java 单机接口限流处理方案
378
2022-06-07
要使用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
因为有些参数为必填,有些参数为选填。而且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
然后是我们的总入口:
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
返回的xml为:
return_code 和result_code都为SUCCESS的时候会返回我们需要的prepay_id。。。,然后在jsapi中使用他就可以了。。
本文已被整理到了《JavaScript微信开发技巧汇总》,《Android微信开发教程汇总》,《java微信开发教程汇总》欢迎大家学习阅读。
以上就是本文的全部内容,希望对大家的学习有所帮助。
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~