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

How to implement WeChat QR code payment in PHP

Apr 19, 2023 am 09:20 AM

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转换为数组格式
Copy after login

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));
}
Copy after login

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"]);
Copy after login

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; />";
Copy after login

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";
}
Copy after login

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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities. OWASP Top 10 PHP: Describe and mitigate common vulnerabilities. Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP 8 JIT (Just-In-Time) Compilation: How it improves performance. PHP 8 JIT (Just-In-Time) Compilation: How it improves performance. Mar 25, 2025 am 10:37 AM

PHP 8's JIT compilation enhances performance by compiling frequently executed code into machine code, benefiting applications with heavy computations and reducing execution times.

PHP Secure File Uploads: Preventing file-related vulnerabilities. PHP Secure File Uploads: Preventing file-related vulnerabilities. Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

PHP Encryption: Symmetric vs. asymmetric encryption. PHP Encryption: Symmetric vs. asymmetric encryption. Mar 25, 2025 pm 03:12 PM

The article discusses symmetric and asymmetric encryption in PHP, comparing their suitability, performance, and security differences. Symmetric encryption is faster and suited for bulk data, while asymmetric is used for secure key exchange.

PHP Authentication & Authorization: Secure implementation. PHP Authentication & Authorization: Secure implementation. Mar 25, 2025 pm 03:06 PM

The article discusses implementing robust authentication and authorization in PHP to prevent unauthorized access, detailing best practices and recommending security-enhancing tools.

PHP API Rate Limiting: Implementation strategies. PHP API Rate Limiting: Implementation strategies. Mar 26, 2025 pm 04:16 PM

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

PHP Input Validation: Best practices. PHP Input Validation: Best practices. Mar 26, 2025 pm 04:17 PM

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

PHP CSRF Protection: How to prevent CSRF attacks. PHP CSRF Protection: How to prevent CSRF attacks. Mar 25, 2025 pm 03:05 PM

The article discusses strategies to prevent CSRF attacks in PHP, including using CSRF tokens, Same-Site cookies, and proper session management.

See all articles