Table of Contents
A brief discussion on the process of developing WeChat payment using PHP, a brief discussion on the php payment process
Home Backend Development PHP Tutorial A brief discussion on the process of using PHP to develop WeChat payment, a brief discussion on the PHP payment process_PHP tutorial

A brief discussion on the process of using PHP to develop WeChat payment, a brief discussion on the PHP payment process_PHP tutorial

Jul 12, 2016 am 09:07 AM
php WeChat Pay

A brief discussion on the process of developing WeChat payment using PHP, a brief discussion on the php payment process

The following uses PHP language as an example to explain the development process of WeChat payment.

1. Get order information

2. Generate sign based on order information and payment-related account number, and generate payment parameters

3. POST the payment parameter information to the WeChat server and obtain the return information

4. Generate the corresponding payment code (within WeChat) or payment QR code (not within WeChat) based on the returned information to complete the payment.

The following is a step-by-step explanation:

1. There are three necessary order parameters related to WeChat payment, namely: body (product name or order description), out_trade_no (usually order number) and total_fee (order amount, unit "cent", pay attention to the unit Question), in different applications, the first thing to do is to obtain the relevant information in the order to prepare for the generation of payment parameters.

2. Other necessary payment parameters include appid (WeChat appid), mch_id (notified after the application is successful), device_info (the parameters on the web and WeChat sides are the same, capitalized "WEB"), trade_type (according to This value is also different in different usage scenarios. It is "NATIVE" outside WeChat and "JSAPI" inside WeChat), nonce_str (32-bit random string), spbill_create_ip (the terminal IP that initiates the payment, that is, the server IP), notify_url (payment Callback address, the WeChat server notifies the website whether the payment is completed or not, modify the order status), sign (signature), and there is another point that needs to be explained. If trade_type is JSAPI, openid is a required parameter.

The signature algorithm is prone to errors because the signing steps are cumbersome. In fact, the most important thing is that sign does not participate in the signature

A: Assign the parameters mentioned in 1 and 2 except sign into an array array, and sort them in dictionary order. In fact, the key values ​​are sorted in the order of A-Z.

B: Convert the array into a string string in the format k1=v1&k2=v2&...kN=vN

C: Add the KEY value after this string (set by the user in the WeChat payment merchant backend). Now string = k1=v1&k2=v2&...kN=vN&key=KEY.

D:string = md5(string)

E: sign = strtoupper(string)

At this point, the sign is generated.

Add sign to the array array to generate a new array. Convert this array to XML. At this point, the parameter preparation work for WeChat payment is completed.

3. Use POST to send the XML generated in 2 to WeChat (https://api.mch.weixin.qq.com/pay/unifiedorder), obtain the returned XML information, and convert the information into array format for easy operation. The returned XML information is as follows:

<xml>
 <return_code><![CDATA[SUCCESS]]></return_code>
 <return_msg><![CDATA[OK]]></return_msg>
 <appid><![CDATA[wx2421b1c4370ec43b]]></appid>
 <mch_id><![CDATA[10000100]]></mch_id>
 <nonce_str><![CDATA[IITRi8Iabbblz1Jc]]></nonce_str>
 <sign><![CDATA[7921E432F65EB8ED0CE9755F0E86D72F]]></sign>
 <result_code><![CDATA[SUCCESS]]></result_code>
 <prepay_id><![CDATA[wx201411101639507cbf6ffd8b0779950874]]></prepay_id>
 <trade_type><![CDATA[JSAPI]]></trade_type>
</xml> 

Copy after login


If it is trade_type==native payment, there will be an additional parameter code_url, which is the address of WeChat scan code payment.

4. The following is the payment process.

If trade_type==native, then use some methods to convert the code_url into a QR code, and just use WeChat to scan the code. If it is click-to-pay within WeChat, you need to call the relevant things in WeChat js-sdk. This step The most important thing is to generate a string in json format.

First, generate the array_jsapi that converts the json string.

A: The parameters of this array include: appId, timeStamp, nonceStr, package, signType (default is "MD5"). Please note that the case is different from the above array.

B: Use this array to generate paySign parameters. The signature method is the same as above.

C: Append the paySign parameter to the array_jsapi array.

D: Format the array into a string js_string using json_encode.

After completing the above work, you can make payment within WeChat.

The following is a sample code for related payments:

<script type='text/javascript'>
         function jsApiCall()
     {
      WeixinJSBridge.invoke(
       'getBrandWCPayRequest',
       $js_string,
       function(res){
        WeixinJSBridge.log(res.err_msg);
         if(res.err_msg=='get_brand_wcpay_request:ok')
         {
          alert('支付成功');
         }
         else
         {
          alert('支付失败');
         }
       }
      );
     }
     function callpay()
     {
      if (typeof WeixinJSBridge == 'undefined'){
       if( document.addEventListener ){
        document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
       }else if (document.attachEvent){
        document.attachEvent('WeixinJSBridgeReady', jsApiCall); 
        document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
       }
      }else{
       jsApiCall();
      }
     }
    </script> 



Copy after login

The js_string in the code is the string we generated.

Call the callpay() function in HTML code to initiate payment.

In this way, the payment work of WeChat Pay is completed.

The following is the callback work. This function ensures that the correct status is displayed to the user after the order payment is successful.

After the payment is completed, WeChat uses a POST request to feedback the payment results to the website server. The website server obtains the POST information and determines whether to modify the order information based on whether the payment is successful or not.

A: Remove the sign in the POST parameter and record the value.

B: Sign the remaining parameters

C: Compare the signature result with the sign in POST. If the signature is the same, it means the signature is correct. Modify the order status according to the payment result.

E: Return XML information to WeChat to ensure that WeChat knows that the website has received the notification and prevent WeChat from pushing POST again. The example is as follows:

<xml>
 <return_code><![CDATA[SUCCESS]]></return_code>
 <return_msg><![CDATA[OK]]></return_msg>
</xml> 



Copy after login

If failed, return

<xml>
 <return_code><![CDATA[FAIL]]></return_code>
 <return_msg><![CDATA[失败原因]]></return_msg>
</xml> 

Copy after login

At this point, the entire development of WeChat Payment is introduced.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1058152.htmlTechArticleA brief discussion on the process of using PHP to develop WeChat payment. A brief discussion on the php payment process. Let’s take the PHP language as an example to describe the WeChat payment process. The payment development process will be explained. 1. Obtain order information 2. According to the order letter...
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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles