WeChat payment development-Senparc. Weixin. MP

Source: Internet
Author: User
Tags openid
This article introduces payment development-Senparc. Weixin. MP details public account + payment SDK: Senparc. Weixin. MP. dll

Enterprise SDK: Senparc. Weixin. QY. dll

Open Platform SDK: Senparc. Weixin. Open. dll

Official Address: http://weixin.senparc.com/

Of course, to complete the development of the public account payment function, we need to use Senparc. weixin. MP. dll DLL, read the official DEMO and tutorials, and did not load the payment instructions, no way, since you get the source code, find it.

Enable Senparc. weixin. MP. sln, based on the classification of English folder names, can be preliminarily determined that the payment is encapsulated in the TenPayLib folder, but I also found that there is a folder named "TenPayLibV3, so how to choose? After searching online, I came to the conclusion that I applied for v2 before January 1, September 10, 2014 and later for v3. The service number I used to test the payment was just applied for in 16 years and passed the verification, so use V3 decisively.

Open the TenPayLibV3 folder:

First, configure the payment authorization directory and add the payment test White List. only three payment directories are supported, and the domain name must undergo ICP filing. The authorization directory is used to initiate a payment request. the requested link address must be in the authorization Directory. Otherwise, the identity is invalid and the payment cannot be successful. The personal ID added to the white list can be used to complete the payment test directory payment test. if the user is not in the white list, the payment cannot be successful.

After the configuration is complete, how can I call it? Let's continue to read the official note: H5 calls the payment API

"Open the H5 webpage in the browser and execute JS to initiate the payment. The format of input and output data is JSON.

Note: WeixinJSBridge built-in objects are invalid in other browsers.

The parameter names in the list are case-sensitive. incorrect signature verification will fail ."

OK. here are a few things to be done: first, it must be done in the browser; second, the parameters are case sensitive; third, the data format is JSON.

Officially, you only need to call the following script on the page to enable the payment function:

Function onBridgeReady () {WeixinJSBridge. invoke ('getbrandwcpayrequest', {"appId": "wx2421b1c4370ec43b", // name of the public account, which is input by the merchant "timeStamp": "1395712654", // timeStamp, the number of seconds since January 1, 1970 "nonceStr": "success", // random string "package": "prepay_id = u802345jgfjsdfgsdg888", "signType": "MD5", // signature method: "paySign": "70EA570631E4BB79628FBCA90534C63FF7FADD89" // signature}, function (res) {if (res. err_msg = "get_bran D_wcpay_request: OK ") {}// determine the front-end 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. });} If (typeof WeixinJSBridge = "undefined") {if (document. addEventListener) {document. addEventListener ('weixinjsbridgeready', onBridgeReady, false);} else if (document. attachEvent) {document. attachEvent ('weixinjsbridgeready', onBridgeReady); document. attachEvent ('onweixinjsbridgeready', onBridgeReady) ;}} else {onBridgeReady ();}

My call code: because after I click the button to confirm the payment, I will call the payment for subsequent operations and propose the official code to the method.

Function onBridgeReady () {WeixinJSBridge. invoke ('getbrandwcpayrequest', {"appId": $ ('# APPID '). val (), // The name of the public account, which is passed by the merchant "timeStamp": $ ('# Timestamp '). val (), // timestamp, the number of seconds since January 1, 1970 "nonceStr": $ ('# Noncestr '). val (), // random string "package": $ ('# package '). val (), "signType": "MD5", // signature method: "paySign": $ ('# paySign '). val () // signature}, function (res) {if (res. err_msg = "get_brand_wcpay_request: OK") {// The payment is successful and will be processed by yourself.} else {// The payment is canceled or other errors are handled by yourself }});}

Well, where did these parameters come from? Let's analyze them one by one:

AppId: this should be known for Development. the public account can be found in the developer menu.

TimeStamp: timeStamp. it is officially described as "the number of seconds since January 1, 1970". Don't worry, you can find it from the payment class library.

NonceStr: The official explanation is the random string "e61463f8efa94090b1fda-cccfbbb444". what do you rely on? For details, see the random number generation algorithm. it turns out to be a set of encryption rules and algorithms. friends who have done URL request interfaces should know that some companies use similar JSON string signatures.

Package: pre-payment ID, which can be obtained by calling the unified order interface of the official API

SignType: string "MD5"

PaySign: The official explanation is the signature "70EA570631E4BB79628FBCA90534C63FF7FADD89". well, I have endured it. Looking at the Signature generation algorithm, it seems like a random string.

Here, the official interface description has been very clear, so the following will solve the call to pay for these parameters, through Senparc. Weixin. MP. dll should be used? Now that you need to call the unified order interface to obtain the pre-payment order ID, let's first study how to obtain this ID.

The official team provided a detailed description. we will not repeat it here. the parameter research is based on the methods described above. The only difference is that an XML file is required to call the official interface, which is easy to handle, after splicing, you can call the pre-payment method as follows:

// You can use the official object here. here, the CONFIG file private static Senparc is read directly. weixin. MP. tenPayLibV3.TenPayV3Info tenPayV3Info = new Senparc. weixin. MP. tenPayLibV3.TenPayV3Info (ConfigurationManager. appSettings ["corpId"], ConfigurationManager. deleetask[ "corerecret"], ConfigurationManager. deleetask[ "mch_id"], ConfigurationManager. appSettings ["key"], ConfigurationManager. appSettings ["v3url"]); ///// Pre-payment /////////////////////
 Public static string PayInfo (string attach, string body, string openid, string price, string orderNum = "1833431773763549") {RequestHandler requestHandler = new RequestHandler (HttpContext. current); // The assigned public account ID (the enterprise number corpid is the appId) requestHandler. setParameter ("appid", tenPayV3Info. appId); // additional data, which is returned in the original sample in the query API and payment notification. This field is mainly used by the merchant to carry the custom data of the order requestHandler. setParameter ("attach", attach); // A brief description of requestHa for a product or payment order Ndler. setParameter ("body", body); // The merchant ID requestHandler for payment allocation. setParameter ("mch_id", tenPayV3Info. mchId); // random string, no longer than 32 characters. RequestHandler. SetParameter ("nonce_str", TenPayUtil. GetNoncestr (); // receives the callback address of the asynchronous notification for payment. the notification url must be a directly accessible url and cannot contain parameters. RequestHandler. SetParameter ("policy_url", tenPayV3Info. TenPayV3Notify); // trade_type = JSAPI. this parameter is required. it is the unique identifier of the user under the public account appid of the merchant. RequestHandler. setParameter ("openid", openid); // the order number in the merchant's system. it contains 32 characters and can contain letters. you can generate requestHandler by yourself. setParameter ("out_trade_no", orderNum); // submit the client ip address for APP and webpage payment, and fill in the IP address of the machine that calls the payment API for Native payment. RequestHandler. setParameter ("spbill_create_ip", "127.0.0.1"); // The total order amount. unit: Minute. if you have paid for UnionPay, you should know that the order amount is 12 bits, and the last shard is requestHandler. setParameter ("total_fee", price); // The value is as follows: JSAPI, NATIVE, APP. here we use JSAPI requestHandler. setParameter ("trade_type", "JSAPI"); // set KEY requestHandler. setKey (tenPayV3Info. key); requestHandler. createMd5Sign (); requestHandler. getRequestURL (); requestHandler. createSHA1Sign (); string data = requestHandler. parseXML (); requestHandler. getDebugInfo (); // Get and return the pre-payment XML Information return tenpayv3.uniiedorder (data );}}

Okay. everything is easy to handle when we get the data returned from the pre-payment order. we will solve the problem by ourselves based on the different return parameters. we only care about the correct call process and continue the operation, in the returned correct XML data, we get wx201411101639507cbf6ffd8b0779950874 (Official example), okay. start to make a payment on the page!

Here, I encapsulate an object to transmit common data. of course, you can also refer to the entity class provided by Senparc. Weixin. MP. dll.

public class ShareInfo    {        string corpId = string.Empty;        public string CorpId        {            get { return corpId; }            set { corpId = value; }        }        string ticket = string.Empty;        public string Ticket        {            get { return ticket; }            set { ticket = value; }        }        string noncestr = string.Empty;        public string Noncestr        {            get { return noncestr; }            set { noncestr = value; }        }        string timestamp = string.Empty;        public string Timestamp        {            get { return timestamp; }            set { timestamp = value; }        }        private string paySign = string.Empty;        public string PaySign        {            get { return paySign; }            set { paySign = value; }        }        private string package = string.Empty;        public string Package        {            get { return package; }            set { package = value; }        }    }

Let's continue. let's take a look at how to obtain the parameters required by the payment interface:

Public static receive info GetPayInfo (string prepayid) {Register info = new receive info (); // check whether jssdk if (! JsApiTicketContainer. checkRegistered (corpId) {JsApiTicketContainer. register (corpId, correntcret);} JsApiTicketResult jsApiTicket = JsApiTicketContainer. getTicketResult (corpId); JSSDKHelper jssdkHelper = new JSSDKHelper (); cmdinfo. ticket = jsApiTicket. ticket; interval info. corpId = corpId. toLower (); response info. noncestr = JSSDKHelper. getNoncestr (). toLower (); response info. timestamp = JSSDKHelper. getTimestamp (). toLower (); response info. package = "prepay_id =" + prepayid. toLower (); RequestHandler requestHandler = new RequestHandler (HttpContext. current); requestHandler. setParameter ("appId", parameter info. corpId); requestHandler. setParameter ("timeStamp", parameter info. timestamp); requestHandler. setParameter ("nonceStr", parameter info. noncestr); requestHandler. setParameter ("package", parameter info. package); requestHandler. setParameter ("signType", "MD5"); requestHandler. setKey (tenPayV3Info. key); requestHandler. createMd5Sign (); requestHandler. getRequestURL (); requestHandler. createSHA1Sign (); raise info. paySign = (requestHandler. getAllParameters () ["sign"]). toString (); return response info ;}

In this way, all the parameters required for the payment interface are encapsulated in Consumer Info. well, after the call, we will return to the post-code of the page or the corresponding ORM Code you use, output parameters to the page

// Processing page payment call information pipeline info = TenPayModule. GetPayInfo (prepayid); System. Web. HttpContext. Current. Response. Write (string. Format ("", Using info. Noncestr); System. Web. HttpContext. Current. Response. Write (string. Format ("", Using info. Timestamp); System. Web. HttpContext. Current. Response. Write (string. Format ("", Using info. CorpId); System. Web. HttpContext. Current. Response. Write (string. Format ("", Using info. PaySign); System. Web. HttpContext. Current. Response. Write (string. Format ("", Using info. Package ));

Okay, write it here. you can complete the entire payment function by referring to the above JS code. Finally, a method is provided to generate the merchant's order number. the code is as follows:

public string GetOrderNumber()        {            string Number = DateTime.Now.ToString("yyMMddHHmmss");            return Number + Next(1000, 1).ToString();        }        private static int Next(int numSeeds, int length)        {            byte[] buffer = new byte[length];             System.Security.Cryptography.RNGCryptoServiceProvider Gen = new System.Security.Cryptography.RNGCryptoServiceProvider();            Gen.GetBytes(buffer);            uint randomResult = 0x0;             for (int i = 0; i < length; i++)            {                randomResult |= ((uint)buffer[i] << ((length - 1 - i) * 8));            }            return (int)(randomResult % numSeeds);        }

For more details about payment development-Senparc. Weixin. MP, please follow the PHP Chinese website!

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.