C # develop WeChat portals and applications (40) -- use WeChat JSAPI to implement the WeChat payment function,

Source: Internet
Author: User
Tags openid tojson

C # development portal and application (40) -- use JSAPI to implement the payment function,

In my previous blogs, I have introduced various payment-related operations such as payment, red packets, and enterprise payment. However, the above are based on the encapsulation of common APIs, in this article, I will continue to pay for this topic. I will continue to introduce the implementation of the payment function based on the webpage JSAPI. Compared with common API operations, JSAPI debugging is not so convenient, and sometimes some errors need to be verified repeatedly. This article describes the implementation of JSAPI payment based on actual Web payment cases.

1. Knowledge of JS-SDK

In front of me "C # development portal and application (39) -- using JSSDK sign-In function" introduced content, there are introduced a lot of JS-SDK basics, we initiate payments based on web pages, and we initiate them based on JS-SDK, so we need to understand the steps to use these JS-SDK.

In general, the method of wx. chooseWXPay is required for the payment initiated by JSAPI on the webpage. This method also needs to be triggered by the interface element when completing the wx. config initialization.

For example, we can implement the entire payment process as follows:

1) first use JS to initialize the API Configuration

Wx. config ({debug: false, appId: appid, // required. The only identifier of the public account is timestamp: timestamp, // required. The signature timestamp nonceStr: noncestr, // required. The random signature string signature: signature, // required. For details, see Appendix 1 jsApiList: ['checkjsapi ', 'choosewxpay ', 'hideoptionmenu ']});

 

2) use wx. chooseWXPay to initiate a payment

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 pass in 'md5' paySign: '', // payment signature success: function (res) {// callback function after successful payment }});

Note: The prepay_id is obtained through the unified payment order interface, and the paySign uses the unified payment Sign generation method. Note that appId must also be included in the signature here. appId is consistent with the appId passed in config, the signature parameters include appId, timeStamp, nonceStr, package, and signType.

 

3) obtain the user's openid

In some JSAPI operations, you sometimes need to input the current user's openid. This value is generally not directly available, but can be obtained through the user authorization code, therefore, we can configure the Redirection URL in the menu, obtain the corresponding code based on the URL, and then parse the code as the corresponding openid.

In exchange for a special webpage authorization access_token, which is different from the access_token (which is used to call other interfaces) in the basic support. The public account can be used to obtain the webpage authorization access_token through the following interface. If the scope of webpage authorization is snsapi_base, The openid and snsapi_base webpage authorization processes are also obtained when the webpage authorization access_token is obtained in this step.

After getting code, request the following link to get access_token: https://api.weixin.qq.com/sns/oauth2/access_token? Appid = APPID & secret = SECRET & code = CODE & grant_type = authorization_code

 

2. Handle the JSAPI initialization parameters

To get the relevant interface parameters of the JS-SDK, We need to generate the JSAPI-Ticket credential, the implementation of this credential code interface is as follows. Generally, the data of this interface needs to be cached and can be processed by yourself.

/// <Summary> /// obtain the JSAPI_TICKET interface // </summary> /// <param name = "accessToken"> call interface credential </param> /// <returns> </returns> public string GetJSAPI_Ticket (string accessToken) {var url = string. format ("https://api.weixin.qq.com/cgi-bin/ticket/getticket? Access_token = {0} & type = jsapi ", accessToken); var result = JsonHelper <GetTicketResult>. ConvertJson (url); return result! = Null? Result. ticket: null ;}

To implement JSSDK signature processing, we must first construct URL strings based on several variables. For specific processing, we can put them in a Hashtable one by one, as shown in the following code.

/// <Summary> /// obtain the parameter information required by JSSDK, returns Hashtable combination /// </summary> /// <param name = "appId"> AppID </param> /// <param name = "jsTicket"> obtained based on the Token JSSDK ticket </param> /// <param name = "url"> page URL </param> /// <returns> </returns> public static Hashtable GetParameters (string appId, string jsTicket, string url) {string timestamp = GetTimeStamp (); string nonceStr = GetNonceStr (); // here, the parameter order should be sorted in ascending order of the key value ASCII code string rawstring = "jsapi_ticket =" + jsTicket + "& noncestr =" + nonceStr + "& timestamp =" + timestamp + "& url =" + url + ""; string signature = GetSignature (rawstring); Hashtable signPackage = new Hashtable (); signPackage. add ("appid", appId); signPackage. add ("noncestr", nonceStr); signPackage. add ("timestamp", timestamp); signPackage. add ("url", url); signPackage. add ("signature", signature); signPackage. add ("jsapi_ticket", jsTicket); signPackage. add ("rawstring", rawstring); return signPackage ;}

In this way, they are placed in the hash table for extraction and use.

Wx. config ({debug: false, appId: appid, // required. The only identifier of the public account is timestamp: timestamp, // required. The signature timestamp nonceStr: noncestr, // required. The random signature string signature: signature, // required. For details, see Appendix 1 jsApiList: ['checkjsapi ', 'choosewxpay ', 'hideoptionmenu ']});

In order to set the calculated values on the MVC view page, we usually need to calculate them in the background and place them in the ViewBag variable to use them on the front-end of the page, the following is the background code of the MVC view page.

/// <Summary> /// refresh the ticket for the JS-SDK /// </summary> protected virtual void RefreshTicket (AccountInfo accountInfo) {Hashtable ht = baseApi. getJSAPI_Parameters (accountInfo. appID, accountInfo. appSecret, Request. url. absoluteUri); ViewBag. appid = ht ["appid"]. toString (); ViewBag. nonceStr = ht ["noncestr"]. toString (); ViewBag. timestamp = ht ["timestamp"]. toString (); ViewBag. signature = ht ["signature"]. toString ();}

In this way, in the MVC view page, our code can implement JSAPI variable initialization in this way.

<Script language = "javascript"> var openid = '@ ViewBag. openid'; var appid = '@ ViewBag. appid '; var noncestr =' @ ViewBag. noncestr '; var signature =' @ ViewBag. signature '; var timestamp =' @ ViewBag. timestamp '; wx. config ({debug: false, appId: appid, // required. The only identifier of the public account is timestamp: timestamp, // required. The signature timestamp nonceStr: noncestr, // required. The random signature string signature: signature, // required. For details, see Appendix 1 jsApiList: ['checkjsapi ', 'choosewxpay ', 'hideoptionmenu ']});

 

3. Process Parameters for JSAPI payment

In the first section, I mentioned that after initializing the JS-API, you also need to use wx. chooseWXPay to initiate a payment, this interface also has several related parameters.

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 pass in 'md5' paySign: '', // payment signature success: function (res) {// callback function after successful payment }});

Here, the rules of timestamp and nonceStr are the same as those of the parameter rules of the previous initialization operation, but note that they cannot be the same as those of the initialization interface timestamp and nonceStr. Otherwise, 【Payment Verification signature failed.

The package variable is the pre-order id obtained by calling the unified order interface. The format is as follows:

prepay_id=wx2016051517463160322779de0375788970

To obtain the pre-order ID, we first need to build a data object according to the requirements of the unified order interface, as shown below.

PayOrderData data = new PayOrderData () {product_id = id, body = "test payment" + id, attach = "", detail = "test JSAPI payment" + id, total_detail = 1, goods_tag = "test" + id, trade_type = "JSAPI", openid = openid };

Then, call the previously encapsulated unified order interface API to obtain the corresponding unified order ID.

TenPayApi api = new TenPayApi (accountInfo); var orderResult =Api. uniiedorder (data );LogHelper. Debug (string. Format ("unified order result: {0}", (orderResult! = Null )? OrderResult. toJson (): "null"); if (string. isNullOrEmpty (orderResult. prepay_id) | string. isNullOrEmpty (orderResult. appid) {throw new WeixinException ("An error occurred while returning the unified order result! ");}

SignType is fixed to MD5,

In the end, the paySign parameter is a complex parameter, which is the value that needs to be signed based on the preceding parameters. The payment signature is still the same as that of a common API (when I first introduced the payment, I have introduced the relevant rules. For details, refer to C # development portal and application (32) -- Payment access and API encapsulation), introducing entity classesWxPayDataTo store some business parameters and implement parameter signature processing.

It is worth noting that the common API signature is Sign, while the JSAPI signature variable name is paySign. The processing logic is the same, but the names are different.

The code for processing related variables in the background is as follows.

/// <Summary> /// obtain the string parameter object in the JSAPI mode. /// </summary> /// <param name = "accountInfo"> current account </param> /// <param name = "prepay_id"> Unified order ID </param> // <returns> </returns> private WxPayData GetJSPayParam (AccountInfo accountInfo, string prepay_id) {WxPayData data = new WxPayData (); data. setValue ("appId", ViewBag. appId); data. setValue ("timeStamp", data. generateTimeStamp (); data. setValue ("nonceStr", data. generateNonceStr (); data. setValue ("signType", "MD5"); data. setValue ("package", string. format ("prepay_id = {0}", prepay_id); data. setValue ("paySign", data. makeSign (accountInfo. payAPIKey); // signature return data ;}

Then, define a Controller Interface and return relevant parameter data. Some logic code is as follows. This allows the front-end to obtain the corresponding variable value in JSON format.

// The parameter WxPayData param = GetJSPayParam (accountInfo, orderResult. prepay_id); LogHelper. debug ("GetJSPayParam:" + param. toJson (); var obj = new {timeStamp = param. getString ("timeStamp"), nonceStr = param. getString ("nonceStr"), signType = param. getString ("signType"), package = param. getString ("package"), paySign = param. getString ("paySign")}; return Content (obj. toJson ());

On the previous page, obtain the parameters for initiating a payment through ajax. The Code is as follows.

// Initiate a payment function chooseWXPay (id) {// alert (window. location. href); var uid = getUrlVars () ["uid"]; $. ajax ({type: 'post', url: '/JSSDKTest/getwxpaydata', // async: false, // synchronize dataType: 'json', data: {id: id, uid: uid, openid: openid}, success: function (json) {wx. chooseWXPay ({appId: appid, timestamp: json. timeStamp, // payment signature timestamp. Note that all 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: json. nonceStr, // random string of the payment signature, no longer than 32-bit package: json. package, // The value of the prepay_id parameter returned by the Unified payment interface. The submission format is: prepay_id = ***) signType: json. signType, // signature method. The default value is 'sha1'. For new payment, 'md5' paySign: json is required. paySign, // payment signature success: function (res) {// callback function if (res. errMsg = 'choosewxpay: OK ') {$. toast ('payment successfully'); // setTimeout (function () {// window. location. href = "/"; // jump here by default To the homepage //}, 2000); // window. location. href = "/Pay/order_details? OrderId = "+ $ (" # orderId "). val ();} else if (res. errMsg = 'choosewxpay: cancel '| res. errMsg = 'choosewxpay: fail ') {$. toast ("Payment failed"); // window. location. href = "/Pay/order_details? OrderId = "+ $ (" # orderId "). val () ;}, cancel: function () {$. toast ("the user canceled the payment"); // window. location. href = "/Pay/order_details? OrderId = "+ $ (" # orderId "). val () ;}}); wx. error (function (res) {$. toast ("an exception occurred when calling the payment"); // window. location. href = "/Pay/order_details? OrderId = "+ $ (" # orderId "). val () ;}}, error: function (xhr, status, error) {$. toast ("operation failed" + xhr. responseText); // xhr. responseText }});};

 

4. interface effect of JSAPI payment

Through the above code, we can smoothly initiate a payment and see the specific test results. Readers can follow our public account [Guangzhou aiqidi] to test the payment.

After the payment is successful, we can also see the response result in the payment dialog.

 

If you are interested in this series of C # development portals and applications, you can follow my other articles as follows:

C # development portal and application (40) -- use JSAPI for payment

C # development portal and application (39) -- sign-in using JSSDK

C # development portal and application (38) -- shake a red envelope

C # development portal and application (37) -- Public Account tag Management Function

C # development portal and application (36)-encapsulation of card shield Management

C # development portal and application (35) -- payment for enterprise payment Encapsulation

C # development portal and application (34) -- split red packets

C # development portal and application (33) -- encapsulation and use of cash Red Packets

C # development portal and application (32) -- Payment access and API Encapsulation

C # development portal and application (31)-implementation and processing of semantic understanding Interfaces

C # development portal and application (30)-message group processing and preview

C # development portal and application (28) -- Use of the "shake around" function and implementation of interfaces

C # development portal and application (27)-Public Account template Message Management

C # development portal and application (26)-Material Management of Public Accounts

C # development portal and application (25)-enterprise account Client Management Function

C # development portal and application (24)-store shelf Information Management

C # development portal and application (23)-packaging and testing of the store product management interface

C # development portal and application (22)-Development and Use of stores

C # development portal and application (21)-receiving, processing, and decryption of enterprise numbers and events

C # development portal and application (20)-menu management of enterprise number

C # development portal and application (19)-sending of enterprise numbers (text, images, files, voice, video, text messages, etc)

C # development portal and application (18)-member management for enterprise address book management and development

C # development portal and application (17)-department management for enterprise address book management and development

C # development portal and application (16)-enterprise number configuration and use

C # development portal and application (15)-added the scan, image sending, and geographic location functions in the menu

C # development portal and application (14)-use redirection in the menu to obtain user data

C # development portal and application (13)-use geographic location Extension

C # development portal and application (12)-use voice processing

C # development portal and application (11)-menu presentation

C # development portal and application (10) -- synchronize user group information in the management system

C # development portal and application (9)-portal menu management and submission to server

C # development portal and application (8)-portal application management system function Introduction

C # development portal and application (7)-Multi-customer service functions and development integration

C # development portal and application (6)-portal menu management operations

C # development portal and application (5) -- User Group Information Management

C # development portal and application (4) -- Focus on the user list and detailed information management

C # development portal and application (3) -- Response to text messages and text messages

C # development portal and application (2) -- Message Processing and response

C # development portal and application (1) -- getting started with Interfaces

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.