C # MVC Micro-Credit Payment tutorial series sweep code Payment code Instance _c# Tutorial

Source: Internet
Author: User
Tags foreach datetime flush json min openid time limit ticket

Today, let's explore this micro-credit-sweep-code payment. What is the sweep code payment? In this, the sweep of the code is two-dimensional code, we often sweep the kind of two-dimensional code pictures, for example, we add our own friends, you can enter the other's micro-signal, you can sweep the other side of the two-dimensional code. Sweep code payment, as a micro-credit payment inside, an indispensable function, the payment of goods provides a very convenient experience, the use is very much.

For example, the vending machines that are common in subways and bus stations (yes, that kind of machine that makes coins and can be shipped automatically) are used. Micro-letter (Alipay) The appearance of the sweep code payment, greatly reducing the risk in this regard, in recent years, the application of two-dimensional code more and more widely, and even some places, directly used for automatic ticketing (is to set the starting point, the fare set well, directly to the two-dimensional code posted out, so that passengers automatically sweep the relevant two-dimensional code, complete the purchase of tickets, on the bus , only need to provide their own payment voucher to the bus to verify it), in this way, not only green environmental protection, but also greatly improve the speed of ticket sales (to go to the big station to buy tickets should be a deep experience, queue for a ticket, at least half an hour or more, in the mind is also million head grass mud horse in the Pentium).

We will not pull far, said back to us today to do the micro-letter payment of sweeping code to pay. Micro-Credit Official document, this sweep code payment (Nativepay) is divided into two kinds, one is "Generate scan payment mode", the other is "generate direct payment URL, payment URL is valid for 2 hours", as for this, two sweep code mode, how to use it flexibly, the official also did not have a clear explanation. Personally, the first type (Generate scan payment mode), which applies to fixed two-dimensional codes, is the one that is permanently used.

For example, some merchant's two-dimensional code of the public number, is permanent, when sweeping, is to pay attention to this public number, but, this kind of words, I remember the micro-letter is a finite amount, seemingly is a public number, limited 10w, personal view, feel that this limit is enough for us to use. The second (Generate a direct payment URL, the payment URL is valid for a period of 2 hours, this is the case, because there is a valid time limit, more than 2 hours, the two-dimensional code is invalid, but there is no limit to the number of two-dimensional code generated, so, this personal view is applicable to the kind of temporary based on the reality of two-dimensional code, For example: the public platform when landing two of the two-dimension code validation, custom generation, only for one-time payment of the use of two-dimensional code, and so on. Next, let's start with a practical example of the first model.

Sweep Code Payment mode one (Generate Scan payment mode):

First of all, we create a new "MVC" project (ASP.net's official demo is, to ASP.net to see the demo bar, demo address: https://pay.weixin.qq.com/wiki/doc/api/jsapi.php Chapter=11_1), and then delete the system automatically generated Homecontroler and view home.

Then create a new Homecontroler yourself, the code is as follows:

 Get:home public
 ActionResult Index ()
 {return
  View ();
 

Add another view with the following code:

@{
 Layout = null;
}
<! DOCTYPE html>
 
 

Next, we'll copy the official demo Some of the things we're going to use, including the following folders, as shown below:

For this Lib and business two, put these two folders, pay the copy into our new project and include in the project as follows:

We then "regenerate" the following items, or shortcuts: Ctrl+shift+b, this time, the following error will be mentioned:

At this time, we go to add the reference, the Lib folder in the LitJson.dll add to it, the following figure:

Here, we basically put the official demo environment to build up, next, we will begin to write code.

First of all, my logic is, from the front to the back end. The front end is the place that displays the two-dimensional code, then we give him a div first (this article uses the jquery two-dimensional code generation plug-in, Full name: Jquery.qrcode.min.js, I will upload to the attachment, and then when the page loaded, will request the background, let him return the two-dimensional code string, and then through jquery two-dimensional code generation Plug-ins, let him generate two-dimensional code and display in the foreground, the code is as follows:

Front:

@{Layout = null;} &lt;! DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta name= "viewport" content= "Width=device-width"/&gt; &lt;title&gt; Home
 &lt;/title&gt; &lt;link href= "~/scripts/jquery-easyui-1.4.5/themes/bootstrap/easyui.css" rel= "stylesheet"/&gt; &lt;link href= "~/scripts/jquery-easyui-1.4.5/themes/mobile.css" rel= "stylesheet"/&gt; &lt;link href= "~/Scripts/" Jquery-easyui-1.4.5/themes/icon.css "rel=" stylesheet "/&gt; &lt;/head&gt; &lt;body&gt; &lt;p&gt; mode one: Generate Scan payment mode &LT;BR /&gt; &lt;div id= "QRCode1" &gt; &lt;/div&gt; &lt;/p&gt; &lt;p&gt; mode two: Generate Direct payment URL, payment URL is valid for 2 hours &lt;br/&gt; &lt;d IV id= "QRCode2" &gt; &lt;/div&gt; &lt;/p&gt; &lt;script src= "~/scripts/jquery-1.10.2.js" &gt;&lt;/script&gt; &lt;scrip T src= "~/scripts/jquery-easyui-1.4.5/jquery.easyui.min.js" &gt;&lt;/script&gt; &lt;script src= "~/scripts/ Jquery-easyui-1.4.5/jquery.easyui.mobile.js "&gt;&lt;/script&gt; &lt;script src=" ~/scripts/jquery-easyui-1.4.5/ Easyloader.js "&gt;&lt;/script&gt; &lt;script Src= "~/scripts/jquery.qrcode.min.js" &gt;&lt;/script&gt; &lt;script type= "Text/javascript" &gt; $ (function () {FGETQ
  RCode1 ();
   function FGetQRCode1 () {$.messager.progress ({title: "", msg: "Generating two-dimensional code: mode one, please later ..."});
    $.ajax ({type: "post", url: "/home/getqrcode1", data: {time:new Date (), productid:7788}, Success:function (JSON) {$.messager.progress (' close ');/remember to turn off if (Json.result) {$ (' #QRCode1 '). QRCode (JSO N.STR);
     Generate a two-dimensional code} else {$ (' #QRCode1 '). HTML ("Two-dimensional code generation failed");

 }}}) &lt;/script&gt; &lt;/body&gt; &lt;/html&gt;

Back-end:

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Using SYSTEM.WEB.MVC;
Using Wxpayapi;
  Namespace Wxpay.controllers {public class Homecontroller:controller {//Get:home public ActionResult Index ()
  {return View (); ///&lt;summary&gt;///mode one///&lt;/summary&gt;///&lt;returns&gt;&lt;/returns&gt; [httppost] public actio
   Nresult GetQRCode1 () {Object objresult = "";
   string strProductID = request.form["ProductId"];
   String strqrcodestr = Getprepayurl (strProductID); if (!string.
   Isnullorwhitespace (strProductID)) {Objresult = new {result = true, str = STRQRCODESTR};
   else {Objresult = new {result = false};
  Return Json (Objresult);
  /** * Generate scan payment mode one URL * @param productId commodity ID * @return mode one URL/public string Getprepayurl (string productId)
   {Wxpaydata data = new Wxpaydata (); Data. SetValue ("AppID", wxpayconfig.appid)//Public account ID data. SetValue ("mch_id", WxpayConfig.mchid)//merchant Number data. SetValue ("Time_stamp", Wxpayapi.generatetimestamp ());/time stamp data. SetValue ("Nonce_str", Wxpayapi.generatenoncestr ());//random string data. SetValue ("product_id", productId);//commodity ID data. SetValue ("sign", data. Makesign ());//signature String str = tourlparams (data.
   GetValues ());//Convert to URL string string url = "Weixin://wxpay/bizpayurl?" + str;
  return URL; /** * parameter array is converted to URL format * @param map parameter name and parameter value mapping table * @return URL String */private string Tourlparams (sorteddictionary&
   Lt;string, object&gt; map) {String buff = ""; foreach (keyvaluepair&lt;string, object&gt; pair in map) {buff = = pair. Key + "=" + pair.
   Value + "&amp;"; } buff = buff.
   Trim (' &amp; ');
  return buff;
 }
 }
}

At this time, the mode is not a feeling is completed? So let's try it now and we'll browse the page as follows:

Then with a micro-scan sweep function scan, found that the hint is as follows:

What the hell is this, isn't it, do you want to know why, then I tell you, this is why, this is because, you have not set the callback page or callback page has a problem, this time, we create a new control, Named: NativeNotifyController.cs, the code is as follows:

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Web;
Using SYSTEM.WEB.MVC;
Using Wxpayapi; Namespace Wxpay.controllers {public class Nativenotifycontroller:controller {//Get:nativenotify public Actionr
   Esult Index () {String strdata = Processnotify ();
   Response.Write (strdata);
  return View ();
   public string processnotify () {Wxpaydata notifydata = Getnotifydata (); Check if OpenID and product_id return if (!notifydata.isset ("OpenID") | | |!notifydata.isset ("product_id")) {Wxpaydata res =
    New Wxpaydata (); Res.
    SetValue ("Return_code", "FAIL"); Res.
    SetValue ("Return_msg", "Callback data Exception"); return Res.
   TOXML (); //Tune unified next single interface, get the next single result string OpenID = Notifydata.getvalue ("OpenID").
   ToString (); String product_id = Notifydata.getvalue ("product_id").
   ToString ();
   Wxpaydata Unifiedorderresult = new Wxpaydata ();
   try {unifiedorderresult = Unifiedorder (OpenID, product_id); catch (ExceptionEX)//If an exception is thrown when a single interface is tuned, the result is returned immediately to the micro-letter payment Background {wxpaydata res = new Wxpaydata (); Res.
    SetValue ("Return_code", "FAIL"); Res.
    SetValue ("Return_msg", "Unified next single Failure"); return Res.
   TOXML (); ///If the order fails, return the result immediately to the micro-letter payment background if (!unifiedorderresult.isset ("AppID") | |!unifiedorderresult.isset ("mch_id") | |!unifiedor
    Derresult.isset ("prepay_id")) {wxpaydata res = new Wxpaydata (); Res.
    SetValue ("Return_code", "FAIL"); Res.
    SetValue ("Return_msg", "Unified next single Failure"); return Res.
   TOXML ();
   ///Unified under single success, then return successful results to micro-letter payment background Wxpaydata data = new Wxpaydata (); Data.
   SetValue ("Return_code", "SUCCESS"); Data.
   SetValue ("Return_msg", "OK"); Data.
   SetValue ("AppID", wxpayconfig.appid); Data.
   SetValue ("mch_id", Wxpayconfig.mchid); Data.
   SetValue ("Nonce_str", Wxpayapi.generatenoncestr ()); Data.
   SetValue ("prepay_id", Unifiedorderresult.getvalue ("prepay_id")); Data.
   SetValue ("Result_code", "SUCCESS"); Data.
   SetValue ("Err_code_des", "OK"); Data. SetValue ("sign", data.
   Makesign ()); ReturnData.
  TOXML (); ///&lt;summary&gt;///receives data sent from the micro-letter payment background and verifies the signature///&lt;/summary&gt;///&lt;returns&gt; micro-letter payment background returned data &lt;/returns&gt
  ;
   Public Wxpaydata Getnotifydata () {//Receive data from micro-letter backend post System.IO.Stream s = request.inputstream;
   int count = 0;
   byte[] buffer = new byte[1024];
   StringBuilder builder = new StringBuilder (); while ((count = s.read (buffer, 0, 1024)) &gt; 0) {Builder.
   Append (Encoding.UTF8.GetString (buffer, 0, count));
   } s.flush ();
   S.close ();
   S.dispose ();
   Converts the data format and verifies the signature wxpaydata data = new Wxpaydata (); try {data. FromXml (builder.
   ToString ());
    The catch (Wxpayexception ex) {//If the signature is incorrect, returns the result immediately to the micro-letter payment background Wxpaydata res = new Wxpaydata (); Res.
    SetValue ("Return_code", "FAIL"); Res. SetValue ("Return_msg", ex.
   message);
  } return data;
   Private Wxpaydata Unifiedorder (string openId, String productId) {//Unified under single wxpaydata req = new Wxpaydata (); Req.
   SetValue ("Body", "Guangdong XXXX Co., Ltd."); Req. SetValue ("Attach", "additional information, used in the background or in the database, to make their own judgments"); Req.
   SetValue ("Out_trade_no", Wxpayapi.generateouttradeno ()); Req.
   SetValue ("Total_fee", 1); Req.
   SetValue ("Time_start", DateTime.Now.ToString ("Yyyymmddhhmmss")); Req. SetValue ("Time_expire", DateTime.Now.AddMinutes (10).
   ToString ("Yyyymmddhhmmss")); Req.
   SetValue ("Goods_tag", "the product of the memo, can be customized"); Req.
   SetValue ("Trade_type", "NATIVE"); Req.
   SetValue ("OpenID", OpenID); Req.
   SetValue ("product_id", productId);
   Wxpaydata result = Wxpayapi.unifiedorder (req);
  return result;

 }
 }
}

Remember, also want to create a view, is in the index, right to add a View,view code as follows (you are not dizzy, is empty, regardless of him):

@{
 Layout = null;
}
<! DOCTYPE html>
 
 

And then, put this project, posted to IIS on the server, which I posted on the http://sm.lmx.ren/(must be posted to the Internet ha, if you do not understand the release, you can learn the basics first), this is not finished, but also need to put on the public platform, Set up a callback page, which operates as follows:

So, it's done. At this time, we try to scan the code again, found that the following hints have been given, this way, on behalf of our model one, has been successfully completed. The following figure:

At this time, the careful friend will ask questions, I this all pays successfully, how the page does not have any prompt, this page does not interact very is not friendly. Well, yes, child shoes, you have a future, I will tell you now, how to do interactive, but, for your future more promising, I only tell you the logic, concrete how to achieve, I think, more brain.

So what is the logic? In general logic, when we scan this two-dimensional code on the page, this time, he has passed the parameters inside our two-dimensional code to the micro-server, and then they begin to unify the order (if the logic is unclear, look at the official documentation: https://pay.weixin.qq.com/ Wiki/doc/api/native.php?chapter=6_3): When they unify the order, they will generate a product_id, this guy's role is to tell you now micro-trust server, has generated a single number, Labor has received your payment request , hurriedly pay to Lao Tze, O (∩_∩) o haha ~ ... Stop, stop, stop. At this time, the idea can not continue to go down.

Remember, there is a front called "Unified Order," then if there is this step, then we can use, that is, when he unified the success of the next single, we can update the status of the page, tell the customer: You have successfully scanned, and the order of success, please pay. is not that we can prompt them this. Then wait for the user on the phone, pay success, this time, the page is not also to feedback to the user, tell him, boy, your money has come to my pocket, you can go (you go, I do not have your baby). O (∩_∩) o haha ~, but, you have to stop, stop, stop. How do our service companies know that this micro-trust user has already paid for it? Here, let's go back to the code and find Lib/config.cs, as shown below:

Then open Config.cs and locate the following code:

By the right, you are very clever. The micro-letter processing logic is that, after the user pays success, he will send the link to the payment results, default is the previous ASPX page, now I replaced MVC, so we have to manually create a new control, named: Resultnotifycontroller, Then the code is as follows:

Using LmxPublic.Log;
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Web;
Using SYSTEM.WEB.MVC;
Using Wxpayapi; Namespace Wxpay.controllers {public class Resultnotifycontroller:controller {//Get:resultnotify public Actionr
   Esult Index () {String strdata = Processnotify ();
   Response.Write (strdata);
  return View ();
   public string processnotify () {Wxpaydata notifydata = Getnotifydata (); Check the payment result for transaction_id existence if (!notifydata.isset ("transaction_id")) {//If transaction_id does not exist, return the result immediately to the micro-letter payment background W
    Xpaydata res = new Wxpaydata (); Res.
    SetValue ("Return_code", "FAIL"); Res.
    SetValue ("Return_msg", "The result of the payment of the micro-letter order number does not exist"); return Res.
   TOXML (); String transaction_id = Notifydata.getvalue ("transaction_id").
   ToString (); Check the order to determine the authenticity of the order if (!
    Queryorder (transaction_id)) {//If the order query fails, return the result immediately to the micro-letter payment background Wxpaydata res = new Wxpaydata (); Res.
    SetValue ("Return_code", "FAIL"); Res. SetValue ("Return_msg", "Order query failed"); return Res.
   TOXML ();
    //Query Order success Else {Wxpaydata res = new Wxpaydata (); Res.
    SetValue ("Return_code", "SUCCESS"); Res.
    SetValue ("Return_msg", "OK"); Log.info (this. GetType (). ToString (), "Order Query success:" + Res.
    TOXML ()); String strxml = Res.
    TOXML ();
    Filelog.writelog (strxml); return Res.
   TOXML ()//If we come to this step, it means that the user has paid the success, so, what to do. }///&lt;summary&gt;///receives data sent from the micro-mail payment background and verifies the signature///&lt;/summary&gt;///&lt;returns&gt; micro-letter payment background Data &lt;/return
   S&gt; public Wxpaydata Getnotifydata () {//Receive data from the micro-letter backend post System.IO.Stream s = request.inputstream;
   int count = 0;
   byte[] buffer = new byte[1024];
   StringBuilder builder = new StringBuilder (); while ((count = s.read (buffer, 0, 1024)) &gt; 0) {Builder.
   Append (Encoding.UTF8.GetString (buffer, 0, count));
   } s.flush ();
   S.close ();
   S.dispose (); Log.info (this. GetType (). ToString (), "Receive data from WeChat:" + Builder. ToStRing ());
   Converts the data format and verifies the signature wxpaydata data = new Wxpaydata (); try {data. FromXml (builder.
   ToString ());
    The catch (Wxpayexception ex) {//If the signature is incorrect, returns the result immediately to the micro-letter payment background Wxpaydata res = new Wxpaydata (); Res.
    SetValue ("Return_code", "FAIL"); Res. SetValue ("Return_msg", ex.
    message); Log.error (this. GetType (). ToString (), "Sign Check Error:" + Res.
    TOXML ());
   return res;
  } return data;
   //Query Order private bool Queryorder (string transaction_id) {Wxpaydata req = new Wxpaydata (); Req.
   SetValue ("transaction_id", transaction_id);
   Wxpaydata res = wxpayapi.orderquery (req); if (res. GetValue ("Return_code"). ToString () = = "SUCCESS" &amp;&amp; Res. GetValue ("Result_code").
   ToString () = = "SUCCESS") {return true;
   else {return false;

 }
  }
 }
}

Foreground, yes, is also to create a view, the code is as follows (yes, is also empty)

@{
 Layout = null;
}
<! DOCTYPE html>
 
 

All right, the pattern is here. Did not think Ah, a model one, let me write from the morning to the afternoon, really tired ... There is also a pattern two ... Drink your saliva first, let's go.

OK, drink the water, then dry, and here is mode two:

Mode two (Generate direct payment URL, payment URL is valid for 2 hours)

Because there is a detailed description of the model above, mode two, I will be simple to say, if you do not understand, to the group to ask me.

Mode two, front end, add some code, as follows (complete, including pattern one's code):

@{Layout = null;} &lt;! DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta name= "viewport" content= "Width=device-width"/&gt; &lt;title&gt; Home
 &lt;/title&gt; &lt;link href= "~/scripts/jquery-easyui-1.4.5/themes/bootstrap/easyui.css" rel= "stylesheet"/&gt; &lt;link href= "~/scripts/jquery-easyui-1.4.5/themes/mobile.css" rel= "stylesheet"/&gt; &lt;link href= "~/Scripts/" Jquery-easyui-1.4.5/themes/icon.css "rel=" stylesheet "/&gt; &lt;/head&gt; &lt;body&gt; &lt;p&gt; mode one: Generate Scan payment mode &LT;BR /&gt; &lt;div id= "QRCode1" &gt; &lt;/div&gt; &lt;/p&gt; &lt;p&gt; mode two: Generate Direct payment URL, payment URL is valid for 2 hours &lt;br/&gt; &lt;d IV id= "QRCode2" &gt; &lt;/div&gt; &lt;/p&gt; &lt;script src= "~/scripts/jquery-1.10.2.js" &gt;&lt;/script&gt; &lt;scrip T src= "~/scripts/jquery-easyui-1.4.5/jquery.easyui.min.js" &gt;&lt;/script&gt; &lt;script src= "~/scripts/ Jquery-easyui-1.4.5/jquery.easyui.mobile.js "&gt;&lt;/script&gt; &lt;script src=" ~/scripts/jquery-easyui-1.4.5/ Easyloader.js "&gt;&lt;/script&gt; &lt;script Src= "~/scripts/jquery.qrcode.min.js" &gt;&lt;/script&gt; &lt;script type= "Text/javascript" &gt; $ (function () {FGETQ
  RCode1 ();
   function FGetQRCode1 () {$.messager.progress ({title: "", msg: "Generating two-dimensional code: mode one, please later ..."});
    $.ajax ({type: "post", url: "/home/getqrcode1", data: {time:new Date (), productid:7788}, Success:function (JSON) {$.messager.progress (' close ');/remember to turn off if (Json.result) {$ (' #QRCode1 '). QRCode (JSO N.STR);
     Generate a two-dimensional code} else {$ (' #QRCode1 '). HTML ("Two-dimensional code generation failed");
    } fGetQRCode2 ();
     }, Error:function (JSON) {$ (' #QRCode1 '). HTML ("Two-dimensional code generation failed");
    FGetQRCode2 ();
   }}} function FGetQRCode2 () {$.messager.progress ({title: "", msg: "Generating two-dimensional code: mode two, please later ..."});
    $.ajax ({type: "post", url: "/home/getqrcode2", data: {time:new Date (), productid:7788}, Success:function (JSON) {$.messager.progress (' close ');//Remember to turn off if (Json.result) {$ (' #QRCode2 '). QRCode (JSON.STR);//Generate two-dimensional code} else {$ (' #QRCode2 '). HTML ("Two-dimensional code generation failed");
    }, Error:function (JSON) {$ (' #QRCode2 '). HTML ("Two-dimensional code generation failed");

 }}) &lt;/script&gt; &lt;/body&gt; &lt;/html&gt;

Back-end:

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Using SYSTEM.WEB.MVC;
Using Wxpayapi;
  Namespace Wxpay.controllers {public class Homecontroller:controller {//Get:home public ActionResult Index ()
  {return View (); ///&lt;summary&gt;///mode one///&lt;/summary&gt;///&lt;returns&gt;&lt;/returns&gt; [httppost] public actio
   Nresult GetQRCode1 () {Object objresult = "";
   string strProductID = request.form["ProductId"];
   String strqrcodestr = Getprepayurl (strProductID); if (!string.
   Isnullorwhitespace (strProductID)) {Objresult = new {result = true, str = STRQRCODESTR};
   else {Objresult = new {result = false};
  Return Json (Objresult); ///&lt;summary&gt;///mode two///&lt;/summary&gt;///&lt;returns&gt;&lt;/returns&gt; [httppost] public actio
   Nresult GetQRCode2 () {Object objresult = "";
   string strProductID = request.form["ProductId"]; String strqrcodestr = Getpayurl (strProductID); if (!string.
   Isnullorwhitespace (strProductID)) {Objresult = new {result = true, str = STRQRCODESTR};
   else {Objresult = new {result = false};
  Return Json (Objresult);
  /** * Generate scan payment mode one URL * @param productId commodity ID * @return mode one URL/public string Getprepayurl (string productId)
   {Wxpaydata data = new Wxpaydata (); Data. SetValue ("AppID", wxpayconfig.appid)//Public account ID data. SetValue ("mch_id", Wxpayconfig.mchid)//merchant Number data. SetValue ("Time_stamp", Wxpayapi.generatetimestamp ());/time stamp data. SetValue ("Nonce_str", Wxpayapi.generatenoncestr ());//random string data. SetValue ("product_id", productId);//commodity ID data. SetValue ("sign", data. Makesign ());//signature String str = tourlparams (data.
   GetValues ());//Convert to URL string string url = "Weixin://wxpay/bizpayurl?" + str;
  return URL; /** * parameter array is converted to URL format * @param map parameter name and parameter value mapping table * @return URL String */private string Tourlparams (sorteddictionary& lt;string, Object&gt; map) {String buff = ""; foreach (keyvaluepair&lt;string, object&gt; pair in map) {buff = = pair. Key + "=" + pair.
   Value + "&amp;"; } buff = buff.
   Trim (' &amp; ');
  return buff; /** * Generate direct Payment URL, payment URL is valid for 2 hours, Mode II * @param productId Commodity ID * @return mode two URL/public string Getpayurl (string
   PRODUCTID) {Wxpaydata data = new Wxpaydata (); Data. SetValue ("Body", "Guangdong XXXX Co., Ltd.")//Product description data. SetValue ("Attach", "additional information, used in the background or in the database, make your own judgment");/Append data. SetValue ("Out_trade_no", Wxpayapi.generateouttradeno ());//random string data. SetValue ("Total_fee", 1);//Total amount data. SetValue ("Time_start", DateTime.Now.ToString ("YYYYMMDDHHMMSS"))//Transaction start time data. SetValue ("Time_expire", DateTime.Now.AddMinutes (10). ToString ("YYYYMMDDHHMMSS"))//Transaction end time data. SetValue ("Goods_tag", "product memo, can be customized");//Mark data. SetValue ("Trade_type", "NATIVE");//transaction type data. SetValue ("product_id", productId);//Product ID wxpaydata result = wxpayapi.unifiedorder (data);//Invoke Uniform down-interface String url = ResU LT.getvalue ("Code_url").
  ToString ();//Get the two-dimensional Code link return URL returned by the unified next single interface;

 }
 }
}

Hereby correct, thanks to "abc54288" point of view, mode two also has callback, the callback interface is set in Config.cs, in the following figure:

So the following is invalid, but if you need to manually query the order, you can also use the following methods to query. Thanks again to the Garden friends: "abc54288".

Since mode two is not the result of the payment callback, so we have to query the success of the payment, we need to write their own methods to query, the official offer of inquiries to pay the success or failure of the following methods,

/***
  * Order query Complete Business process Logic
  * @param transaction_id Micro-letter order number (preferred)
  * @param out_trade_no Merchant Order number
  * @return Order query Results (XML format)
  */public
  static string Run (String transaction_id, String out_trade_no)
  {
   Log.info (" Orderquery "," orderquery is processing ... ");
   Wxpaydata data = new Wxpaydata ();
   if (!string. IsNullOrEmpty (transaction_id)//If the micro-letter order number exists, then the micro-letter order number is the
   {
    data. SetValue ("transaction_id", transaction_id);
   }
   else//Micro-letter order number does not exist, only according to the merchant order number to check the list
   {
    data. SetValue ("Out_trade_no", out_trade_no);
   }
   Wxpaydata result = wxpayapi.orderquery (data);//Submit order query request to API, receive return Data
   log.info ("Orderquery", "orderquery process Complete, Result: "+ result." TOXML ());
   return result. Toprintstr ();
  }

This micro-letter order number (TRANSACTION_ID) can be queried through the merchant Order number (OUT_TRADE_NO), so we have to make reasonable use of this technique, the above mode two, I use the out_trade_no is a random string, We can put this string record good, put the database or put where, you like, and then write a ajsx long poll, the time to inquire about the merchant order number, to see if there is a successful payment to make payment confirmation.

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