Home >Backend Development >PHP Tutorial >How to use PHP to develop the payment function of WeChat official account

How to use PHP to develop the payment function of WeChat official account

PHPz
PHPzOriginal
2023-10-27 10:57:42744browse

How to use PHP to develop the payment function of WeChat official account

How to use PHP to develop the payment function of WeChat official account

With the rapid development of mobile payment, WeChat payment, as one of the most mainstream payment methods in China, has become A necessary payment method for many businesses and individuals. When developing a WeChat public account, if the payment function can be integrated, it will provide users with a more convenient payment method and bring more benefits to the enterprise. This article will introduce how to use PHP to develop the payment function of WeChat official accounts and provide specific code examples.

First of all, we need to understand the basic process of WeChat official account payment. It is mainly divided into the following steps:

  1. The user initiates a payment request in the WeChat official account.
  2. The official account sends the payment request to the WeChat payment platform.
  3. The WeChat payment platform returns the prepayment transaction session ID (prepay_id).
  4. The public account uses prepay_id to generate a signature and returns it to the front end.
  5. The front-end calls up the WeChat payment interface, and the user completes the payment operation.
  6. The WeChat payment platform sends payment result notifications to the public account.
  7. The official account verifies the validity of the notification and processes the payment results.

Next, we will implement the specific code for these steps.

The first step is for the user to initiate a payment request in the WeChat official account. We need to add a payment button to the front-end interface and trigger a payment request when the button is clicked. The specific code is as follows:

<button id="payBtn">支付</button>
<script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
<script>
    document.getElementById('payBtn').addEventListener('click', function() {
        // 调用后端接口获取支付参数
        fetch('/getPayParams.php', {
            method: 'GET'
        })
        .then(response => response.json())
        .then(data => {
            // 调起微信支付界面
            wx.chooseWXPay({
                appId: data.appId,
                timestamp: data.timestamp,
                nonceStr: data.nonceStr,
                package: data.package,
                signType: data.signType,
                paySign: data.paySign,
                success: function(res) {
                    // 支付成功后的操作
                },
                cancel: function(res) {
                    // 用户取消支付
                },
                fail: function(res) {
                    // 支付失败
                }
            });
        });
    });
</script>

In the above code, we use the JS-SDK provided by WeChat to trigger the WeChat payment interface by calling the wx.chooseWXPay method.

In the second step, the official account sends the payment request to the WeChat payment platform. We need to write code on the backend that receives payment requests and sends them to the WeChat payment platform. The specific code is as follows:

<?php
// 获取参数
$totalFee = $_GET['totalFee']; // 支付金额,单位为分,例如100表示1元

// 构造请求数据
$data = [
    'appid' => '公众号的AppID',
    'mch_id' => '商户号',
    'nonce_str' => uniqid(), // 随机字符串
    'body' => '支付测试', // 商品描述
    'out_trade_no' => time(), // 商户订单号
    'total_fee' => $totalFee, // 支付金额
    'spbill_create_ip' => $_SERVER['REMOTE_ADDR'], // 终端IP
    'notify_url' => '支付结果通知的接收地址',
    'trade_type' => 'JSAPI', // 交易类型
    'openid' => '用户的openid'
];

// 生成签名
$data['sign'] = md5(http_build_query($data) . '&key=商户的Key');

// 将请求数据转为XML格式
$xmlData = '<xml>';
foreach ($data as $key => $value) {
    $xmlData .= "<$key>$value</$key>";
}
$xmlData .= '</xml>';

// 发送请求
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.mch.weixin.qq.com/pay/unifiedorder');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
curl_close($ch);

// 解析支付结果
$responseData = simplexml_load_string($response, null, LIBXML_NOCDATA);
if ($responseData->return_code == 'SUCCESS' && $responseData->result_code == 'SUCCESS') {
    $prepayId = $responseData->prepay_id; // 获取预支付交易会话标识
    // 构造返回数据
    $returnData = [
        'appId' => '公众号的AppID',
        'timeStamp' => time(),
        'nonceStr' => uniqid(),
        'package' => 'prepay_id=' . $prepayId,
        'signType' => 'MD5'
    ];
    $returnData['paySign'] = md5(http_build_query($returnData) . '&key=商户的Key');

    echo json_encode($returnData);
} else {
    echo '支付请求失败';
}
?>

In the above code, we first obtain the payment amount and other parameters passed by the front end, then construct the request data, and send the request to the unified order interface of the WeChat payment platform through cURL. Next, we parse the payment result and, if the payment request is successful, return the prepayment transaction session ID (prepay_id) to the front end.

The third step is to open the WeChat payment interface on the front end. The previous code has already implemented this function, we do not need additional code.

The fourth step is that the WeChat payment platform sends payment result notification to the public account. We need to write code on the backend of the official account to receive and process payment result notifications. The specific code is as follows:

<?php
// 接收支付结果通知
$xmlData = file_get_contents('php://input');
$responseData = simplexml_load_string($xmlData, null, LIBXML_NOCDATA);

// 验证通知的有效性
if ($responseData->return_code == 'SUCCESS' && $responseData->result_code == 'SUCCESS') {
    // 处理支付结果
    // do something
    // 返回处理结果给微信支付平台
    echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
} else {
    echo '支付结果通知验证失败';
}
?>

In the above code, we first obtain the XML data of the payment result notification, then parse the data and verify the validity of the notification. If the verification is passed, the payment result is processed, and finally the processing result is returned to the WeChat payment platform.

With the above code, we can use PHP to develop the payment function of WeChat official account. Of course, in the actual development process, factors such as security and user experience also need to be considered and optimized accordingly.

To summarize, using PHP to develop the payment function of WeChat official account requires completing the following steps: add a payment button in the front-end interface and trigger a payment request, the back-end receives the payment request and sends it to the WeChat payment platform, the front-end Open the WeChat payment interface, and the backend receives and processes payment result notifications. Through the code implementation of the above steps, we can easily implement the payment function of WeChat official account.

The above is the detailed content of How to use PHP to develop the payment function of WeChat official account. 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