Home  >  Article  >  Backend Development  >  How to implement WeChat QR code payment in PHP

How to implement WeChat QR code payment in PHP

PHPz
PHPzOriginal
2023-04-19 09:20:412028browse

With the popularity of mobile payment, WeChat has become one of the most widely used payment methods in China. WeChat Pay provides a variety of payment methods, and QR code payment is also welcomed by more and more users. This article will introduce how to use PHP to implement WeChat QR code payment.

1. Prerequisites

Before you start, you need to prepare the following conditions:

  1. WeChat developer account
  2. WeChat payment function Apply to pass
  3. PHP development environment construction
  4. WeChat payment SDK

2. WeChat payment process

The process of WeChat payment can be briefly summarized as The following steps:

  1. The user opens the merchant's payment page and selects the payment method
  2. The merchant sends the user's order information to WeChat Pay
  3. WeChat Pay generates 2D code and return it to the merchant
  4. The merchant displays the QR code to the user
  5. The user uses WeChat to scan the QR code and complete the payment
  6. WeChat Pay sends payment result notification to the merchant

In order to implement WeChat QR code payment, we need to complete the corresponding steps in sequence according to the above process.

3. Implementation steps

  1. Create payment order

On the merchant website, the user needs to fill in the order information and select the WeChat payment method. After the user submits the order, the merchant needs to send the order information to WeChat Pay.

In PHP, we can use the CURL library to send POST requests to the WeChat payment API. The following is a sample code:

$url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
$fields = array(
    "appid" => "YOUR_APP_ID", // 公众号ID或应用ID
    "mch_id" => "YOUR_MCH_ID", // 商户号
    "nonce_str" => uniqid(), // 随机字符串
    "out_trade_no" => "YOUR_ORDER_NUMBER", // 商户订单号
    "total_fee" => "YOUR_ORDER_AMOUNT", // 订单金额,单位为分
    "spbill_create_ip" => $_SERVER["REMOTE_ADDR"], // 用户端实际ip
    "notify_url" => "YOUR_NOTIFY_URL", // 支付通知回调地址
    "trade_type" => "NATIVE", // 交易类型,NATIVE为扫码支付
    "product_id" => "PRODUCT_ID", // 商品ID
);
$fields["sign"] = make_sign($fields, "YOUR_MCH_KEY"); // 签名字段
$xml = array_to_xml($fields); // 将数组转换为XML格式
$response = curl_post($url, $xml); // 发送POST请求
$result = xml_to_array($response); // 将响应XML转换为数组格式

In the above code, we use the following functions:

  • uniqid() is used to generate a unique Random string
  • make_sign() Used to generate signature
  • array_to_xml() Convert array to XML format
  • curl_post() Send POST request
  • xml_to_array() Convert XML to array format

Among them, the code generated by the signature is as follows:

function make_sign($fields, $key) {
    $string = "";
    ksort($fields);
    foreach ($fields as $k => $v) {
        if ($k != "sign" && $v != "" && !is_array($v)) {
            $string .= $k . "=" . $v . "&";
        }
    }
    $string .= "key=" . $key;
    return strtoupper(md5($string));
}

It should be noted that the merchant number and API key can be obtained on the WeChat Pay merchant platform.

  1. Generate QR code

After obtaining the response from WeChat Pay, the merchant needs to parse the QR code link in the response and generate a QR code. In PHP, we can use the PHPQRCode library to generate QR codes. The sample code is as follows:

require_once("phpqrcode.php");
QRcode::png($result["code_url"]);

In the above code, we first introduced the PHPQRCode library. Then, use its QRcode::png() method to generate a QR code.

  1. Display QR code

After generating the QR code, the merchant needs to display it to the user. In PHP, we can use the <img> tag to display the QR code. The sample code is as follows:

echo "<img src=&#39;data:image/png;base64," . base64_encode(file_get_contents("qrcode.png")) . "&#39; />";

In the above code, we read the QR code file as binary data , and Base64 encode it. Then, use the encoded data as the URL of the image, and use the <img> tag to display the QR code.

  1. Payment result notification

After the user completes the payment, WeChat Pay will push the payment result to the merchant's payment result notification URL. After receiving the notification, the merchant needs to verify the validity of the notification and update the order status based on the payment result in the notification. The sample code for PHP is as follows:

$xml = file_get_contents("php://input");
$data = xml_to_array($xml);
if (check_sign($data, "YOUR_MCH_KEY")) {
    if ($data["return_code"] == "SUCCESS" && $data["result_code"] == "SUCCESS") {
        // 修改订单状态
        // ...
        echo "SUCCESS";
    } else {
        echo "FAIL";
    }
} else {
    echo "FAIL";
}

In the above code, we first use file_get_contents("php://input") to read the XML data in the POST request body and convert it Convert to array format. Then, use the check_sign() function to verify the validity of the signature. Finally, the order status is updated based on the payment result and a "SUCCESS" or "FAIL" response is sent to WeChat Pay.

4. Summary

This article introduces how to use PHP to implement WeChat QR code payment. During the implementation process, you need to pay attention to the details of the WeChat payment process and use PHP related functions and libraries reasonably. I hope this article can provide you with some help when implementing WeChat payment.

The above is the detailed content of How to implement WeChat QR code payment in PHP. 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