WeChat JSAPI payment and the pitfalls encountered, jsapi

Source: Internet
Author: User
Tags openid

JSAPI payment and the pitfalls encountered

First, we will introduce that weixin. senparc SDK is used to call the payment interface. It is very convenient to use an open-source Development SDK.

Weixin. senparc SDK Official Website: http://weixin.senparc.com/

Download the Senparc. Weixin SDK first.

Before calling the payment interface, you must call the unified order interface. The Merchant system first calls this interface to generate a pre-payment transaction ticket in the payment service background, return the correct call-back ID of the pre-payment transaction before making the payment in the APP.

In this directory, Senparc. Weixin. MP. Sample. Controllers finds JsApi payment.

Public ActionResult JsApi (string code, string state) {if (string. IsNullOrEmpty (code) {return Content ("you have denied authorization! ");} If (! State. contains ("|") {// The state is actually exposed to the client, and the verification capability is weak. Here, we just demonstrate that // actually can store any data you want to transmit, for example, the user ID must be combined with the Session ["OAuthAccessToken"] below to verify return Content ("Verification Failed! Please go through the regular channel! 1001 ");} try {// get product information var stateData = state. split ('|'); int productId = 0; ProductModel product = null; if (int. tryParse (stateData [0], out productId) {int hc = 0; if (int. tryParse (stateData [1], out hc) {var products = ProductModel. getFakeProductList (); product = products. firstOrDefault (z => z. id = productId); if (product = null | product. getHashCode ()! = Hc) {return Content ("the product information does not exist or it is illegal to enter! 1002 ");} ViewData [" product "] = product;} // pass, use code in exchange for access_token var openIdResult = OAuthApi. getAccessToken (TenPayV3Info. appId, TenPayV3Info. appSecret, code); if (openIdResult. errcode! = ReturnCode. request successful) {return Content ("error:" + openIdResult. errmsg);} string sp_billno = Request ["order_no"]; if (string. isNullOrEmpty (sp_billno) {// generates the Order's 10-digit serial number. In this example, the time and random number are used to generate the serial number. The Merchant adjusts the number according to the user and ensures that the unique sp_billno = string. format ("{0} {1} {2}", TenPayV3Info. mchId, DateTime. now. toString ("yyyyMMdd"), TenPayV3Util. buildRandomStr (10);} else {sp_billno = Request ["order_no"];} var timeStamp = TenPayV3Util. getTimestamp (); Var nonceStr = TenPayV3Util. GetNoncestr (); var body = product = null? "Test": product. Name; var price = product = null? 100: product. price * 100; var xmlDataInfo = new tenpayv3uniiedorderrequestdata (TenPayV3Info. appId, TenPayV3Info. mchId, body, sp_billno, price, Request. userHostAddress, TenPayV3Info. tenPayV3Notify, TenPayV3Type. JSAPI, openIdResult. openid, TenPayV3Info. key, nonceStr); var result = tenpayv3.uniiedorder (xmlDataInfo); // call the unified order interface // JsSdkUiPackage jsPackage = new JsSdkUiPackage (TenPayV3Info. appId, time Stamp, nonceStr,); var package = string. format ("prepay_id = {0}", result. prepay_id); ViewData ["appId"] = TenPayV3Info. appId; ViewData ["timeStamp"] = timeStamp; ViewData ["nonceStr"] = nonceStr; ViewData ["package"] = package; ViewData ["paySign"] = TenPayV3.GetJsPaySign (TenPayV3Info. appId, timeStamp, nonceStr, package, TenPayV3Info. key); return View () ;}catch (Exception ex) {var msg = ex. message; msg + = "<Br>" + ex. StackTrace; msg + = "<br> = Source = <br>" + ex. Source; if (ex. InnerException! = Null) {msg + = "<br >== InnerException ===< br>" + ex. InnerException. Message;} return Content (msg );}}


First, generate a pre-payment transaction ticket in the service background to obtain the pre-payment order number.

Let's talk about the pitfalls encountered in unified order.


1. The returned results are parsed when the unified order is placed. the following problem persists: you do not have the JSAPI payment permission.

<Return_code> <! [CDATA [FAIL]> </return_code>
<Return_msg> <! [CDATA [you do not have the JSAPI payment permission]> </return_msg>


1) Check whether your public account payment settings are correct.

For how to configure payment: refer to this http://jingyan.baidu.com/article/77b8dc7fef360d6174eab690.html

2) Check whether your authorization directory is correct, the format should be like this, remember not to miss a/For example: http://test.cn/u/

3) Check the account parameters that need to be passed in. Check whether your account parameters are correct with the public account number and the merchant account number. I found out during development that the public account Merchant number and the appid are different from the two public accounts. After finding them for a long time, I felt that something was wrong. It turned out that the configuration parameter key was incorrect.

Here we will detail the corresponding parameters:

MCHID: The Merchant ID (which must be configured and can be viewed in the account opening email). After the merchant applies for payment, the merchant's payment account is allocated by the payment.

APPID: The application APPID approved by the open platform. appid is the unique identifier of a public account or an open platform APP. After applying for a public account on the public platform or applying for an APP account on the open platform, the corresponding appid is automatically assigned to identify the application. You can view it on the public platform> Developer Center. This field value is also included in the merchant's payment review email.

KEY: the merchant's payment KEY. For details, refer to the account opening email settings (which must be configured and configured on the merchant's platform). The signature KEY generated during the transaction is only kept in the merchant's system and payment backend, will not spread in the network. The merchant keeps the Key properly. Do not transmit the key over the network or store it in other clients, so that the Key will not be leaked. Merchants can log on to the merchant platform as instructed by the email. You can also click the following path to set up: merchant platform (pay.weixin.qq.com) --> account settings --> API security --> key settings.
APPSECRET: Public Account secert (configuration is required only when JSAPI is used for payment. log on to the public platform and enter the Developer Center for setting)


2. In the unified order, I found that the result returned by the resolution does not match the merchant's mch_id and appid.

<Return_code> <! [CDATA [FAIL]> </return_code>
<Return_msg> <! [CDATA [the merchant ID mch_id does not match appid]> </return_msg>

The reason is that the Merchant number I got is not the public number. Check whether the Merchant number of this public account is correct.


3. In the unified order, appid and openid not match appear in the result returned by resolution. The appid and openid do not match.

<Return_code> <! [CDATA [FAIL]> </return_code>
<Return_msg> <! [CDATA [appid and openid not match]> </return_msg>

The reason is that my user's openid is not a public account.


3. In the unified order, CDATA [openid is invalid] appears in the result returned by parsing. The openid is invalid.

<Return_code> <! [CDATA [FAIL]> </return_code>
<Return_msg> <! [CDATA [openid is invalid]> </return_msg>

The reason is that the upload is not a valid opendid. I accidentally read the error and passed the user ID as an openid.


When the unified order is successfully placed, parameters in the following format are returned.


Resolution to get the pre-payment order number:

String prepayId = res. Element ("xml"). Element ("prepay_id"). Value; // get the pre-payment order number

Parameters corresponding to the page

                ViewData["appId"] = TenPayV3Info.AppId;                ViewData["timeStamp"] = timeStamp;                ViewData["nonceStr"] = nonceStr;                ViewData["package"] = package;                ViewData["paySign"] = TenPayV3.GetJsPaySign(TenPayV3Info.AppId, timeStamp, nonceStr, package, TenPayV3Info.Key);

Static Page js call:

Wx. chooseWXPay ({timestamp: 0, // pay the signature timestamp. Note that all the timestamp fields in jssdk are in lower case. However, the timeStamp field name used to generate a signature in the payment background of the latest version must be capitalized with the S character nonceStr: '', // random string of the payment signature, no longer than 32-bit package :'', // The value of the prepay_id parameter returned by the Unified payment interface. The submission format is prepay_id = ***) signType: '', // signature method. The default value is 'sha1 ', to use the new payment version, you need to input 'md5' paySign: '', // payment signature success: function (res) {if (res. err_msg = "get_brand_wcpay_request: OK") {// payment successful} else {
// Payment failed
// Determine the frontend return using the above method. The team solemnly prompts that res. err_msg will return OK after the user successfully pays, but it is not guaranteed to be absolutely reliable. }});


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.