How to use. NET to parse WeChat payment

Source: Internet
Author: User
Tags openid
Due to its wide use, a series of development-based solutions have also emerged. This article mainly introduces the implementation method of resolution payment (. NET Edition). If you are interested, please take a look. Due to its wide use, a series of development-based solutions have also emerged. This article mainly introduces the implementation method of resolution payment (. NET Edition). If you are interested, please take a look.

Some time ago, I made a payment for the Web version and encountered many problems, but I finally solved the problem. now I am going to record the development process and instructions here and give them some reference.

I. preparations

First of all, you must activate the payment function. a deposit of 30 thousand is required for the previous payment. now you do not need this function.

For payment development, you need to set it in the background of the public account and the merchant's background.

1. Development Directory configuration

You must configure the payment authorization directory in the public account background (payment = "development configuration. The authorized directory must be an online address, that is, the address accessible through the Internet. the payment system must be able to access your address through the Internet.

Authorization directory needs to be accurate to level 2 or level 3 directory, example: if the initiate payment link is http://www.hxfspace.net/weixin/WeXinPay/WeXinPayChoose then the configured directory should be http://www.hxfspace.net/weixin/WeXinPay/ where http: // www. hxfspace.net is the domain name weixin is the virtual directory WeXinPay, that is, the Controller-related payment requests are all in the action in WeXinPay.

// Determine whether the webpage authorization is performed and the authorization code is obtained. if no authorization is performed, construct the webpage authorization code and re-request if (string. isNullOrEmpty (Request. queryString ["code"]) {string redirectUrl = _ weChatPaySerivce. getAuthorizeUrl (account. appId, account. redquestUrl, "STATE" + "# wechat_redirect", "snsapi_base"); return Redirect (redirectUrl );}


Url authorization method for splicing web pages


Public string GetAuthorizeUrl (string appId, string redirectUrl, string state, string scope) {string url = string. Format ("https://open.weixin.qq.com/connect/oauth2/authorize? Appid = {0} & redirect_uri = {1} & response_type = code & scope = {2} & state = {3} ", appId, HttpUtility. urlEncode (redirectUrl), scope, state);/* after this step is sent, the customer will get the authorization page, regardless of the consent or rejection, will return the redirectUrl page. * If the user agrees to the authorization, the page will jump to redirect_uri /? Code = CODE & state = STATE. The code here is used in exchange for access_token (and the access_token of the general interface is not universal) * if the user prohibits authorization, the code parameter is not included after the redirection, but the state parameter redirect_uri? State = STATE */AppLog. Write ("get authorization url:", AppLog. LogMessageType. Debug); return url ;}


2. exchange authorization code for webpage authorization access_token and openid

After obtaining the authorization code from step 1, combine the webpage authorization request url to obtain the access_token and openid


Public Tuple
 
  
GetOpenidAndAccessTokenFromCode (string appId, string code, string appSecret) {Tuple
  
   
Tuple = null; try {string url = string. Format ("https://api.weixin.qq.com/sns/oauth2/access_token? Appid = {0} & secret = {1} & code = {2} & grant_type = authorization_code ", appId, appSecret, code); string result = WeChatPayHelper. get (url); AppLog. write ("payment-get openid and access_token request Url:" + url + "result:" + result, AppLog. logMessageType. debug); if (! String. IsNullOrEmpty (result) {var jd = Newtonsoft. Json. JsonConvert. DeserializeObject
   
    
> (Result); tuple = new Tuple
    
     
(Jd ["openid"], jd ["access_token"]); AppLog. write ("payment-successful acquisition of openid and access_token", AppLog. logMessageType. debug) ;}} catch (Exception ex) {AppLog. write ("payment: An error occurred while obtaining the openid and access_tokenu", AppLog. logMessageType. debug, ex);} return tuple ;}
    
   
  
 


3. call the unified order interface to obtain the prepayment prepayId

Here, RequestHandler is a dll encapsulated by someone else on the internet. it helps you encapsulate the signature generation and some verification requests. Dll can download http://weixin.senparc.com/


// Create the payment response object RequestHandler packageReqHandler = new RequestHandler (null); // initialize packageReqHandler. init (); // timeStamp string timeStamp = TenPayUtil. getTimestamp (); // random string nonceStr = TenPayUtil. getNoncestr (); // Set package order parameters to generate prepayId prepayment Id packageReqHandler. setParameter ("appid", account. appId); // the public account ID packageReqHandler. setParameter ("mch_id", account. partnertId); // merchant ID packageReqHandler. setParameter ("nonce_str", nonceStr); // random string packageReqHandler. setParameter ("body", account. body); packageReqHandler. setParameter ("out_trade_no", account. orderSerialId); // The Merchant's order number packageReqHandler. setParameter ("total_eter", account. totalAmount); // item amount, in units (money * 100 ). toString () packageReqHandler. setParameter ("spbill_create_ip", account. requestIp); // the user's public ip address, not the merchant's server IP packageReqHandler. setParameter ("policy_url", account. notifyUrl); // The URL packageReqHandler that receives the Caifu notification. setParameter ("trade_type", "JSAPI"); // The transaction type packageReqHandler. setParameter ("openid", account. openId); // your openId string sign = packageReqHandler. createMd5Sign ("key", account. paySignKey); packageReqHandler. setParameter ("sign", sign); // signature string prepayId = string. empty; try {string data = packageReqHandler. parseXML (); var result = tenpayv3.uniiedorder (data); MailHelp. sendMail ("call unified order interface, order result: --" + result + "request parameter:" + data); var res = XDocument. parse (result); prepayId = res. element ("xml "). element ("prepay_id "). value; AppLog. write ("The prepayId is successfully obtained by calling the unified order interface", AppLog. logMessageType. debug);} catch (Exception ex) {AppLog. write ("An error occurred while obtaining the openid and access_tokenu", AppLog. logMessageType. debug, ex); MailHelp. sendMail ("An error occurred while calling the unified order interface to obtain the pre-payment prepayid:", ex); return null ;}


4. set jsapi payment request parameters and initiate payment

Here I first assemble the parameters required for the payment, and then create and call the js script.


// Generate the JsAPI payment parameter RequestHandler paySignReqHandler = new RequestHandler (null); paySignReqHandler. setParameter ("appId", account. appId); paySignReqHandler. setParameter ("timeStamp", timeStamp); paySignReqHandler. setParameter ("nonceStr", nonceStr); paySignReqHandler. setParameter ("package", string. format ("prepay_id = {0}", prepayId); paySignReqHandler. setParameter ("signType", "MD5"); string paySign = paySignReqHandler. createMd5Sign ("key", account. paySignKey); WeChatJsPayRequestModel resultModel = new WeChatJsPayRequestModel {AppId = account. appId, NonceStr = nonceStr, TimeStamp = timeStamp, Package = string. format ("prepay_id = {0}", prepayId), PaySign = paySign, SignType = "MD5 "};


Create call script


Private string CreateWeixinJs (WeChatJsPayRequestModel model) {string js = @"

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.