search
HomeBackend DevelopmentPHP TutorialA 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 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> 


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> 



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> 



If failed, return

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

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
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment