search
HomeBackend DevelopmentPHP ProblemHow to implement WeChat QR code payment in PHP

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 alt="How to implement WeChat QR code payment in PHP" > tag to display the QR code. The sample code is as follows:

echo "<img  alt="How to implement WeChat QR code payment in PHP" >";

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 alt="How to implement WeChat QR code payment in PHP" > 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
ACID vs BASE Database: Differences and when to use each.ACID vs BASE Database: Differences and when to use each.Mar 26, 2025 pm 04:19 PM

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

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 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 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 Password Hashing: password_hash and password_verify.PHP Password Hashing: password_hash and password_verify.Mar 26, 2025 pm 04:15 PM

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

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 XSS Prevention: How to protect against XSS.PHP XSS Prevention: How to protect against XSS.Mar 26, 2025 pm 04:12 PM

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

PHP Interface vs Abstract Class: When to use each.PHP Interface vs Abstract Class: When to use each.Mar 26, 2025 pm 04:11 PM

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct

See all articles

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

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.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools