How 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:
- WeChat developer account
- WeChat payment function Apply to pass
- PHP development environment construction
- WeChat payment SDK
2. WeChat payment process
The process of WeChat payment can be briefly summarized as The following steps:
- The user opens the merchant's payment page and selects the payment method
- The merchant sends the user's order information to WeChat Pay
- WeChat Pay generates 2D code and return it to the merchant
- The merchant displays the QR code to the user
- The user uses WeChat to scan the QR code and complete the payment
- 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
- 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.
- 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.
- 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='data:image/png;base64," . base64_encode(file_get_contents("qrcode.png")) . "' />";
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.
- 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics





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's JIT compilation enhances performance by compiling frequently executed code into machine code, benefiting applications with heavy computations and reducing execution times.

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.

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.

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

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

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.

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