Home > PHP Framework > ThinkPHP > body text

How to use ThinkPHP6 for Alipay and WeChat payment operations?

PHPz
Release: 2023-06-12 09:46:01
Original
3003 people have browsed it

With the rapid development of mobile Internet, electronic payment plays an increasingly important role in modern life. Alipay and WeChat Pay have become one of the main means of electronic payment in modern society. Therefore, in order for web applications to handle Alipay and WeChat payment smoothly, this article will introduce how to use ThinkPHP 6 for Alipay and WeChat payment operations.

1. Introduce relevant library files

Before using ThinkPHP6 for Alipay and WeChat payment, you first need to introduce relevant library files. I assume here that you have already installed Composer, then use the following command in the console to install the relevant library files:

composer require alipay/easysdk
composer require wechatpay/ wechatpay
composer require guzzlehttp/guzzle

Among them, alipay/easysdk is the Alipay development kit, wechatpay/wechatpay is the WeChat open platform SDK, and guzzlehttp/guzzle is used to API PHP library for making HTTP requests.

2. Alipay payment operation

The main process of Alipay payment process is:

  1. Construct the order information that needs to be paid;
  2. Call Alipay API Initiate a payment request;
  3. The user pays through Alipay;
  4. The Alipay payment result is notified to the merchant server.

The following is an example of using ThinkPHP6 for Alipay payment:

use AlipayEasySDKFactory;

class AlipayController extends Controller
{
    public function index()
    {
        $config = [
            'app_id' => 'your-app-id',
            'private_key' => 'your-private-key',
            'public_key' => 'your-public-key',
            'log' => [
                'file' => './alipay/easy.log',
                'level' => 'debug',
            ],
            'notify_url' => 'http://yourwebsite.com/notify',
            'return_url' => 'http://yourwebsite.com/return'
        ];
        
        $app = Factory::create('payment', $config);
        
        $order = [
            'out_trade_no' => date('YmdHis'),
            'total_amount' => 0.01,
            'subject' => 'test',
        ];
        
        $url = $app->order->page($order, 'http://yourwebsite.com/return');
        
        return $url;
    }
}
Copy after login

In the above code, first we quoted Alipay's EasySDK factory class, which creates a Configured transaction instance. Then, we construct an order array containing order information. Here, we set the order number (out_trade_no), order amount (total_amount) and order subject (subject). Next, we use the order method to initiate a payment request, and finally return the payment URL to the user.

After the payment is completed, Alipay will send a POST request to the merchant server. The request contains some payment information and calls the merchant's notify_url. In the code, notify_url points to an address of the merchant's server, providing the merchant with the ability to process payment results.

3. WeChat payment operation

The main process of WeChat payment process is:

  1. Request prepayment order information from WeChat server;
  2. obtain The prepay_id returned by the WeChat server and generates the signature of the order (please note that the order of signatures is appid, mch_id, nonce_str, prepay_id, trade_type, key);
  3. The client initiates a payment request;
  4. The WeChat payment result is notified to the merchant server.

The following is an example of using ThinkPHP6 for WeChat payment:

use WechatPayGuzzleMiddlewareUtilPemUtil;
use WechatPayNotifyPaidNotify;
use WechatPayOpenAPIV3PayAppPayClient;
use WechatPayOpenAPIV3PayJsPayClient;

class WechatController extends Controller
{
    public function index()
    {
        $merchantId = 'your-mchid';
        $merchantSerialNumber = 'your-serial';
        $merchantPrivateKey = PemUtil::loadPrivateKey('./cert/apiclient_key.pem');
        $wechatpayCertificate = PemUtil::loadCertificate('./cert/wechatpay_certificate.pem');
        $apiV3Key = 'your-key';

        $client = new JsPayClient(
            $merchantId,
            $merchantSerialNumber,
            $merchantPrivateKey,
            $wechatpayCertificate,
            $apiV3Key
        );

        $params = [
            'body' => 'testbody',
            'out_trade_no' => date('YmdHis'),
            'app_id' => 'your-app-id',
            'notify_url' => 'http://yourwebsite.com/wechat_notify',
            'amount' => [
                'total' => 1,
            ],
            'description' => 'test_description',
        ];

        $result = $client->prepare($params);
        $prepayId = $result['prepay_id'];

        $appClient = new AppPayClient(
            $merchantId,
            $merchantSerialNumber,
            $merchantPrivateKey,
            $wechatpayCertificate,
            $apiV3Key
        );

        $packageParams = [
            'prepay_id' => $prepayId,
            'trade_type' => 'JSAPI',
            'timeStamp' => strval(time()),
            'nonceStr' => md5(bin2hex(openssl_random_pseudo_bytes(16))), 
        ];

        $packageParams['sign'] = $appClient->sign($packageParams);

        return json_encode($packageParams); 
    }
}
Copy after login

In the above code, we introduced the GuzzleMiddleware library of WeChat payment and the SDK of the WeChat payment open platform. Then, we set up the merchant ID, merchant serial number, and merchant private key (mchid, serial and key). Next, we construct the payment-related parameters and use the prepare method of JsPayClient to obtain prepay_id. Note that the order of generating order signatures must be in accordance with appid, mch_id, nonce_str, prepay_id, trade_type, and key. Finally, we use the sign method of AppPayClient to generate a signature, serialize all its parameters in JSON and return it to the user.

After the payment is completed, WeChat will send a POST request to the merchant server. The request contains some payment information and calls the merchant's notify_url. In the code, notify_url points to an address of the merchant's server, providing the merchant with the ability to process payment results.

To sum up, this article introduces how to use ThinkPHP6 for Alipay and WeChat payment operations. Please note that this article only provides a basic example, you should handle payment results and exceptions in more detail. If you encounter any problems, please refer to the API documentation of Alipay and WeChat Pay or the information of platforms such as GitHub.

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

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