To use JSAPI for micro-credit payment, first to obtain a prepay_id from the micro-letter, and then by calling the Jsapi of the micro-letter to complete the payment, the JS API return results Get_brand_wcpay_request:ok only when the user successfully completed the payment return. Because of the complex front-end interaction, get_brand_wcpay_request:cancel or get_brand_wcpay_request:fail can be unified processing for users to encounter errors or unsolicited, do not need to refine the distinction. The
sample code is as follows:
function Onbridgeready () {
weixinjsbridge.invoke (
' getbrandwcpayrequest ', {
"appId": " wx2421b1c4370ec43b ",//public number name, by merchant incoming
" TimeStamp ":" 1395712654 ", //timestamp, seconds since 1970
" Noncestr ":" e61463f8efa94090b1f366cccfbbb444 ",//Random string
" package ":" u802345jgfjsdfgsdg888 ",
" Signtype ":" MD5 ", // Micro-letter Signature mode:
"paysign": "70ea570631e4bb79628fbca90534c63ff7fadd89"//micro-letter Signature
},
function (res) {
if ( Res.err_msg = = "Get_brand_wcpay_request:ok") {}//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.
}
);
}
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 ();
}
The parameters passed in above are package, that is prepay_id
The following is to get parameters to invoke Jsapi
when we call JSAPI, we must obtain the user's OpenID (Trade_type=jsapi,openid is required).
to first define a requested object:
Package com.unstoppedable.protocol;
Import Com.unstoppedable.common.Configure;
Import Com.unstoppedable.common.HttpService;
Import Com.unstoppedable.common.RandomStringGenerator;
Import Com.unstoppedable.common.Signature;
Import Java.lang.reflect.Field;
Import Java.util.HashMap;
Import Java.util.Map;
public class Unifiedorderreqdata {private String AppID;
Private String mch_id;
Private String Device_info;
Private String nonce_str;
Private String sign;
Private String body;
Private String detail;
Private String attach;
Private String out_trade_no;
Private String Fee_type;
private int total_fee;
Private String spbill_create_ip;
Private String Time_start;
Private String Time_expire;
Private String Goods_tag;
Private String Notify_url;
Private String Trade_type;
Private String product_id;
Private String Limit_pay;
Private String OpenID;
Private Unifiedorderreqdata (Unifiedorderreqdatabuilder builder) {this.appid = Builder.appid; this.mch_id = builder.mch_id;
This.device_info = Builder.device_info;
This.nonce_str = Randomstringgenerator.getrandomstringbylength (32);
This.body = Builder.body;
This.detail = Builder.detail;
This.attach = Builder.attach;
This.out_trade_no = Builder.out_trade_no;
This.fee_type = Builder.fee_type;
This.total_fee = Builder.total_fee;
This.spbill_create_ip = builder.spbill_create_ip;
This.time_start = Builder.time_start;
This.time_expire = Builder.time_expire;
This.goods_tag = Builder.goods_tag;
This.notify_url = Builder.notify_url;
This.trade_type = Builder.trade_type;
this.product_id = builder.product_id;
This.limit_pay = Builder.limit_pay;
This.openid = Builder.openid;
This.sign = Signature.getsign (Tomap ());
} public void Setappid (String appid) {this.appid = AppID;
} public void setmch_id (String mch_id) {this.mch_id = mch_id;
} public void Setdevice_info (String device_info) {this.device_info = Device_info; } public void Setnonce_str (String nonce_str) {this.nonce_str = Nonce_STR;
} public void Setsign (String sign) {this.sign = sign;
public void Setbody (String body) {this.body = body;
} public void Setdetail (String detail) {this.detail = detail;
} public void Setattach (String attach) {This.attach = attach;
} public void Setout_trade_no (String out_trade_no) {this.out_trade_no = Out_trade_no;
} public void Setfee_type (String fee_type) {this.fee_type = Fee_type;
The public void Settotal_fee (int total_fee) {this.total_fee = Total_fee;
} public void Setspbill_create_ip (String spbill_create_ip) {this.spbill_create_ip = spbill_create_ip;
} public void Settime_start (String time_start) {this.time_start = Time_start;
} public void Settime_expire (String time_expire) {this.time_expire = Time_expire;
} public void Setgoods_tag (String goods_tag) {this.goods_tag = Goods_tag;
} public void Setnotify_url (String notify_url) {this.notify_url = Notify_url; } public void Settrade_type (String trade_type) {This.traDe_type = Trade_type;
} public void setproduct_id (String product_id) {this.product_id = product_id;
} public void Setlimit_pay (String limit_pay) {this.limit_pay = Limit_pay;
public void Setopenid (String OpenID) {This.openid = OpenID;
Public map<string, Object> Tomap () {map<string, object> Map = new hashmap<string, object> ();
field[] fields = This.getclass (). Getdeclaredfields ();
for (Field field:fields) {Object obj;
try {obj = Field.get (this);
if (obj!= null) {Map.put (Field.getname (), obj);
} catch (IllegalArgumentException e) {e.printstacktrace ();
catch (Illegalaccessexception e) {e.printstacktrace ();
} return map;
public static class Unifiedorderreqdatabuilder {private String AppID;
Private String mch_id;
Private String Device_info;
Private String body;
Private String detail;
Private String attach;
Private String out_trade_no;
Private String Fee_type;
private int total_fee; Private StriNg Spbill_create_ip;
Private String Time_start;
Private String Time_expire;
Private String Goods_tag;
Private String Notify_url;
Private String Trade_type;
Private String product_id;
Private String Limit_pay;
Private String OpenID;
Public Unifiedorderreqdatabuilder (String AppID, String mch_id, String body, String out_trade_no, Integer Total_fee, String spbill_create_ip, String Notify_url, String trade_type) {if (AppID = = null) {throw new Illegalargumentexcepti
On ("Incoming parameter AppID cannot be null");
} if (mch_id = = null) {throw new IllegalArgumentException ("Incoming parameter mch_id cannot be null");
} if (BODY = = null) {throw new IllegalArgumentException ("Incoming parameter body cannot be null");
} if (out_trade_no = = null) {throw new IllegalArgumentException ("Incoming parameter out_trade_no cannot be null");
} if (Total_fee = = null) {throw new IllegalArgumentException ("Incoming parameter total_fee cannot be null");
} if (spbill_create_ip = = null) {throw new IllegalArgumentException ("Incoming parameter spbill_create_ip cannot be null"); } if (Notify_url= = null) {throw new IllegalArgumentException ("Incoming parameter notify_url cannot be null");
} if (Trade_type = = null) {throw new IllegalArgumentException ("Incoming parameter trade_type cannot be null");
} this.appid = AppID;
this.mch_id = mch_id;
This.body = body;
This.out_trade_no = Out_trade_no;
This.total_fee = Total_fee;
This.spbill_create_ip = spbill_create_ip;
This.notify_url = Notify_url;
This.trade_type = Trade_type;
Public Unifiedorderreqdatabuilder Setdevice_info (String device_info) {this.device_info = Device_info;
return this;
Public Unifiedorderreqdatabuilder Setdetail (String detail) {this.detail = detail;
return this;
Public Unifiedorderreqdatabuilder Setattach (String attach) {This.attach = attach;
return this;
Public Unifiedorderreqdatabuilder Setfee_type (String fee_type) {this.fee_type = Fee_type;
return this;
Public Unifiedorderreqdatabuilder Settime_start (String time_start) {this.time_start = Time_start;
return this; } public UnifieDorderreqdatabuilder Settime_expire (String time_expire) {this.time_expire = Time_expire;
return this;
Public Unifiedorderreqdatabuilder Setgoods_tag (String goods_tag) {this.goods_tag = Goods_tag;
return this;
Public Unifiedorderreqdatabuilder setproduct_id (String product_id) {this.product_id = product_id;
return this;
Public Unifiedorderreqdatabuilder Setlimit_pay (String limit_pay) {this.limit_pay = Limit_pay;
return this;
Public Unifiedorderreqdatabuilder Setopenid (String OpenID) {This.openid = OpenID;
return this; Public Unifiedorderreqdata Build () {if ("Jsapi". Equals (this.trade_type) && This.openid = = null) {throw
New IllegalArgumentException ("When the incoming Trade_type is Jsapi, OpenID is a required parameter"); } if ("NATIVE". Equals (this.trade_type) && this.product_id = null) {throw new IllegalArgumentException ("when incoming TRA
When the De_type is native, the product_id is the required parameter ");
Return to New Unifiedorderreqdata (this);
}
}
}
Because some parameters are required, some are optional. And sign have to wait for all parameters to be passed in before they can be computed, so the builder mode is used here. About builder mode.
We use httpclient for network transmission.
Package Com.unstoppedable.common;
Import Com.thoughtworks.xstream.XStream;
Import Com.thoughtworks.xstream.io.xml.DomDriver;
Import Com.thoughtworks.xstream.io.xml.XmlFriendlyNameCoder;
Import Org.apache.commons.logging.Log;
Import Org.apache.commons.logging.LogFactory;
Import org.apache.http.HttpEntity;
Import Org.apache.http.HttpResponse;
Import org.apache.http.client.ClientProtocolException;
Import Org.apache.http.client.ResponseHandler;
Import Org.apache.http.client.config.RequestConfig;
Import Org.apache.http.client.methods.HttpGet;
Import Org.apache.http.client.methods.HttpPost;
Import org.apache.http.conn.ConnectTimeoutException;
Import org.apache.http.conn.ConnectionPoolTimeoutException;
Import Org.apache.http.conn.ssl.SSLConnectionSocketFactory;
Import org.apache.http.conn.ssl.SSLContexts;
Import org.apache.http.entity.StringEntity;
Import org.apache.http.impl.client.CloseableHttpClient;
Import org.apache.http.impl.client.HttpClients; Import Org.apache.http.util.EntityUtils;
Import Javax.net.ssl.SSLContext;
Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.IOException;
Import java.net.SocketTimeoutException;
Import Java.security.KeyStore;
/** * Created by Hupeng on 2015/7/28.
* * Public class Httpservice {private static Log logger = Logfactory.getlog (Httpservice.class);
private static Closeablehttpclient httpclient = Buildhttpclient ();
Connection Timeout, default 10 seconds private static int sockettimeout = 5000;
Transmission timeout, default 30 seconds private static int connecttimeout = 5000;
private static int requesttimeout = 5000;
public static Closeablehttpclient Buildhttpclient () {try {KeyStore KeyStore = keystore.getinstance ("PKCS12"); FileInputStream instream = new FileInputStream (New File (Configure.getcertlocalpath ());//load local certificate for HTTPS encrypted transport try {KeyS
Tore.load (Instream, Configure.getcertpassword (). ToCharArray ());//Set Certificate password} finally {instream.close (); }//Trust own CA and all self-signed certs sslcontext Sslcontext = Sslcontexts.custom (). Loadkeymaterial (KeyStore, Configure.getcertpassword (). ToCharArray ()). build (); Allow TLSV1 protocol only sslconnectionsocketfactory SSLSF = new Sslconnectionsocketfactory (Sslcontext, New St
ring[]{"TLSv1"}, NULL, sslconnectionsocketfactory.browser_compatible_hostname_verifier); Requestconfig requestconfig = Requestconfig.custom (). Setconnecttimeout (connecttimeout). SetConnectionRequestTimeou
T (requesttimeout). SetSocketTimeout (Sockettimeout). build ();
HttpClient = Httpclients.custom (). Setdefaultrequestconfig (Requestconfig). Setsslsocketfactory (SSLSF). build ();
return httpclient;
The catch (Exception e) {throw new RuntimeException ("Error Create HttpClient ...", e);
} public static string Doget (String requesturl) throws Exception {HttpGet httpget = new HttpGet (Requesturl);
try {logger.debug ("executing request" + httpget.getrequestline ()); Create A custom response handler responsehandler<string> ResponSehandler = new Responsehandler<string> () {@Override public String handleresponse (final HttpResponse Respo
NSE) throws Clientprotocolexception, IOException {int status = Response.getstatusline (). Getstatuscode ();
if (Status >= && status <) {Httpentity entity = response.getentity (); Return entity!= null?
Entityutils.tostring (entity): null;
else {throw new clientprotocolexception ("Unexpected response status:" + status);
}
}
};
Return Httpclient.execute (HttpGet, ResponseHandler);
finally {httpget.releaseconnection ();
} public static string DoPost (string url, Object object2xml) {string result = NULL;
HttpPost HttpPost = new HttpPost (URL); Resolves XStream bug xstream xstreamforrequestpostdata = new XStream (New Domdriver ("UTF-8", New Xmlfriendlynamecoder
("-_", "_")));
The data object to be submitted to the API is converted into XML format data post to the API String Postdataxml = Xstreamforrequestpostdata.toxml (object2xml); Logger.info ("Api,post the past numberIt is: ");
Logger.info (Postdataxml);
It is indicated that the use of UTF-8 encoding, otherwise to the API server XML in Chinese can not be successfully identified stringentity postentity = new Stringentity (postdataxml, "UTF-8");
Httppost.addheader ("Content-type", "Text/xml");
Httppost.setentity (postentity);
Set the configuration of the requestor Logger.info ("executing request" + httppost.getrequestline ());
try {httpresponse response = Httpclient.execute (HttpPost);
httpentity entity = response.getentity ();
result = entityutils.tostring (entity, "UTF-8"); catch (Connectionpooltimeoutexception e) {logger.error ("http Get throw connectionpooltimeoutexception")
, e);
catch (Connecttimeoutexception e) {logger.error ("http Get throw connecttimeoutexception", e);
catch (Sockettimeoutexception e) {logger.error ("http Get throw sockettimeoutexception", e);
catch (Exception e) {logger.error ("http Get throw Exception", e);
finally {httppost.abort ();
return result;
}
}
Then our total entry:
Package com.unstoppedable.service;
Import Com.unstoppedable.common.Configure;
Import Com.unstoppedable.common.HttpService;
Import Com.unstoppedable.common.XMLParser;
Import Com.unstoppedable.protocol.UnifiedOrderReqData;
Import org.xml.sax.SAXException;
Import javax.xml.parsers.ParserConfigurationException;
Import java.io.IOException;
Import Java.util.Map;
/** * Created by Hupeng on 2015/7/28. */public class Wxpayapi {public static map<string,object> Unifiedorder (Unifiedorderreqdata reqdata) throws Ioexc Eption, Saxexception, parserconfigurationexception {String res = Httpservice.dopost (Configure.unified_order_api,
Reqdata);
Return Xmlparser.getmapfromxml (RES); public static void Main (string[] args) throws Exception {Unifiedorderreqdata reqdata = new Unifiedorderreqdata.unifi Edorderreqdatabuilder ("AppID", "mch_id", "Body", "out_trade_no", 1, "Spbill_create_ip", "Notify_url", "Jsapi").
Setopenid ("OpenID"). Build ();
System.out.println (Unifiedorder (reqdata));
}}
The returned XML is:
<xml>
<return_code><![ Cdata[success]]></return_code>
<return_msg><![ Cdata[ok]]></return_msg>
<appid><![ Cdata[wx2421b1c4370ec43b]]></appid>
<mch_id><![ Cdata[10000100]]></mch_id>
<nonce_str><![ Cdata[iitri8iabbblz1jc]]></nonce_str>
<sign><![ Cdata[7921e432f65eb8ed0ce9755f0e86d72f]]></sign>
<result_code><![ Cdata[success]]></result_code>
<prepay_id><![ Cdata[wx201411101639507cbf6ffd8b0779950874]]></prepay_id>
<trade_type><![ Cdata[jsapi]]></trade_type>
</xml>
Return_code and Result_code are success when they return to the prepay_id we need ... And then use him in the Jsapi.
This article has been organized into the "JavaScript micro-Credit Development Skills Summary", welcome to learn to read.
For everyone to recommend now more attention than the micro-letter Program Tutorial: "Micro-letter Small Program Development tutorial" Small series for everyone carefully organized, hope like.
The above is the entire content of this article, I hope to help you learn.