To use JSAPI for WeChat payment, you must first get a Prepay_id from WeChat, and then complete the payment by calling WeChat's JSAPI. The return result of the JS API is GET_BRAND_WCPAY_REQUEST: OK only returns when the user has successfully completed the payment. Due to the complicated front -end interactive interaction, get_brand_wcpay_request: Cancel or get_brand_wcpay_request: FAIL can be handled uniformly for users to encounter errors or actively give up, without having to refine the distinction.
The example code is as follows:
Function onbridgeready () {weixinjsbridge.invoke ('getbrandwcpayRequest', {"appid": "wx2421b1c4370EC43B", // The name of the public account was passed into "Timestamp": "139" 5712654 ", // timestamp, since 1970秒数"nonceStr" : "e61463f8efa94090b1f366cccfbbb444", //随机串"package" : "u802345jgfjsdfgsdg888", "signType" : "MD5", //微信签名方式: "paySign" : "70EA570631E4BB79628FBCA90534C63FF7FADD89" //微信签名}, function (res) {if (res.err_msg == "get_brand_wcpay_request: ok") {} // Use the above method to determine the front end return, the WeChat team solemn: res.err_msg will return to OK after the user payment is successful, but it does not guarantee it. Absolutely reliable});} If (Typeof Weixinjsbridge == "Undefined") {if (docume Ridgeready, FALSE);} Else if (document.attachevent) {document.attachevent ('WeixinjsbridgeReady', onbridgeready); Document.attachevent ('Onweixinjsbridgeready', onbridgeready);
The above parameters of the parameter Package are prepaay_id
The following is about getting parameters to call JSAPI
When we call JSAPI, we must get the user's OpenID.
First define the object of a request:
package com.unstoppedable.protocol; Import com.unstoppedable.Configure; Import com.unstoppedable.httpservice; Ommon.randomStringGenerator; Import com.unstoppedable.Common.signature; Import Java.lang.reflet. FIELD; Import Java.util.hashmap; Import Java.util.Map; Public Class University Ring 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; Ivate String Time_expire; Private String Goods_tags; Private String Notify_url; Private String Trade_type; Private String Product_id; Private String L Imit_pay; Private String Openid; Private unifiedOrDerreqdata (unifiedOrDerreqDataBuilder Builder) {this.appid = builder.appid; this.mch_id = builder.mch_id; = Builder.Device_info; This.nonce_str = RandomstringGENATOR.GetrandomSlingby (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; ify_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) = 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 SetnOnOnonONONONONONCE_STR r) {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 Voice ch (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;} publ IC Void Settotal_fee (int Total_fee) {This.total_fee = Total_fee;} Public void Setspbill_Create_ip (String SPBILL_CREATE_IP) {This .spbill_create_ip = spban_create_ip;} Public void settime_start (string time_start) {this.time_start = time_start; String time_expire) {this.time_expire = time_expire;} public void setgoods_tags (string goods_tag) {this.goods_tags_tag; } PUBLIC VOID SETNOTIFY_URL (String Notify_url) {this.notify_url = notify_url;} Public void Settrade_Type (String Trade_type) {This.tr Ade_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> Tom> AP () {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 (illegalargumentedException E) {e.printstacktrace ();} Catch (illegalaccessException E) { ACE ();}} 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 Tring out_TRADE_NO; Private String Fee_type; Private Int Total_fee; Private String SPBILL_CREATE_IP; Private String Time_start; xpire; Private String Goods_tag; Private String Notify_url; Private String Trade_type; Private String Product_id; Private String Limit_pay; ; TIFY_URL, String Trade_type) {if (Appid == NULL) {Throw New iLlegalargumentexception ("Passing parameter Appid cannot be null");} if (mch_id == null) {Throw NewALARGUMENTEXCEPTION ("" Numbers of mch_id cannot be null ");} if (Body == NULL) {Throw New iLlegalargumentedException ("" Pass parameter body cannot be null ");} if (out_trade_no == NULL) {Throw NewALARGUMENTEXCEPTION Numbers out_trade_no cannot be null ");} if (Total_fee == NULL) {Throw New iLleGALARGUMENTEXCEPTION ("Total_fee cannot be null");} if (spban_create_ip == NULL) {Throw NewALARGUMENTEXCEPTION (" The number of parameters SPBILL_CREATE_IP cannot be null ");} if (notify_url == null) {Throw New illegalargumentedException ("Pass parameter notify_url cannot be null");} if (trade_type == null) de_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 = topal_fee; ATE_IP; this.Notify_url = notify_url; this.trade_type = trade_type;} Public UnifyReqdataBuilder SetDevice_info ) {{ This.device_info = Device_info; Return This;} Public UnifyReqdataBuilder SetDetail (String Detail) {This.detail = Detail; Retail is;} Public UnifiedOrderreqdatabuilder Setattach (String Attach) {this.attach = Attach; Return This; e_type ( String Fee_type) {this.fee_type = Fee_type; Return this;} public unifyReqdataBuilder settime_start (string time_start) {this.time_start = Time_start; Return This;} Public UniFiedREQDataBuilder Settime_expire (String time_expire) {this.time_expire = time_expire; s;} Public UnifiedOrderreqdatabuilder Setgoods_tags_tags (String Goods_tag) {this.Goods_tags_tags_tag; Return This;} Public Lder Setproduct_id (String Product_id) {This.product_id = Product_id; Return This;} Public UnifiederReqdataBuilder limit_pay) {this.limit_pay = limit_pay; Return This;} Public UnifiedREQDATABUILEDER STRING Openid (String Openid) {this.openid = OpenID; Return This;} Public UnifiederReqdata () {if ("jsapi" .equals (this.trade_type) &&TYPE &&OPENID == NULL) {Throw New iLlegalagumentexception ("When trade_type is JSAPI, openid is a must -fill parameter");} if ("native" .equals (this.trade_type) &&PRODUCT_ID == NULL) Throw New iLlegalagumentexception ("" When trade_type is native, product_id is a must -fill parameter ");} Return New UnifiedOrDerreqdata (this);}}}}
Because some parameters are required, some parameters are selected. And SIGN has to wait for all the parameters to pass in before calculating, so the BUILDER mode is used here. About Builder mode.
We choose HTTPClient for network transmission.
package com.unstoppedable.com; Import com.thoughtworks.xstream.xstream; Import com.thoughtworks.xstream.io.domdriver; Import com.thoughtWorks.x stream.io.xml.xmlfriendlynameCoder; Import org.apache.Commons. Logging .Log; Import org.apache.commons. Logging.logfactory; Import org.apache.http.httpetity; Import org.apache.httpresponse; he.http.client.clientProtocolexception; Import org.apache.http. Client.Responsehandler; Import org.apache.http.client.config.requestConfig; Import org.apache.http.client.Methods.httpget; Import http.client.methods.httppost; Import org.apache.http. conn.connectTimeoutexception; Import org.apache.http.conn.connectionPoolTimeoutexception; Import KetFactory; Import org.apache.http.conn.ssl.sslContexts; Import org.apache.http.entity. Stringentity; Import org.APache.http.impl.client.closehttpClient; Import org.apache.http.client.httpClients; ttp.util.entitytils; 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 Logger = LogFactory.getLog (httpservice.class); Private Static CloseablehttpClient = BUILDHTTPCL IENT (); // Connect timeout time, default 10 seconds Private Static int Sockettimeout = 5000; // Transmission timeout, default 30 Second Private Static int ConnectTimeout = 5000; Private Static int Requesttimeout = 5000; Public Static CloseHtttpClient () {Try {try {try {try YSTORE KeyStore = KeyStore.getInstance ("PKCS12"); FileInputStream Instream = New FileInputStream (New File (Configure.getcertLocalPath () ); // Load the local certificate for https encryption transmission. Trust OWN CA and All Self-Signed Certs SSLCONTEXT SSLCONTEXT = SSLCONTEXTS.CUSTOM () .loadKeymaterial (KEYSTORE, Configure.getcertpassword (). ToCharRay (). ild (); // Allow Tlsv1 Protocol only sslConnectionSocketFactory SSLSF = New SSLCONNECTIONSOTFACTORY (SSLContext, New String [] {"TLSV1"}, NULL, SSLCONNECTIONSOTFACTFACTORY.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); RequestConfig RequestConfig = ) .setConnectTimeout (connecttimeout) .setConnectionRequestTimeout (requesttimeout) .setsockettimeout (sockettimeout). = HttpClients.CUSTOM () .setDefaultRequestConfig (requestConfig) .setsslSocketFactory (sslsf) .build (); Return httpClient;} {Throw New Runtimee xception ("ERROR CREATE HTTPCLIENT ...", E);}} Public Static String Doget (String Requesturl) Throws Exception {httpget httpget = new httpget (requesturl); TRY {logger.debug ("Executing request". getRequestline ()); // Create a Custom Response handler responsehandler <string> Responsehandler = New Responsehandler <string> () {@Override Public String HandlerSponse (FINAL HTTPRESPONSE Response) Throws Clientprilexception, IOEXCEPTION {int = response.getstatusline (). GetstatusCode (); if (status> = 200 && Status <300) {httpetity entity = response.getitity (); Return Entity! = Null? EntityUtils.tostring (Entity): null;} Else {Throw New ClientProtocolexception ("UNEXPECTED sponse status: " + status);}}}; Return httpclient.execute (httpget, responsehandler );} Finally {httpget.releaseconnection ();}} Public Stric String Vopost (String URL, Object Object2xml) {String Result = NULL; OST = New Httppost (URL); // Solve the XSTREAM pair of Bug XSTREAM XSTREAMFORREQUESTPOSTDATA = New XSTREAM (New DomDriver ("UTF-8", New XMLFRIENDLYNAMECODER ("-_", "_"); // The data object to be submitted to the API is converted to XML format data to API postdataxml = xstreamForRequestpostData .toxml (Object2xml); logger.info ("API, Post's past data was:"); logger.info (postdataxml); // You must indicate the UTF-8 encoding, otherwise the Chinese of the API server XML cannot be successfully identified. Stringentity publicity = New Stringentity (postdataxml, "UTF-8"); httppost.addheader ("content-type", "text/xml"); ) ;/ Set the configuration logger.info of the request device ( "Executing Request" + httppost.getRequestline ()); Try {httpresponse response = httpClient.execute (httppost); httpetity entity = it (); result = EntityUtils.tostring (Entity, "UTF-8");} Catch (ConnectionPoolTimeoutexception E) {Logger.error ("HTTP GET Throw ConnectionPoolTimeoutexception (WAIT TIME OUT)", E);} CATCH event e) {logger.error ("http get throwing thnectTimeoutexception", e);} Catch ) {Logger.error ("" HTTP Get Throw Sockettimeoutexception ", E);} Catch (Exception E) {logger.error (" http get Throw), e);} Finally {httppp ost.abort ();} Return Result; }}
Then there is our general entrance:
package com.unstoppedable.service; Import Com.unstoppedable.Configure; Import com.unstoppedable.common.httpService; Import on.xmlparser; Import com.unstoppedable.protocol.unifiedorderreqdata; Import org.xml.sax. Saxexception; Import Javax.xml.parserConfigurationException; Import Java.io.ioException; Import Java.util.map;/*** Created by Hupeng on 201 5/7/28. */Public Class WXPAYAPI {Public Static Map <string Object> UnifiedOrder (UnifiedOrderreqdata ReqData) Throws IOEXCEPTION, SAXEXCEPTION, PARSERCONFIGUTEXCEPTION {String Res) Onfigure.Unified_order_api, ReqData); Return XMLPARSER.GetMapfromxml (res);} Public Static void Main (String [] args) Throws Exception {UnifiedOrderreqdata Reqdata = new unifiedOrDerreqdata.UnifyReqdataBuilder ("appid", "mch_id", "out_trade_no", 1, "spaby_create_ip_ip_ip ", notify_url", "jsapi"). Setopenid ("openid"). Build () ; System.out.println (unifiedOrder (ReqData));}}
The returned XML is:
<xml> <sturn_code> <! [CDATA [SUCCESS]]> </Return_Code> <Return_msg> <! [OK]> </Return_msg> <! [WX2421B1C4370EC43B]]] > </appid > <mch_id> <! [CDATA [10000100]]> </mch_id> <nonce_str> <! [cdata [IITRI8IABBBLZ1JC]]> </nonce_str> <! [7921e432F6555F0E86D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D76D7D7D7D76D7D7D7D7D7D7D76D7D7D7D76D7D7D7D76D7D7E86D7D7ED75E8E8ED0CE6 2F]]> </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 will return the Prepay_id when they are Success. Essence Essence , Then use him in JSAPI. Essence
This article has been organized to "JavaScript WeChat Development Summary", "Android WeChat Development Tutorial Summary", and "Java WeChat Development Tutorial Summary" welcome everyone to learn and read.
I recommend a WeChat Mini Program Tutorial with a higher degree of attention to everyone: The editor of "WeChat Mini Program Development Tutorial" is carefully organized for everyone. I hope I like it.
The above is all the contents of this article. I hope it will be helpful to everyone's learning.