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

How to use Hyperf framework for WeChat payment

王林
Release: 2023-10-20 17:24:43
Original
1254 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template