Home PHP Framework Swoole How to use Hyperf framework for WeChat payment

How to use Hyperf framework for WeChat payment

Oct 20, 2023 pm 05:24 PM
use WeChat Pay hyperf framework

How to use Hyperf framework for WeChat payment

Use Hyperf framework for WeChat payment

Introduction:
With the development of e-commerce, WeChat payment has become one of the main ways for people to shop and pay in daily life. . In development, how to quickly integrate WeChat payment becomes particularly important. This article will introduce how to use the Hyperf framework for WeChat payment and provide specific code examples.

Text:

1. Preparation work
Before using the Hyperf framework for WeChat payment, some preparation work is required. First, register a WeChat payment account and obtain merchant number, application key and other information. Secondly, install the Hyperf framework. You can use Composer to install it and execute the command: composer create-project hyperf/hyperf-skeleton. Finally, install the WeChat payment SDK library. You can use Composer to install it and execute the command: composer require overtrue/wechat.

2. Configuration file
In the Hyperf framework, the configuration file is located in the config/autoload directory. In the configuration file, fill in the WeChat payment-related configuration items correctly, including merchant number, application key, etc. The sample configuration is as follows:

return [
    'wechat' => [
        'app_id' => env('WECHAT_APPID', ''),
        'mch_id' => env('WECHAT_MCH_ID', ''),
        'key' => env('WECHAT_KEY', ''),
        'cert_path' => env('WECHAT_CERT_PATH',''),
        'key_path' => env('WECHAT_KEY_PATH',''),
        'notify_url' => env('WECHAT_NOTIFY_URL',''),
    ],
];
Copy after login

3. Create a WeChat payment service class
In the Hyperf framework, you can create a WeChat payment service class to encapsulate payment-related methods. The sample code is as follows:

<?php

declare(strict_types=1);

namespace AppService;

use EasyWeChatPaymentApplication;

class WechatPayService
{
    protected $app;

    public function __construct()
    {
        $config = config('wechat');
        $this->app = new Application($config);
    }

    public function createOrder(string $orderNo, float $totalAmount, string $description)
    {
        $result = $this->app->order->unify([
            'out_trade_no' => $orderNo,
            'body' => $description,
            'total_fee' => $totalAmount * 100,
            'trade_type' => 'APP',
        ]);

        if ($result['return_code'] === 'SUCCESS' && $result['result_code'] === 'SUCCESS') {
            $prepayId = $result['prepay_id'];
            $jssdkParams = $this->app->jssdk->appConfig($prepayId);

            return [
                'prepay_id' => $result['prepay_id'],
                'jssdk_params' => $jssdkParams,
            ];
        } else {
            throw new Exception($result['return_msg']);
        }
    }

    public function notify(array $data)
    {
        $response = $this->app->handlePaidNotify(function ($message, $fail) {
            // 处理支付回调
            // 更新订单状态,发货等操作
            return true; // 返回处理结果, true 或 false
        });

        return $response;
    }
}
Copy after login

4. Call the payment interface
Wherever WeChat payment needs to be called, instantiate the WeChat payment service class and call the corresponding method. The sample code is as follows:

<?php

declare(strict_types=1);

namespace AppController;

use AppServiceWechatPayService;
use HyperfHttpServerAnnotationController;
use HyperfHttpServerAnnotationPostMapping;
use HyperfHttpServerContractRequestInterface;

/**
 * @Controller()
 */
class PayController
{
    /**
     * @PostMapping(path="/pay")
     */
    public function pay(RequestInterface $request, WechatPayService $payService)
    {
        $orderNo = $request->input('orderNo');
        $totalAmount = $request->input('totalAmount');
        $description = $request->input('description');

        try {
            $result = $payService->createOrder($orderNo, $totalAmount, $description);
            // 返回给前端APP的支付参数
            return $result;
        } catch (Exception $e) {
            // 处理异常错误
            return [
                'error' => $e->getMessage(),
            ];
        }
    }

    /**
     * @PostMapping(path="/notify")
     */
    public function notify(RequestInterface $request, WechatPayService $payService)
    {
        $payService->notify($request->all());
        // 处理支付回调结果

        return 'success';
    }
}
Copy after login

5. Configure routing
Configure routing and bind the payment interface and callback interface to the corresponding controller method. The sample code is as follows:

<?php

declare(strict_types=1);

use HyperfHttpServerRouterRouter;

Router::addRoute(['POST'], '/pay', 'App\Controller\PayController@pay');
Router::addRoute(['POST'], '/notify', 'App\Controller\PayController@notify');
Copy after login

Summary:
This article introduces how to use the Hyperf framework for WeChat payment and provides specific code examples. By setting WeChat payment related parameters through the configuration file and creating a WeChat payment service class, you can easily call the payment interface and call back the payment results. I hope this article will be helpful to developers who integrate WeChat Pay during the development process.

The above is the detailed content of How to use Hyperf framework for WeChat payment. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

If you forget your WeChat payment password, how to retrieve it? If you forget your WeChat payment password, how to retrieve it? Feb 23, 2024 pm 09:40 PM

In WeChat, users can enter their payment password to make purchases, but how do they retrieve their payment password if they forget it? Users need to go to My-Services-Wallet-Payment Settings-to recover their payment password if they forget it. This introduction to how to retrieve your payment password if you forget it will tell you the specific operation method. The following is a detailed introduction, so take a look! WeChat usage tutorial. How to find the WeChat payment password if you forget it? Answer: My-Service-Wallet-Payment Settings-Forgot payment password. Specific method: 1. First, click My. 2. Click on the service inside. 3. Click on the wallet inside. 4. Find the payment settings. 5. Click Forgot payment password. 6. Enter your own information for verification. 7. Then enter the new payment password to change it.

How to set up WeChat payment for Meituan Takeout How to set up WeChat payment How to set up WeChat payment for Meituan Takeout How to set up WeChat payment Mar 12, 2024 pm 10:34 PM

There are many food and snack shops provided in the Meituan takeout app, and all mobile phone users log in through their accounts. Add your personal delivery address and contact number to enjoy the most convenient takeout service. Open the homepage of the software, enter product keywords, and search online to find the corresponding product results. Just swipe up or down to purchase and place an order. The platform will also recommend dozens of nearby restaurants with high reviews based on the delivery address provided by the user. The store can also set up different payment methods. You can place an order with one click to complete the order. The rider can arrange the delivery immediately and the delivery speed is very fast. There are also takeout red envelopes of different amounts for use. Now the editor is online in detail for Meituan takeout users. We show you how to set up WeChat payment. 1. After selecting the product, submit the order and click Now

What software is crystaldiskmark? -How to use crystaldiskmark? What software is crystaldiskmark? -How to use crystaldiskmark? Mar 18, 2024 pm 02:58 PM

CrystalDiskMark is a small HDD benchmark tool for hard drives that quickly measures sequential and random read/write speeds. Next, let the editor introduce CrystalDiskMark to you and how to use crystaldiskmark~ 1. Introduction to CrystalDiskMark CrystalDiskMark is a widely used disk performance testing tool used to evaluate the read and write speed and performance of mechanical hard drives and solid-state drives (SSD). Random I/O performance. It is a free Windows application and provides a user-friendly interface and various test modes to evaluate different aspects of hard drive performance and is widely used in hardware reviews

How to download foobar2000? -How to use foobar2000 How to download foobar2000? -How to use foobar2000 Mar 18, 2024 am 10:58 AM

foobar2000 is a software that can listen to music resources at any time. It brings you all kinds of music with lossless sound quality. The enhanced version of the music player allows you to get a more comprehensive and comfortable music experience. Its design concept is to play the advanced audio on the computer The device is transplanted to mobile phones to provide a more convenient and efficient music playback experience. The interface design is simple, clear and easy to use. It adopts a minimalist design style without too many decorations and cumbersome operations to get started quickly. It also supports a variety of skins and Theme, personalize settings according to your own preferences, and create an exclusive music player that supports the playback of multiple audio formats. It also supports the audio gain function to adjust the volume according to your own hearing conditions to avoid hearing damage caused by excessive volume. Next, let me help you

Can Xianyu pay with WeChat? How to change to WeChat payment method? Can Xianyu pay with WeChat? How to change to WeChat payment method? Mar 12, 2024 pm 12:19 PM

When everyone has nothing to do, they will choose to browse the Xianyu platform. Everyone can find that there are a large number of products on this platform, which can allow everyone to see various second-hand products. Although these products are second-hand products, there is absolutely no problem with the quality of these products, so everyone can buy them with confidence. The prices are very affordable, and they still allow everyone to face-to-face with these products. It is entirely possible for sellers to communicate and conduct some price bargaining operations. As long as everyone negotiates properly, then you can choose to conduct transactions, and when everyone pays here, they want to make WeChat payment, but it seems that the platform It's not allowed. Please follow the editor to find out what the specific situation is. Xianyu

How to use Baidu Netdisk app How to use Baidu Netdisk app Mar 27, 2024 pm 06:46 PM

Cloud storage has become an indispensable part of our daily life and work nowadays. As one of the leading cloud storage services in China, Baidu Netdisk has won the favor of a large number of users with its powerful storage functions, efficient transmission speed and convenient operation experience. And whether you want to back up important files, share information, watch videos online, or listen to music, Baidu Cloud Disk can meet your needs. However, many users may not understand the specific use method of Baidu Netdisk app, so this tutorial will introduce in detail how to use Baidu Netdisk app. Users who are still confused can follow this article to learn more. ! How to use Baidu Cloud Network Disk: 1. Installation First, when downloading and installing Baidu Cloud software, please select the custom installation option.

How to use NetEase Mailbox Master How to use NetEase Mailbox Master Mar 27, 2024 pm 05:32 PM

NetEase Mailbox, as an email address widely used by Chinese netizens, has always won the trust of users with its stable and efficient services. NetEase Mailbox Master is an email software specially created for mobile phone users. It greatly simplifies the process of sending and receiving emails and makes our email processing more convenient. So how to use NetEase Mailbox Master, and what specific functions it has. Below, the editor of this site will give you a detailed introduction, hoping to help you! First, you can search and download the NetEase Mailbox Master app in the mobile app store. Search for "NetEase Mailbox Master" in App Store or Baidu Mobile Assistant, and then follow the prompts to install it. After the download and installation is completed, we open the NetEase email account and log in. The login interface is as shown below

Sharing the steps to apply for a refund with WeChat Pay Sharing the steps to apply for a refund with WeChat Pay Mar 25, 2024 pm 06:31 PM

1. First, we need to open the WeChat APP on the mobile phone, and then click to log in to the WeChat account, so that we enter the WeChat homepage. 2. Click the [Me] button in the lower right corner of the WeChat homepage, then select the [Payment] option. We click to enter the payment page. 3. After entering the [Payment] page, click the [Wallet] option to enter, and click [Bill] in the upper right corner of the [Wallet] page.

See all articles