The implementation method of resolving micro-credit payment (. NET Edition) _ Practical Skills

Source: Internet
Author: User
Tags cdata httpcontext md5 openid

Some time ago made a web version of micro-letter payment, encountered a lot of problems, but eventually resolved, now recorded in the development process and description, to other people some reference.

First, preparatory work

First of all, we must first open the micro-letter payment function, before the opening of micro-letter payment needs 30,000 of the deposit, now do not need, so did this function.

To carry out the development of micro-credit payment, it is necessary to set up the background of the public number and the micro-letter merchant.

1, Development directory Configuration

Micro-credit payments need to be in the public number backstage (micro-letter Payment = "Development configuration) to configure Payment authorization directory." The authorization directory here needs to be an online address, which is an address that can be accessed via the Internet, and the micro-credit payment system needs to be able to access your address via the Internet.

The micro-Credit authorization directory needs to be accurate to level two or level three directory, case: If the link to initiate payment is Http:// then the configured directory should be http:// them http://www. is the domain Weixin is the virtual directory Wexinpay is the controller related payment request in the Wexinpay action inside.

2, OAuth2.0 Web page authorized domain name setting

When a micro-credit is paid, a callback is made to the payment request to obtain the authorization code, so you need to set the authorized domain name here. Of course here the domain name is to and payment authorization directory in the domain name is the same one. This do not forget to set me up at that time is to forget to set up and find a half-day reason, crying dead.

3, related parameter preparation

Calling micro-credit payment requires a script to initiate a payment request to a micro-credit payment system, as described in the micro-credit website payment Platform

The generation of package and Paysign requires the developer key Appsecret (Application key), the micro-letter merchant number, the micro-credit payment key, and the acquisition and setup of these parameters can be read in this article

Second, the development process

Not much nonsense to say directly after finishing the process:

1, through the micro-letter authorization callback to obtain authorization code

2, through authorization code in exchange for Web page authorization Access_token and OpenID

3, call the unified next single interface to obtain pre-payment Prepayid

4, the formation of JSAPI micro-letter payment request parameters, to initiate payment

5, receive the micro-credit payment callback for follow-up operations

Third, the specific development (on the Code)

Micro-credit payment can only be carried out on the online environment, the mode is very inconvenient, at the beginning of the development of the best in each key location log good.

1, through the micro-letter authorization callback to obtain authorization code

First, the initiation of payment address and related parameters to the micro-letter payment interface, micro-credit payment to receive verification success, will request your payment address and bring authorization code.

Like me here.

 To determine whether the Web page is licensed, obtain authorization code, no representative is not authorized, construct a Web page authorization to get code, and then request the
      if string. IsNullOrEmpty (request.querystring["Code"]))
        string redirecturl = _wechatpayserivce.getauthorizeurl ( Account. AppId, account. Redquesturl, "state
          " + "#wechat_redirect", "snsapi_base");
        Return Redirect (RedirectURL);

Mosaic micro-letter Web page Authorization URL method

public string Getauthorizeurl (string appId, String RedirectURL, string state, string scope)
      string url = string. Format ("{0}&redirect_uri={1}&response_type= Code&scope={2}&state={3} ",
          appId, Httputility.urlencode (redirecturl), scope, state);
      /* This step is sent, the customer will get the authorization page, regardless of consent or rejection, will return to the RedirectURL page.
       * If the user agrees to authorize, the page will jump to redirect_uri/?code=code&state=state. The code here is used in exchange for Access_token (and General interface Access_token)
       * If the user prohibits authorization, then redirects will not take the code parameter, will only take the state parameter redirect_uri?state= State
      /Applog.write ("Get to Authorization URL:", AppLog.LogMessageType.Debug); 
      return URL;

2, through authorization code in exchange for Web page authorization Access_token and OpenID

After obtaining the authorization code from the first step, combine the page authorization request URL to get Access_token and OpenID

 Public tuple<string, String> getopenidandaccesstokenfromcode (string appId, String code, string Appsecret) {
      tuple<string, string> Tuple = null; try {string url = string. Format ("Https://{0}&secret={1}&code={2}&grant_type
        =authorization_code ", AppId, Appsecret, code);
        string result = Wechatpayhelper.get (URL);
        Applog.write ("micro-credit payment-get OpenID and Access_token request URL:" + URL + "Result:" + result, AppLog.LogMessageType.Debug); if (!string. IsNullOrEmpty (Result)) {var jd=newtonsoft.json.jsonconvert.deserializeobject<dictionary<string, s
          Tring>> (result);
          tuple = new tuple<string, string> (jd["OpenID"],jd["Access_token"]);
        Applog.write ("micro-credit payments-get OpenID and Access_token success", AppLog.LogMessageType.Debug); (Exception ex) {applog.write ("micro-letter payment: Get OpenID and Access_tokenu exceptions", APPLOG.LOGMESSAGETYPE.DEBUG,EX);
    return tuple;

3, call the unified next single interface to obtain pre-payment Prepayid

Here RequestHandler is used by other people on the internet to encapsulate a good DLL, to help you encapsulate the signature generation and some authentication requests. DLLs can be downloaded from their website

Create a payment reply object RequestHandler Packagereqhandler = new RequestHandler (null);
      Initialization of Packagereqhandler.init ();
      Timestamp string timeStamp = Tenpayutil.gettimestamp ();
      Random string noncestr = Tenpayutil.getnoncestr (); Set up Package order parameters to generate Prepayid pre-payment ID packagereqhandler.setparameter ("AppID", account.     APPID); Public ID packagereqhandler.setparameter ("mch_id", account.     Partnertid);          Merchant number Packagereqhandler.setparameter ("Nonce_str", noncestr); Random string Packagereqhandler.setparameter (' body ', account.
      body); Packagereqhandler.setparameter ("Out_trade_no", account.    Orderserialid); Merchant Order number Packagereqhandler.setparameter ("Total_fee", account.          TotalAmount); The amount of merchandise to be divided into units (Money * 100). ToString () packagereqhandler.setparameter ("Spbill_create_ip", account.  REQUESTIP); User's public network IP, not merchant server IP packagereqhandler.setparameter ("Notify_url", account.      Notifyurl); The URL that receives the TENPAY notification packagereqhandler.seTparameter ("Trade_type", "Jsapi"); Transaction type Packagereqhandler.setparameter ("OpenID", account.)            OPENID); User's OpenID string sign = packagereqhandler.createmd5sign ("Key", account.
      Paysignkey);            Packagereqhandler.setparameter ("sign", sign); Signature string Prepayid = string.
        try {String data = Packagereqhandler.parsexml ();
        var result = Tenpayv3.unifiedorder (data);
        Mailhelp.sendmail ("Call Unified next single interface, the order result:--" +result+ "Request parameter:" +data);
        var res = Xdocument.parse (result); Prepayid = Res. Element ("xml"). Element ("prepay_id").
      Applog.write ("Call Unified next single interface to obtain advance payment Prepayid Success", AppLog.LogMessageType.Debug);
        catch (Exception ex) {applog.write ("Get to OpenID and Access_tokenu exception", AppLog.LogMessageType.Debug, ex);
        Mailhelp.sendmail ("Call Unified next single interface to get pre paid Prepayid exception:", ex);
      return null;

4, the formation of JSAPI micro-letter payment request parameters, to initiate payment

I am here to first assemble the micro-letter to pay the required parameters, and then create a call to the JS script

Generate JSAPI Payment parameters
      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"

Creating the Calling Script

private string Createweixinjs (Wechatjspayrequestmodel model) {string js = @ ' <script type= ' Text/javascript ' &
                Callpay ();
                    function Jsapicall () {weixinjsbridge.invoke (' getbrandwcpayrequest '), { Requestparam}, function (res) {if (res.err_msg = = ' Get_brand_
                    Wcpay_request:ok ') {window.location.href = ' successurl ';
                    }else{window.location.href = ' Failurl '; 
                    function Callpay () {if (typeof Weixinjsbridge = = ' undefined ') { if (Document.addeventlistener) {document.addeventlistener (' Weixinjsbridgeready '), Jsapi
                    Call, false); }else if (document.attachevent) {document. attachevent (' Weixinjsbridgeready ', jsapicall);
                    Document.attachevent (' Onweixinjsbridgeready ', jsapicall);
                  }}else{Jsapicall ();
      }} </script>; String Requestparam = String.
        Format (@ ' appId ': ' {0} ', ' TimeStamp ': ' {1} ', ' noncestr ': ' {2} ', ' package ': ' {3} ', ' Signtype ': ' {4} ', ' paysign ': ' {5} ' ', Model. AppId, model. TimeStamp, model. NONCESTR, model. Package, model. Signtype, model.
      Paysign); js = js. Replace ("Requestparam", Requestparam). Replace ("Successurl", model. Jumpurl + "&result=1"). Replace ("Failurl", model.
      Jumpurl + "&result=0");
      Applog.write ("Build executable script succeeded", AppLog.LogMessageType.Debug);
    Return JS;

5, receive the micro-credit payment callback for follow-up operations

Callback when the first need to verify that the signature is correct, to ensure security, signature verification after the subsequent operation, order status, notice what.

ResponseHandler Reshandler = new ResponseHandler (System.Web.HttpContext.Current);
      BOOL issuccess = _wechatpayserivce.processnotify (Reshandler);
      if (issuccess)
        string result = @ ' <xml>
                  <return_code><![ Cdata[success]]></return_code>
                  <return_msg><![ cdata[Payment Success]]></return_msg>
                 </xml> ";
        HttpContext.Response.Write (result);
        HttpContext.Response.End ();
      return new Emptyresult ();

There is one thing to note here is that the micro-credit payment callback when the micro-letter will be notified eight times, as if it is this number, so you need to receive the first notification of the status of the request in XML format in response to the micro-credit payment interface. Of course, you can not do this operation is also possible, and then callback every time to determine whether the order has been callback success, callback success is not processed on it.

Original link:

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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: 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.