search
HomePHP FrameworkSwooleHow to use Hyperf framework for WeChat payment

How to use Hyperf framework for WeChat payment

Oct 20, 2023 pm 05:24 PM
useWeChat Payhyperf 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',''),
    ],
];

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;
    }
}

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';
    }
}

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');

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
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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools