Recently did the development of micro-letter public number payment, because it is the first time to do also grope for a few days, but also only to achieve the level of functionality, and not too much consideration of performance issues, so this article is more suitable for beginners.
The general public number of micro-credit payment is actually very simple, roughly divided into three steps. The first step is to obtain the user authorization; the second step calls the unified next single interface to obtain the pre-payment ID; The third step H5 to adjust the micro-letter to pay the built-in JS. The development process for each step is described below.
First of all to make clear that the micro-letter public number payment belongs to the web version of the payment, so compared to the app's direct access to the micro-letter to pay a step more micro-letter authorization. That is, you need to get the user's OpenID. The type of transaction used by the micro-credit public number is JSAPI, so the document that unifies the single interface is explicitly written to
So we have to get OpenID, and we can deal with some of the logic we need. There are two ways to obtain user authorization: 1.scope=snsapi_base;2.scope=snsapi_userinfo. I'm using Snsapi_base.
Scope is Snsapi_base
https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx520c15f417810387&redirect_uri=http%3A%2F% 2fchong.qq.com%2fphp%2findex.php%3fd%3d%26c%3dwxadapter%26m%3dmobiledeal%26showwxpaytitle%3d1%26vb2ctag%3d4_ 2030_5_1194_60&response_type=code&scope=snsapi_base&state=123
Scope is Snsapi_userinfo
https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf0e81c3bee622d60&redirect_uri=http%3A%2F% 2fnba.bluewebgame.com%2foauth_response.php&response_type=code&scope=snsapi_userinfo&state=state
The official document of the micro-letter also has a detailed description of each parameter, and I will explain the key parameters carefully. First of all, AppID will not say that is your micro-AppID fixed written dead, Redirect_uri This parameter is the most important, this address is to access your processing interface address. You can connect to this link on the parameters you need, generally you want to send the amount of the order to this interface, access to the link when the micro-letter will give you code you need to use it to obtain OpenID, remember to do it urlencode processing. The state parameter can be understood as an extended field, and other parameters are fixed and are not described in more detail. Here is the code snippet to get OpenID.
Get OpenID
httpclientutil util = Httpclientutil.getinstance ();
map<string, string> map = new hashmap<string, string> ();
Map.put ("AppID", wxpayconfig.appid);
Map.put ("Secret", Wxpayconfig.appsecret);
Map.put ("code", code);
Map.put ("Grant_type", wxpayconfig.grant_type);
String returnstr = util.dopostretstring ("Https://api.weixin.qq.com/sns/oauth2/access_token", null,map);
Logger.info ("returnstr:[" + Returnstr + "]");
Accesstoken at = json.parseobject (returnstr, Accesstoken.class);
Accesstoken.java
public class Accesstoken {private String access_token;
Private String expires_in;
Private String Refresh_token;
Private String OpenID;
Private String scope;
Private String Unionid;
Public String Getaccess_token () {return access_token;
} public void Setaccess_token (String access_token) {this.access_token = Access_token;
Public String getexpires_in () {return expires_in;
} public void setexpires_in (String expires_in) {this.expires_in = expires_in;
Public String Getrefresh_token () {return refresh_token;
} public void Setrefresh_token (String refresh_token) {this.refresh_token = Refresh_token;
Public String Getopenid () {return OpenID;
public void Setopenid (String OpenID) {This.openid = OpenID;
Public String Getscope () {return scope;
public void Setscope (String scope) {this.scope = scope;
Public String Getunionid () {return unionid; } public void Setunionid (STring Unionid) {This.unionid = Unionid;
@Override public String toString () {return "Accesstoken [access_token=" + Access_token + ", expires_in=" + expires_in + ", refresh_token=" + Refresh_token + ", openid=" + OpenID + ", scope=" + Scope + ", unionid=" + u
Nionid + "]";
}
}
Two after we have acquired OpenID, we can proceed to the next unified development of the next single. Micro-letter Unified the next single interface of the document written in more detail, the specific parameters of the meaning I do not introduce more. The following directly to the most intuitive code, the special reminder is sure to pay attention to the correct signature. The key used by the signature is not Appsecret but the merchant key that you defined yourself when you applied.
Unified under the single
wxpaysenddata data = new Wxpaysenddata ();
Data.setappid (wxpayconfig.appid);
Data.setattach ("Micro-letter Payment");
Data.setbody ("micro-credit public number payment");
DATA.SETMCH_ID (Wxpayconfig.mchid);
Data.setnonce_str (NONCESTR);
Data.setnotify_url (Wxpayconfig.notify_url);
Data.setout_trade_no (Tradeno);
Data.settotal_fee ((int) (fee*100));/unit: Minute
data.settrade_type ("Jsapi");
DATA.SETSPBILL_CREATE_IP (IP);
Data.setopenid (At.getopenid ());
String returnxml = Unifiedorderservice.unifiedorder (Data,wxpayconfig.key);
Wxpayreturndata redata = new Wxpayreturndata ();
XStream XS1 = new XStream (new Domdriver ());
Xs1.alias ("xml", Wxpayreturndata.class);
Redata = (wxpayreturndata) xs1.fromxml (returnxml);
Unifiedorderservice.java
public class Unifiedorderservice {private final static Logger Logger = Loggerfactory.getlogger (unifiedorderservice
. Class);
public static string Unifiedorder (Wxpaysenddata data,string key) {//Unified order payment String returnxml = null;
try {//Generate sign signature sortedmap<object,object> parameters = new treemap<object,object> ();
Parameters.put ("AppID", Data.getappid ());
Parameters.put ("Attach", Data.getattach ());
Parameters.put ("Body", data.getbody ());
Parameters.put ("mch_id", data.getmch_id ());
Parameters.put ("Nonce_str", Data.getnonce_str ());
Parameters.put ("Notify_url", Data.getnotify_url ());
Parameters.put ("Out_trade_no", Data.getout_trade_no ());
Parameters.put ("Total_fee", Data.gettotal_fee ());
Parameters.put ("Trade_type", Data.gettrade_type ());
Parameters.put ("Spbill_create_ip", Data.getspbill_create_ip ());
Parameters.put ("OpenID", Data.getopenid ()); Parameters.put ("Device_info", DAta.getdevice_info ());
Logger.info ("SIGN:" +wxsign.createsign (Parameters,key));
Data.setsign (Wxsign.createsign (Parameters,key));
XStream xs = new XStream (New Domdriver ("UTF-8", New Xmlfriendlynamecoder ("-_", "_"));
Xs.alias ("xml", Wxpaysenddata.class);
String XML = xs.toxml (data);
Logger.info ("Unified single XML as: \ n" + xml);
Httpclientutil util = Httpclientutil.getinstance ();
Returnxml = util.dopostforstring ("Https://api.mch.weixin.qq.com/pay/unifiedorder", null, XML);
Logger.info ("return result:" + returnxml);
catch (Exception e) {e.printstacktrace ();
return returnxml;
}
}
Wxsign
public class Wxsign {private static String characterencoding = "UTF-8";
@SuppressWarnings ("Rawtypes") public static String createsign (sortedmap<object,object> parameters,string key) {
StringBuffer sb = new StringBuffer ();
Set es = Parameters.entryset ();//All parameters participating in the argument are sorted by accsii (ascending) Iterator it = Es.iterator ();
while (It.hasnext ()) {Map.entry Entry = (map.entry) it.next ();
String k = (string) entry.getkey ();
Object v = entry.getvalue (); if (null!= v &&! "". Equals (v) &&! " Sign ". Equals (k) &&!"
Key ". Equals (k)) {Sb.append (k +" = "+ V +" & ");
} sb.append ("key=" + key);
String sign = Md5util.md5encode (Sb.tostring (), characterencoding). toUpperCase ();
return sign;
public static String Getnoncestr () {Random Random = new Random ();
Return Md5util.md5encode (string.valueof (Random.nextint (10000)), "UTF-8"); } public static String GettImestamp () {return string.valueof (System.currenttimemillis ()/1000);
}
}
The last thing to mention is the Notify_url callback address, which receives the micro-mail payment asynchronous notification callback address.
Three through the above operation we have received the pre-payment Trade statement logo prepay_id, so we can take the last step of the operation. Use H5 to tune the payment API.
H5
to pay Attr.addattribute ("AppId", Redata.getappid ());
Attr.addattribute ("TimeStamp", Wxsign.gettimestamp ());
Attr.addattribute ("Noncestr", Redata.getnonce_str ());
Attr.addattribute ("Package", "prepay_id=" +redata.getprepay_id ());
Attr.addattribute ("Signtype", "MD5");
sortedmap<object,object> Signmap = new treemap<object,object> ();
Signmap.put ("AppId", Redata.getappid ());
Signmap.put ("TimeStamp", Wxsign.gettimestamp ());
Signmap.put ("Noncestr", Redata.getnonce_str ());
Signmap.put ("Package", "prepay_id=" +redata.getprepay_id ());
Signmap.put ("Signtype", "MD5");
Logger.info ("Paysign:" +wxsign.createsign (Signmap,wxpayconfig.key));
Attr.addattribute ("Paysign", Wxsign.createsign (Signmap,wxpayconfig.key));
When you pass the required parameters to the page, use the micro-letter method to provide the payment.
<script> function Geturlparam (name) {//construct a regular expression object with a target parameter var reg = new RegExp (^|&) "+ name +" = (
[^&]*) (&|$) ");
Match Target parameter var r = Window.location.search.substr (1). Match (REG);
Returns the parameter value if (r!= null) return unescape (r[2]);
return null;
function Onbridgeready () {var appId = Geturlparam (' appId ');
var timeStamp = Geturlparam (' TimeStamp ');
var noncestr = Geturlparam (' noncestr ');
var Package = Geturlparam (' Package ');
var signtype = Geturlparam (' Signtype ');
var paysign = Geturlparam (' paysign '); Weixinjsbridge.invoke (' Getbrandwcpayrequest ', {"appId": appid,//"wx2421b1c4370ec43b",//public number name, incoming by merchant "time Stamp ": timestamp,//" 1395712654 ",//timestamp, number of seconds since 1970" Noncestr ": noncestr,//" e61463f8efa94090b1f366cccfbbb444 ",
Random string "package": package,//"prepay_id=u802345jgfjsdfgsdg888", "Signtype": signtype,//"MD5",//micro-letter Signature way: "Paysign": paysign,//"70ea570631e4bb79628fbca90534c63ff7fadd89 "//micro-letter Signature}, function (res) {//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 success, but does not guarantee that it is absolutely reliable.
alert (res.err_msg);
if (res.err_msg = = "Get_brand_wcpay_request:ok") {alert ("paid successfully");
} if (res.err_msg = = "Get_brand_wcpay_request:cancel") {alert ("Transaction cancellation");
} if (res.err_msg = = "Get_brand_wcpay_request:fail") {alert ("Payment failed");
}
});
function Callpay () {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 ();
}} </script>
You can customize some of your own return pages where you return the results.
Summary: Because I am also the first time to do, write this article is to record their work results, and share to the novice friends can have some help, and finally hope to have good insights friends can leave a message discussion, we learn to progress together.
The above is about the Java Development Micro-trust public pay all the content, I hope you can enjoy.