Today, we go on to talk about the micro-letter Payment Series tutorials, which we talked about in front of this micro-letter red envelope and sweep code payment. Now, let's talk about this public number payment. Public number to pay for the application environment common users through the public number, and then through the public number inside the menu link, into the public number of the mall, and then in the inside to complete the purchase and payment function, we can look at the official explanation of this public number payment scene, Link: https:// Pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_1, through this official explanation, we probably know what this public number is for, and I'm going to talk about the preparation for this public number.
1, download the micro-letter Web Developer tools, tools to use, also look at the link, address: https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1455784140&token =&lang=zh_cn
2, the configuration of "micro-letter Payment" environment, the following figure:
3, authorized to obtain user information, the following figure:
Here we go, step-by-step down.
First, we first develop the program, firstly, a new MVC project (asp.net words, the official demo is asp.net, you can download to refer to: https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?) Chapter=11_1), known as: micro-credit Payment public number payment, as shown below:
Then right-click the item and we'll modify the properties as shown below:
Then we will automatically generate the program HomeController.cs and view inside the delete, and then create a new HomeController.cs and add view, the code is as follows:
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Using SYSTEM.WEB.MVC;
Namespace Web.controllers
{public
class Homecontroller:controller
{
//get:home
Public ActionResult Index ()
{return
View ();
}
}
}
View Code:
@{
Layout = null;
}
<! DOCTYPE html>
Well, yes, it's still empty, and now we're starting to write the front desk, the code is as follows (I'll post the code to explain why, because if I write it step-by-step, according to the previous two, I think it's all ready to start, so I'll go over the code and explain it step-by-step.) ):
@{Layout = null;} <! DOCTYPE html>
The background code is as follows:
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Using SYSTEM.WEB.MVC;
Using Web.models;
Using Wxpayapi;
Namespace Web.controllers {public class Homecontroller:controller {Jsapipay Jsapipay = new Jsapipay (); Get:home public ActionResult Index () {if (session["OpenID"] = = null) {try {//Call "page licensing get user Information"
The mouth gets the user's OpenID and Access_token Getopenidandaccesstoken (); The catch (Exception ex) {//response.write (ex).
ToString ());
Throw
} return View (); /** * * * * Web page authorization to obtain the user's basic information of the entire process * Please refer to the website authorization to obtain user basic information: HTTP://MP.WEIXIN.QQ.COM/WIKI/17/C0F37D5704F0B64713D5D2C37B468D7
5.html * First step: Use URL jump to get code * Second step: Use the code to obtain OpenID and Access_token * * * * */public void Getopenidandaccesstoken () { if (session["code"]!= null) {//Get Code code to obtain OpenID and Access_token string code = session["Code"].
ToString (); Log.debug (this. GetType ().
ToString (), "Get Code:" + code); Jsapipay.getoPenidandaccesstokenfromcode (code);
else {//construct URL String host = Request.Url.Host for Web page authorization to get code;
string path = Request.path;
String Redirect_uri = Httputility.urlencode ("http://" + host + path);
String Redirect_uri = Httputility.urlencode ("Http://gzh.lmx.ren");
Wxpaydata data = new Wxpaydata (); Data.
SetValue ("AppID", wxpayconfig.appid); Data.
SetValue ("Redirect_uri", Redirect_uri); Data.
SetValue ("Response_type", "Code"); Data.
SetValue ("Scope", "snsapi_base"); Data.
SetValue ("state", "state" + "#wechat_redirect"); String url = "Https://open.weixin.qq.com/connect/oauth2/authorize?" + data.
Tourl (); Log.debug (this. GetType ().
ToString (), "'ll Redirect to URL:" + URL);
session["url"] = URL; }///<summary>///get code///</summary>///<returns></returns> [HttpPost] Pub
Lic ActionResult GetCode () {Object objresult = ""; if (session["url"]!= null) {Objresult = Session["url"].
ToString (); The else {objresult = "url is empty.
";
Return Json (Objresult); ///<summary>///through code in exchange for Web page authorization Access_token and OpenID return data///</summary>///<returns></retur
ns> [HttpPost] public ActionResult Getwxinfo () {Object objresult = "";
String strcode = request.form["code"]; if (session["access_token"] = = NULL | |
session["OpenID"] = = null) {Jsapipay.getopenidandaccesstokenfromcode (strcode); String straccess_token = session["Access_token"].
ToString (); String Stropenid = session["OpenID"].
ToString ();
Objresult = new {OpenID = Stropenid, Access_token = Straccess_token};
Return Json (Objresult); ///<summary>///Recharge///</summary>///<returns></returns> [httppost] public Ac
Tionresult Meterrecharge () {Object objresult = "";
String strtotal_fee = request.form["Totalfee"]; String Strfee = (double. Parse (strtotal_fee) * 100).
ToString ();
If the relevant parameters are passed, then unified the next single interface, to obtain the subsequent correlation interface of the entry parameters Jsapipay.openid = session["OpenID".
ToString (); Jsapipay.total_fee = Int.
Parse (Strfee); Jsapi Payment preprocessing try {string strbody = "South Masan micro-letter Payment";//Product description Wxpaydata Unifiedorderresult = Jsapipay.getunifiedorde
Rresult (strbody); Wxpaydata Wxjsapiparam = jsapipay.getjsapiparameters ()//Get H5 to tune up the JS API parameters, note that this refers to the official demo method, because the original method is to return string, so, To change the original method to the following code, the code is modelfororder aorder = new Modelfororder () {appId = Wxjsapiparam.getvalue ("AppId") in the next paragraph. ToString (), noncestr = Wxjsapiparam.getvalue ("Noncestr"). ToString (), Packagevalue = Wxjsapiparam.getvalue ("package"). ToString (), paysign = Wxjsapiparam.getvalue ("Paysign"). ToString (), TimeStamp = Wxjsapiparam.getvalue ("TimeStamp").
ToString (), msg = "The success of the order, is receiving a letter to pay."
};
Objresult = Aorder;
The catch (Exception ex) {Modelfororder aorder = new Modelfororder () {appId = "", Noncestr = "",
Packagevalue = "", Paysign = "", TimeStamp = "", msg = "Order failed, please try again, fail multiple times, please contact admin."};
Objresult = Aorder;
Return Json (Objresult);
}
}
}
Here is the code modified above, children's shoes please note
/** * * To obtain a micro-browser from the data successfully returned from the unified list Jsapi to pay the required parameters, * Micro-letter browser to adjust the JSAPI when the input parameter format is as follows: * {* "appId": "wx2421b1c4370ec43b", The name of the public number, introduced by the merchant * "TimeStamp": "1395712654",//timestamp, number of seconds since 1970 * "Noncestr": "e61463f8efa94090b1f366cccfbbb444", Random String * "package": "prepay_id=u802345jgfjsdfgsdg888", * "Signtype": "MD5",//micro-letter Signature way: * "paysign": "70ea57 0631e4bb79628fbca90534c63ff7fadd89 "//micro-letter Signature *} * @return string micro-letter browser to adjust the input parameters of JSAPI, JSON format can be directly used for the parameters of the * More detailed instructions please refer to the page to adjust the support
Pay Api:http://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_7 * * */public Wxpaydata getjsapiparameters () { Log.debug (this. GetType ().
ToString (), "Jsapipay::getjsapiparam is processing ...");
Wxpaydata Jsapiparam = new Wxpaydata ();
Jsapiparam.setvalue ("AppId", Unifiedorderresult.getvalue ("appId"));
Jsapiparam.setvalue ("TimeStamp", Wxpayapi.generatetimestamp ());
Jsapiparam.setvalue ("Noncestr", Wxpayapi.generatenoncestr ()); Jsapiparam.setvalue ("Package", "prepay_id=" + UnifiedorderResult.getvalue ("prepay_id"));
Jsapiparam.setvalue ("Signtype", "MD5");
Jsapiparam.setvalue ("Paysign", Jsapiparam.makesign ());
String parameters = Jsapiparam.tojson (); Log.debug (this. GetType ().
ToString (), "Get Jsapiparam:" + parameters);
return jsapiparam;
}
Code for the Modelfororder class:
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Namespace Web.models
{public
class Modelfororder
{public
string AppId {get; set;}
public string TimeStamp {get; set;}
public string Noncestr {get; set;}
public string Packagevalue {get; set;}
public string Paysign {get; set;}
public string, msg {get; set;}}}
There is another place to pay attention to, the change is here Wxlib/business/jsapipay.cs, the following figure:
Finally, the program is published, this time we publish the web on the Http://gzh.lmx.ren, and then the interface to the permissions, the following figure:
Notice that the domain name is the same as the domain name we published above.
In addition, we need to change here:
Is must authorize here, otherwise, pay the time, will prompt other error, concrete, I will not test.
In addition, here has actually completed the public number of the process of payment, but, on our page, will be friendly to remind (in fact, the hint is red, in the head, prompted not to enter the password what), this is because we have not put this http:// Gzh.lmx.ren domain name is set to secure domain name, after setting, will not be prompted. Set the method as shown below:
Join us in this domain, it is perfect ...
My code is as concise as possible, superfluous, I will lose, is to avoid confusing. If the code inside, there are not clearly written, you can DMS ask me, or group to ask me, group number at the end of the article.
Now, I'm beginning to explain what I've done.
First, at the back end, when the page loads, he will first perform
Public ActionResult Index ()
{
if (session["OpenID"] = = null)
{
try
{
//Call "Web page licensing get user Information" Interface to obtain the user's OpenID and Access_token
Getopenidandaccesstoken ();
}
catch (Exception ex)
{
//response.write (ex. ToString ());
Throw
}
}
return View ();
}
This is in order to obtain the user's OpenID and Access_token, this use is very big, and there is, we through the code can know, we through this method, can obtain the micro-letter some relevant information, after getting finished, he will return to our page, There is a session inside the URL, as follows:
session["url"] = URL;
Then, on the front end:
When the page is loaded, the following JS methods are executed, as follows:
$ (function () {
var vcode = getquerystring ("code");
if (Vcode!= "" && vcode!= null) {
//alert (vcode);
$.ajax ({
type: ' Post ',
data: {
code:vcode
},
URL: '/home/getwxinfo ',
success:function ( Sjson) {
//alert (Sjson);
var vdata = json.stringify (Sjson);
alert (vdata);
$.messager.show ({
title: ' Hint ',
msg: ' Welcome to the micro-credit Recharge Center. '
});
}
})
}
else {
$.ajax ({
type: ' Post ',
URL: '/home/getcode ',
success:function (Sjson) {
//alert ( Sjson);
Location.href = Sjson}}}
)
He will first get the browser URL, and then get code, is the general URL behind the xxx.com?code=xxx, which is the first to judge if there is no code, if there is no code, then, we go to the background request this code. Why do you ask for this code? Let's look at this method: Getwxinfo, as shown below:
<summary>
///Get code
///</summary>
///<returns></returns>
[HttpPost] Public
ActionResult GetCode ()
{
Object objresult = "";
if (session["url"]!= null)
{
objresult = session["url"]. ToString ();
}
else
{
objresult = "url is empty. ";
}
Return Json (Objresult);
He will return the URL to the front end, the front-end through JS to visit that URL, that is the micro-client access to our information, to us according to the rules to return a URL, this rul is behind the need to go after the code URL. This code is important to us because we need to do the work that is related to payment in the back. With code, we can get OpenID and Access_token. The logic of the code can be seen in detail.
OK, so come this way, we already know about OpenID and Access_token, and at this point we're going to take care of the front-end stuff.
Front end, I will be an amount of input box, and then a submission, the actual application, we certainly also need to import the parameters of the product, I do not write those redundant, the follow-up you add to it. When you click Submit, you will invoke the micro-letter environment and look at the following code:
Initialization of the micro-credit payment environment
function Fcharge () {
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 {
fpostcharge ();
}
}
He will initialize the environment, if the initialization of the success, the representative, this page is in the micro-letter client running, then we will give him to run our real recharge code submitted, so, will be implemented: Fpostcharge ();
After the submission, you will enter the background, the background needs to organize our front desk need to use the parameters, including the following:
<summary>///Recharge///</summary>///<returns></returns> [httppost] public actionres
Ult Meterrecharge () {Object objresult = "";
String strtotal_fee = request.form["Totalfee"]; String Strfee = (double. Parse (strtotal_fee) * 100).
ToString (); If the relevant parameters are passed, then unified the next single interface, to obtain the subsequent correlation interface of the entry parameters Jsapipay.openid = session["OpenID".
ToString (); Jsapipay.total_fee = Int.
Parse (Strfee); Jsapi Payment preprocessing try {string strbody = "South Masan micro-letter Payment";//Product description Wxpaydata Unifiedorderresult = Jsapipay.getunifiedorde
Rresult (strbody);
Wxpaydata Wxjsapiparam = jsapipay.getjsapiparameters ()//Get H5 Tune JS API parameter Modelfororder = new Aorder () {appId = Wxjsapiparam.getvalue ("AppId"). ToString (), noncestr = Wxjsapiparam.getvalue ("Noncestr"). ToString (), Packagevalue = Wxjsapiparam.getvalue ("package"). ToString (), paysign = Wxjsapiparam.getvalue ("Paysign"). ToString (), TimeStamp = Wxjsapiparam.getvalue ("TimeStamp"). ToString (), msg = "The success of the order, is receiving a letter to pay."
};
Objresult = Aorder;
The catch (Exception ex) {Modelfororder aorder = new Modelfororder () {appId = "", Noncestr = "",
Packagevalue = "", Paysign = "", TimeStamp = ", msg =" Order failed, please try again, please contact admin. "};
Objresult = Aorder;
Return Json (Objresult);
}
The main thing we need to provide is the parameters in this class Modelfororder, and then return these parameters to the foreground call, as follows:
Call the micro-payment module
function Onbridgeready (JSON) {
weixinjsbridge.invoke (
' getbrandwcpayrequest ', {
"appId ": Json.appid, //Public number name, by merchant incoming
" TimeStamp ": Json.timestamp, //timestamp, number of seconds since 1970
" Noncestr ": JSON.NONCESTR,//random string
"package": Json.packagevalue,
"Signtype": "MD5",// micro-letter Signature way:
"paysign": Json.paysign//micro-letter Signature
},
function (res) {
if (res.err_msg = = "Get_brand_wcpay_request:ok") {
// Alert ("Payment successful, please check the balance later, if in doubt, please contact the Administrator.");
Falreadypay ();
} Use the above method to judge the front end return, the micro-letter team solemnly prompts: Res.err_msg will return OK after the user pays successfully, but does not guarantee that it is absolutely reliable.
}
);
In this way, he will pop up a micro-mail payment window as follows:
Then we confirm payment, whether payment is successful, if payment succeeds, we are in execution: Falreadypay ();
This method has been deleted by me, use is used, we received the user's paragraph, we need to sync some data into our database, so, how to operate, their own changes.
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.