Java implements WeChat payment through JsApi

Source: Internet
Author: User
Tags openid
This article explains how Java implements JsApi payment. the code content is detailed and the idea is clear. if you need it, you can refer to this article to explain how Java implements JsApi payment. the code content is detailed, the idea of this article is clear. For more information, see

To use JsApi for payment, you must first obtain a prepay_id and then complete the payment by calling jsapi. the js api return result get_brand_wcpay_request: OK is only returned when the user successfully completes the payment. Due to the complexity of front-end interaction, get_brand_wcpay_request: cancel or get_brand_wcpay_request: fail can be handled in a unified manner for users to encounter errors or voluntarily give up without further division.
The sample code is as follows:

Function onBridgeReady () {WeixinJSBridge. invoke ('getbrandwcpayrequest', {"appId": "wx2421b1c4370ec43b", // name of the public account, which is input by the merchant "timeStamp": "1395712654", // timeStamp, the number of seconds since January 1, 1970 "nonceStr": "success", // random string "package": "u802345jgfjsdfgsdg888", "signType": "MD5", // signature method: "paySign": "70EA570631E4BB79628FBCA90534C63FF7FADD89" // signature}, function (res) {if (res. err_msg = "get_brand_wcpay_re Quest: OK ") {} // Determine the front-end response using the above method. The team solemnly prompts that res. err_msg will return OK after the user successfully pays, but it does not guarantee its absolute reliability. });} 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 package is prepay_id.

The following describes how to obtain parameters to call jsapi.
When calling JSAPI, we must obtain the user's openid (trade_type = JSAPI, openid is a required parameter .)
First, define a request 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 policy_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_pipeline = builder. total_detail; 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;} public void settotal_detail (int total_detail) {this. total_detail = total_detail;} 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 = yy_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
 
  
ToMap () {Map
  
   
Map = new HashMap
   
    
(); 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 policy_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 policy_url, String trade_type) {if (appid = null) {throw new IllegalArgumentException ("input parameter appid cannot be null");} if (mch_id = null) {throw new IllegalArgumentException ("input parameter mch_id cannot be null");} if (body = null) {throw new IllegalArgumentException ("input parameter body cannot be null ");} if (out_trade_no = null) {throw new IllegalArgumentException ("the input parameter out_trade_no cannot be null");} if (total_limit = null) {throw new IllegalArgumentException ("total_expiration cannot be null");} if (spbill_create_ip = null) {throw new IllegalArgumentException ("spbill_create_ip cannot be null ");} if (notify_url = null) {throw new IllegalArgumentException ("the input parameter yy_url cannot be null");} if (trade_type = null) {throw new IllegalArgumentException ("the input 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_detail = total_detail; this. spbill_create_ip = spbill_create_ip; this. notify_url = yy_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 ("openid is required when trade_type is set to JSAPI");} if ("NATIVE ". equals (this. trade_type) & this. product_id = null) {throw new IllegalArgumentException ("when trade_type is set to NATIVE, product_id is a required parameter");} return new unigiedorderreqdata (this );}}}
   
  
 

Because some parameters are required and some are optional. And sign can only be calculated after all parameters are passed in, so the builder mode is used here. About the 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 value: 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 the local certificate for https encrypted transmission try {keyStore. load (instream, Configure. getCertPassword (). toCharArray (); // Set the 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 String [] {"TLSv1"}, null, SSLConnectionSocketFactory. BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); RequestConfig requestConfig = RequestConfig. custom (). setConnectTimeout (connectTimeout ). setConnectionRequestTimeout (requestTimeout ). setSocketTimeout (socketTimeout ). build (); httpClient = HttpClients. custom (). setDefaultRequestConfig (requestConfig ). setSSLSocketFactory (sslsf ). build (); return httpClient;} 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
 
  
ResponseHandler = new ResponseHandler
  
   
() {@ Override public String handleResponse (final HttpResponse response) throws ClientProtocolException, IOException {int status = response. getStatusLine (). getStatusCode (); if (status >=200 & status <300) {HttpEntity entity = response. getEntity (); return entity! = Null? EntityUtils. toString (entity): null;} else {throw new ClientProtocolException ("Unexpected response status:" + status) ;}}; return httpClient.exe cute (httpget, responseHandler );} finally {httpget. releaseConnection () ;}} public static String doPost (String url, Object object2Xml) {String result = null; HttpPost httpPost = new HttpPost (url ); // solve XStream bug XStream xStreamForRequestPostData = new XStream (new DomDriver ("UTF-8", new XmlFriendlyNameCoder ("-_","_"))); // convert the data objects to be submitted to the API into XML format. Post the data to the API String postDataXML = xStreamForRequestPostData. toXML (object2Xml); logger.info ("API, POST data in the past is:"); logger.info (postDataXML); // specify to use UTF-8 encoding, otherwise, the Chinese language to the API server XML cannot be successfully recognized StringEntity postEntity = new StringEntity (postDataXML, "UTF-8"); httpPost. addHeader ("Content-Type", "text/xml"); httpPost. setEntity (postEntity); // Set the logger.info ("executing request" + httpPost. getRequestLine (); try {HttpResponse response = httpClient.exe cute (httpPost); HttpEntity entity = response. getEntity (); result = EntityUtils. toString (entity, "UTF-8");} catch (ConnectionPoolTimeoutException e) {logger. error ("http get throw ConnectionPoolTimeoutException (wait time out)", 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 there is our total portal:

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
 
   UnifiedOrder(UnifiedOrderReqData reqData) throws IOException, 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.UnifiedOrderReqDataBuilder("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:

  
  SUCCESS
   
  OK
   wx2421b1c4370ec43b 
  10000100
   
  IITRi8Iabbblz1Jc
   
  7921E432F65EB8ED0CE9755F0E86D72F
   
  SUCCESS
   
  wx201411101639507cbf6ffd8b0779950874
   
  JSAPI
  
 

When both the return_code and result_code are SUCCESS, the prepay_id we need will be returned... and then we can use it in jsapi ..

The above is a detailed description of how Java implements the payment method through JsApi. For more information, see other related articles on php Chinese network!

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.