搜尋
首頁微信小程式微信開發詳解Java透過JsApi方式實作微信支付方法

本文解釋了Java如何實現JsApi方式的微信支付,代碼內容詳細,文章思路清晰,需要的朋友可以參考下

要使用JsApi進行微信支付,首先要從微信獲得一個prepay_id,然後透過呼叫微信的jsapi完成支付,JS API的回傳結果get_brand_wcpay_request:ok僅在使用者成功完成支付時傳回。由於前端互動複雜,get_brand_wcpay_request:cancel或get_brand_wcpay_request:fail可以統一處理為使用者遇到錯誤或主動放棄,不必細化區分。
範例程式碼如下:

function onBridgeReady(){
 WeixinJSBridge.invoke(
 'getBrandWCPayRequest', {
  "appId" : "wx2421b1c4370ec43b", //公众号名称,由商户传入 
  "timeStamp":" 1395712654",  //时间戳,自1970年以来的秒数 
  "nonceStr" : "e61463f8efa94090b1f366cccfbbb444", //随机串 
  "package" : "u802345jgfjsdfgsdg888", 
  "signType" : "MD5",  //微信签名方式: 
  "paySign" : "70EA570631E4BB79628FBCA90534C63FF7FADD89" //微信签名 
 },
 function(res){ 
  if(res.err_msg == "get_brand_wcpay_request:ok" ) {} // 使用以上方式判断前端返回,微信团队郑重提示:res.err_msg将在用户支付成功后返回 ok,但并不保证它绝对可靠。 
 }
 ); 
}
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();
}

以上傳入的參數package,也就是為prepay_id

下面講的是取得參數來呼叫jsapi
我們呼叫JSAPI時,必須取得用戶的openid,(trade_type=JSAPI,openid為必填參數。)
先定義一個請求的物件

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;
 }
 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> toMap() {
 Map<string> map = new HashMap<string>();
 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 IllegalArgumentException("传入参数appid不能为null");
  }
  if (mch_id == null) {
  throw new IllegalArgumentException("传入参数mch_id不能为null");
  }
  if (body == null) {
  throw new IllegalArgumentException("传入参数body不能为null");
  }
  if (out_trade_no == null) {
  throw new IllegalArgumentException("传入参数out_trade_no不能为null");
  }
  if (total_fee == null) {
  throw new IllegalArgumentException("传入参数total_fee不能为null");
  }
  if (spbill_create_ip == null) {
  throw new IllegalArgumentException("传入参数spbill_create_ip不能为null");
  }
  if (notify_url == null) {
  throw new IllegalArgumentException("传入参数notify_url不能为null");
  }
  if (trade_type == null) {
  throw new IllegalArgumentException("传入参数trade_type不能为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("当传入trade_type为JSAPI时,openid为必填参数");
  }
  if("NATIVE".equals(this.trade_type) && this.product_id == null) {
  throw new IllegalArgumentException("当传入trade_type为NATIVE时,product_id为必填参数");
  }
  return new UnifiedOrderReqData(this);
 }
 }
}</string></string></string>

因為有些參數為必填,有些參數為選填。而且sign要等所有參數傳入之後才能計算的出,所以這裡用了builder模式。關於builder模式。

我們選用httpclient進行網路傳輸。

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();
 //连接超时时间,默认10秒
 private static int socketTimeout = 5000;
 //传输超时时间,默认30秒
 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()));//加载本地的证书进行https加密传输
  try {
  keyStore.load(instream, Configure.getCertPassword().toCharArray());//设置证书密码
  } 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<string> responseHandler = new ResponseHandler<string>() {
  @Override
  public String handleResponse(
   final HttpResponse response) throws ClientProtocolException, IOException {
   int status = response.getStatusLine().getStatusCode();
   if (status >= 200 && status <p style="text-align: left;">然後是我們的總入口:</p>
<pre class="brush:php;toolbar:false">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> 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));
 }
}</string>

回傳的xml為:

<xml>
 <return_code></return_code>
 <return_msg></return_msg>
 <appid></appid>
 <mch_id></mch_id>
 <nonce_str></nonce_str>
 <sign></sign>
 <result_code></result_code>
 <prepay_id></prepay_id>
 <trade_type></trade_type>
</xml>

return_code 和result_code都為SUCCESS的時候會回傳我們需要的prepay_id。 。 。 ,然後在jsapi中使用他就可以了。 。

以上是詳解Java透過JsApi方式實作微信支付方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
4 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。