I. Background introduction

As an Android developer, from the initial stumbling to now a little understanding, which has experienced a bitter and happy process is also a pain. In this process, I have been constantly learning from my predecessors and friends at work and on the Internet. I have enriched myself time and time again, learned new things and solved new problems. My heart is very grateful. At the same time, in this process, also slowly accumulated some of their own experience, while there is a little spare time, share, I hope to help friends in need. Because my technical ability is limited, if the article has a lack of improper place, but also hope to correct.

In the recent development work, I re-connected wechat Pay, and finally completed the process of participating in the account setting on the open platform, the code writing on the APP side and the server side, which can be seen as a clear overall process of wechat pay, and gained a greater understanding of how to avoid pit and error minesweeping. Access still remember the last time a year ago, when the main role is limited to the APP development work, although is APP side leading development, but not from the global from the whole to participate in, so part of the process and concept or a indefinitely until a state (the final APP detail letter payment is successful, but it is also much didn’t). Therefore, I write down the article here to record what I know and feel, and I hope to make personal notes and new reference.

The main purpose of this article is not to introduce how to plug into wechat Pay to quickly complete the code development. I believe the answer to this question is well written in wechat’s official development documentation and on the Internet. If you are new to wechat Pay access and have not read the official development documentation, you will have a lot of confusion when reading this article; But if you’re already in the process of plugging in and are familiar with the official development documentation, some parts of this article will give you a sense of clarity. As the title suggests, the purpose of this paper is to illustrate WeChat pay the division of Labour cooperation, focus on from the WeChat pay open platform APP information set] to [get prepaid id information server backstage] to [APP side to initiate payment requests after server information 】 until (till) the final notice 】 【 server and the client paid success of such a process, During this process, the areas needing attention will be inserted in the form of Tips at appropriate locations, hopefully for reference in error mine-clearing manuals. Because this article is aimed at developers, especially Android developer, might account application and APP Settings link, server background processing process link most people did not go to participate in, based on the principle of check leakage fill a vacancy, so these two will be a more detailed description of the APP access code segment is mainly about the description of the theory, Does not involve the specific code implementation, if interested can leave a message for communication.

Ii. Division of labor and cooperation process

2.1 Account Application and APP Settings

2.1.1 Account Application

Open the login address of the wechat Pay open platform and select an access scenario for access according to the application process of wechat Pay. For example, the access process of APP payment is as follows:

1. Register an open platform account

2. Certified developer qualification

3. Create APP and submit it for approval (Tips: Set APP keystore signature)

4. Submit information to apply for wechat Payment

5. If the account is successfully opened, log in to the merchant platform for verification

6. Sign agreements online

7. Start design and development




Wechat Payment APP access process

2.1.2 APP Settings

After the approval of the wechat Pay application, the merchant will receive an email sent by the wechat Pay assistant in the mailbox filled in the application information, which contains the payment account information required for development.




Wechat Pay application has been approved by email

After receiving the email, you need to log in to the wechat merchant platform to set the API payment key.




Set the API payment key

Tips: You can verify the validity of wechat Pay account and API key through the interface debugging tool of wechat public platform. Specific methods are as follows:

1. Open the interface debugging tool page of wechat public platform and select the “Custom” option for the interface

2. Fill in the required parameters of wechat Pay and their value (note: case sensitive) and merchant Key (i.e. API Key).

3. Click Generate signature to get unified single interface parameter data

4. Fill the parameter data of the unified ordering interface into a POST request tool (such as Chrome plugin Postman), and submit a POST request to the unified ordering interface address. If the pre-payment ID can be obtained normally, it indicates that the wechat Pay account and API key are valid (Tips: Except appID, McH_id, trade_type and merchant Key, other parameter values can be filled in arbitrarily, as long as they conform to the field type definition, which will not affect the final result of obtaining the pre-payment ID. For example, the notify_URL parameter, if it doesn’t already have its own notification callback page, can be filled in with something like http://www.baidu.com). Otherwise, please go back to the previous steps to check whether the payment account has the APP payment function and whether the API key is set.







POST requests prepayment ID information

At this point, wechat pay account preparation work is completed, you can start the next step of code development.

2.2 Code development process




Wechat Payment business flow chart

Now that you have your wechat Pay account ready and have confirmed that the account’s payment authority and API key Settings are correct, you can start code development. Pictured above is WeChat WeChat payments in the official documentation, business flow diagram, you can see from the diagram that the code development server and APP side, the server is responsible for the payment before the order generation, data acquisition and payment after the order status updates, APP side is responsible for the payment request, in short, the server is responsible for the payment early, late, APP is responsible for the midterm.

2.2.1 Server interface development

The initial work of the server interface is:

1. Generated internal orders, called the unified ordering interface, and obtained the pre-payment ID information

The server generates an internal order in the database according to the product ID and user ID information sent by APP, and then generates unified ordering interface parameters by using the order information and wechat Pay account information, and calls the unified ordering interface to obtain the pre-payment ID. The required interface parameters are shown in the figure.




APP payment unified ordering interface Mandatory parameter

The fixed part is the parameter that is fixed and unchanged every time the interface is called (not all the values are written out, but every time the order is called), the trade_type value APP indicates that APP payment is connected (JSAPI is entered if it is JSAPI payment), and notify_URL is the payment callback page. This page belongs to the payment results monitoring part of the later work (Tips: Spbill_create_ip = spbill_create_IP = spbill_create_IP = spbill_create_IP = spbill_create_IP = spbill_create_IP = spbill_create_IP Will not affect the result of obtaining the pre-payment ID, but it is recommended to fill in the server external IP address).

The account part is the wechat Pay account information part applied, which mainly provides appID and McH_id (Tips: Appid and McH_id are one-to-one and cannot be used staggers. An AppID must correspond to the merchant McH_id signed by the appID when applying for the account; otherwise, the pre-payment ID information cannot be obtained successfully. Appid and McH_id can be configured in the background configuration table. In general, these two values will not change when the same APP calls the unified ordering interface each time. However, it does not exclude the requirement that payment objects are different for different orders, so you can configure account information based on business requirements.

The content of the goods section is the information of the goods to be paid for, and out_trade_no is the internal order ID generated by the server (Tips: this ID is returned in the payment callback page to update the order status, so it needs to be unique in the internal order system). The body field is the product description section, which is used for display in wechat Payment confirmation (Tips: The type definition of this field is String(128), so the field length should not exceed 128 characters). The total_fee field is the price of the commodity, whose unit is minute and type is int. For example, total_fee = 666, the default value is ¥6.66.

The validation part provides security. The nonce_str field is a random string. The purpose is to increase randomness and make the sign field after the signature unpredictable, making interception impossible to crack. Nonce_str can be a 16-bit random string, a 32-bit random string, or any other random string of less than or equal to 32 bits. The nonce_str field should be regenerated before each signature, otherwise it loses its meaning. Its character length, character type set, and whether it is regenerated or used before signing will not affect the success of obtaining the pre-payment ID. However, it is necessary to ensure that the value of nonce_str when signing the sign field and the nonce_str parameter passed to wechat are the same. After the pre-payment ID result is obtained, the nonce_str at the time of signing the sign field must be the same as the result parameter nonce_str returned to the front end, otherwise there will be a signature error problem. The sign field is a key to the whole parameter. It ensures the security of the parameter transmission and receipt and ensures that the parameters are not modified during the transmission from sender to receiver. It generate rules in the introduction to the inside of the official document have agreed to all the parameters passed in the past, in addition to sign field parameters, other parameters field should be carried out in accordance with the parameter name ASCII dictionary sequence smallest to joining together into a string, and then at the end of the string splicing API keys, end up with a bunch of joining together the parameters of the API key chain string, MD5 is used to encrypt the parameter chain string into a 32-bit capital letter string, and the final value of the sign field is obtained. Just think, if a hacker wants to change the original price of 100 yuan to 0.01 yuan by intercepting the modification, that is, change total_fee = 10000 to Total_fee = 1, and then send it to wechat. Then the sign field obtained by wechat after splicing parameters into parameter chains for signature in the verification process is different from the original sign field of parameters, and it will prompt a signature error exception and refuse to accept the request. However, if a hacker wants to change the price and forge the sign field again to pass wechat authentication, he must know the API key, which is only available on the server side and wechat side and does not spread through the network, so there is no way for the hacker to do anything. Therefore, the API key must be properly kept on the server side, and cannot be transmitted to the APP client through the network, let alone built-in in the APP client).

2. Request unified single interface for data acquisition and processing

After the parameters are generated on the server side, the unified ordering interface is called to obtain the result returned by the interface containing the pre-payment ID. In this case, two operations need to be done:

(1) Verify the signature of the result returned by the interface

As mentioned in the analysis of the sign field above, this field ensures the security of data transmission and reception. Therefore, when receiving the data returned by the interface, this field should be verified. All parameters are removed from the sign field and then spliced into parameter chain string with API key in sequence, and then signed by MD5 method. The new 32-bit uppercase MD5 string sign signature is obtained, and the sign field returned by wechat is compared with the re-signed sign. If it is consistent, it indicates that the parameters are accurate and have not been tampered with, otherwise there must be a problem in some link (Tips: Must be good at using WeChat public platform interface debugging tool for screening problem, if the signature method and parameter fields are no problem, but the debugging tools to get sign values and parameters of the original sign values are not consistent, so, ha ha ha, congratulations you, you are targeted by hackers, otherwise please check your signature method and parameter fields are one-to-one correspondence).

(2) Generate and sign the parameters required for APP front-end call payment and return them to the front-end

After the signature verification is correct, the data returned by the unified ordering interface is used to generate the front end to call the required fields of payment, and these fields are signed at the same time. For example, the parameters required for Android APP payment are as follows:




Fields required by wechat Payment for Android APP

Fill in appID, McH_id, prepayID, packageValue, and regenerate nonCESTr and TIMESTAMP. Then arrange these parameters and add API key to form parameter chain string. MD5 signature is performed on the string to obtain sign field. Finally all these fields can be returned to the front end (when interacting with WeChat, its naming rules must be carried out in accordance with the official document WeChat definition, and interact with the APP, its parameters whether key names with an underscore, is in line with the hump, named does not affect the naming conventions here mainly both the server and APP front end. I can only use the name of the server interface to define it, so you don’t have to go too far.

At this point, the preliminary work on the server interface is complete. Let’s take a look at what the server interface does in the post-payment phase.

The later work of the server interface is to write the payment callback page, receive the payment callback successfully and modify the order status, and return the order processing completion information to wechat

A notifY_URL callback page needs to be filled in when invoking the unified order interface, which is the processing page for monitoring the notification of successful payment. In essence, it is a call interface for wechat server after successful payment. In this page, there are three main things to do:

(1) Verify the security of incoming interface parameters

When wechat calls this page, the following information will be passed:




Wechat Pay callback page receiving parameters

When the callback page receives these parameter data, it needs to verify result_code and return_code first. Only when both are SUCCESS, the payment is successfully completed. Otherwise, there is a problem in a link of payment, please troubleshoot the error according to the wechat Payment error code.

After verifying that the payment is successfully completed, it is necessary to verify the security of the sign signature field, and its verification rules are consistent with those in the previous work. If this validates, you can change the order status to paid based on the out_trade_NO field. Otherwise, a validation error message is returned to the wechat server (skip to step 3 below).

(2) Modify the order status

After verification through, then according to amend the order status as paid out_trade_no field condition, if all goes well, the revision process you can return to handle a successful WeChat server information, or if the order to modify the problems appeared in the process of (such as order no longer exists), then return order processing WeChat server failure information.

(3) Reply to the wechat server to complete the processing information

In the process of parameter verification and order processing, whether successful or not, a processing completion message needs to be returned to the wechat server, and its return format is shown in the figure below:




Parameters returned to the wechat server

If an error occurs during the callback page processing, troubleshoot the error. If there are no errors and the callback request is successfully processed, the order payment completes smoothly. (Tips: The callback page must be accessible from the Internet before it can be invoked by the wechat server. Otherwise, please simulate data for invocation during debugging.)

At this point, the post-work on the server interface is complete. And the whole wechat payment development process, the work of the server is also completed.

2.2.2 APP code development

APP is mainly responsible for the mid-term work in the whole wechat Pay, which includes two aspects:

1. Call the server interface to obtain the pre-payment ID and other information

When the user clicks the payment button, APP invokes the interface of the server, passes the user ID and commodity ID to the server as parameters, and obtains the returned data including the sign signature field (that is, the returned data of the last step in the server’s early work) to initiate wechat payment request.

2. Use wechat API to call wechat client for wechat payment

After obtaining the pre-payment ID and other information, the user can call the API in the wechat Pay SDK and initiate a payment request. The wechat Pay confirmation page pops up, requiring the user to enter the password for payment.

At this point, the APP end has completed the mid-term work of payment.

In fact, the APP side also has a payment post work. Because it is also mentioned in the previous wechat payment flow chart, the wechat payment result notification, in addition to the server, will also be to the APP end, so the APP end of this late work is to monitor the wechat payment result notification. The APP side listens to the payment result by creating a new package folder under the name of the project package, which must be named “wxAPI”, and creating a new Activity under the name of the package, which should also be named “WXPayEntryActivity”. The Activity implements the IWXAPIEventHandler interface, and don’t forget to declare the Activity in the manifest file. Wechat will call back the Activity’s onResp method in the payment result notification to inform the Activity of the payment result, and the Activity will respond to the three results in this method respectively (the three results are: Resp.errcode == 0 indicates that the payment is successful, resp.errCode == -1 indicates that the payment is incorrect, and resp.errCode == -2 indicates that the payment is canceled.

Tips: If there is an error in the payment result, resp.errcode == -1, then the possible cause is:

1. The signature is incorrect

The application signature information configured when creating APP on wechat Pay open platform is incorrect. Please correct the application signature information with the signature keystore officially issued. Or, if you do not pack the signature APK, use the official release signature keystore to sign the APK and then test it again.

2. Unregistered APPID and project SettingsappidIncorrect or registeredappidDoes not match the background SettingsappidThere is no mobile payment application function

Check the code first to see if the API is called to register the APPID with wechat before initiating the payment request. If the code is registered with appID, then contact the relevant personnel of server development and account application to check and compare the value of appID, confirm whether appID and merchant McH_id correspond one by one, and confirm whether the application applies for wechat payment function.

3. The login of the wechat client is interrupted

Current WeChat client login status may have been offline the other devices, but the user is not in the device to login WeChat, then need to prompt the user to login WeChat address (once encountered in the process of development of the problem, then use the simulator test and cell phone at the same time, a began to win, to a successful call every time payment interface, However, the cross-testing between the simulator and the phone sometimes failed. Later, I found this rule in the process of reoccurrence of the problem, which turned out to be caused by the current device’S wechat login status being pushed offline.)

4. Check whether the wechat client is installed and whether the version supports wechat Pay is not carried out.

Before initiating a payment request, the wechat Payment API should be called to judge whether wechat is installed and whether the installed wechat version supports wechat Payment. If it is not installed, it will prompt the user to install it; if the wechat version does not support payment, it will prompt the user to upgrade wechat (Tips: Some play the Android player, often by software, such as green guardian will WeChat client greening, cause WeChat actual is installed on a mobile phone, but couldn’t via WeChat API if it support payments as a result, so here on tip can be modified to “please start or upgrade your WeChat client to complete WeChat payment”).

5. Other exceptions.

to be continue

At this point, wechat Pay on the APP side has done all the work.

Third, concluding remarks

By now, after division of labor, you should have successfully accessed wechat Pay. In this article, only the payment process of wechat Pay is involved. For other order inquiry, refund and other processes, you can refer to the wechat Pay open document for access (you may also find that AppSecret was not mentioned at all before, because it is not used in the payment process).

Well, this article is over, if there is improper place or missing part, welcome to comment correction, thank you.

Fourth, the appendix

Wechat Pay open document address

Wechat Pay open platform login address

Wechat Pay merchant platform login address

Address of wechat public platform interface debugging tool