微信JSAPI支付
@Override
public MessageBean pay(HttpServletRequest request, WXPayVO wxPayVO) {
MessageBean result = new MessageBean();
try {
Order order = orderMapper.getByOrderCode(wxPayVO.getOrderNo());
if (order == null) {throw new BDException("订单不存在");}
if (order.getStatus()!=0) {throw new BDException("订单状态异常,请重试");}
//获取用户openid
JSONObject jsonResult = WechatUtil.getSessionKeyOrOpenId(wxPayVO.getCode());
String openid = jsonResult.getString("openid");
//订单实付金额(分)
String total_fee = order.getPayPrice().multiply(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_HALF_UP).toString();
//拼接统一下单地址参数
Map<String, String> paraMap = new HashMap<>();
//获取请求ip地址
String ip = CusAccessObjectUtil.getIpAdrress(request);
paraMap.put("appid", "你自己的appid");
paraMap.put("body", "订单编号:799798449494");
paraMap.put("mch_id", "商户id");
paraMap.put("nonce_str", WXPayUtil.generateNonceStr());
paraMap.put("openid", openid);
paraMap.put("out_trade_no", "商户订单号,就是你自己的生成的订单号");
paraMap.put("spbill_create_ip", ip);
// paraMap.put("total_fee",total_fee);
paraMap.put("total_fee","1");//测试可以用1分钱
paraMap.put("trade_type", "JSAPI");
// 此路径是微信服务器调用支付结果通知路径
paraMap.put("notify_url","你的支付成功回调接口");
String sign = WXPayUtil.generateSignature(paraMap, Constant.PATERNER_KEY);
paraMap.put("sign", sign);
String xml = WXPayUtil.mapToXml(paraMap);//将所有参数(map)转xml格式
System.out.println(xml);
// 统一下单 https://api.mch.weixin.qq.com/pay/unifiedorder
//发送post请求"统一下单接口"返回预支付id:prepay_id
String xmlStr = HttpClientUtil.sendPost("https://api.mch.weixin.qq.com/pay/unifiedorder", xml);
Map<String, String> map = WXPayUtil.xmlToMap(xmlStr);
//以下内容是返回前端页面的json数据
String prepay_id = "";//预支付id
if (xmlStr.indexOf("SUCCESS") != -1) {
prepay_id = map.get("prepay_id");
Map<String, String> payMap = new HashMap<>();
payMap.put("appId", Constant.WX_LOGIN_APPID);
payMap.put("timeStamp", WXPayUtil.getCurrentTimestamp()+"");
payMap.put("nonceStr", WXPayUtil.generateNonceStr());
payMap.put("signType", "MD5");
payMap.put("package", "prepay_id=" + prepay_id);
String paySign = WXPayUtil.generateSignature(payMap, Constant.PATERNER_KEY);
payMap.put("paySign", paySign);
result.setData(payMap);
result.setDesc(xmlStr);
}else {
result.setSuccess(false).setDesc(map.get("return_msg"));
}
} catch (Exception e) {
logger.error(ErrorInfoUtil.getErrorInfo(e));
throw ExceptionFormatUtil.formatException(e, ErrorEnum.SYSTEM_ERROR);
}
return result;
}
回调接口
@Override
@Transactional(readOnly = false,rollbackFor = Exception.class)
public void callback(HttpServletRequest request, HttpServletResponse response) {
logger.info("微信支付成功,微信发送的callback信息,请注意修改订单信息");
InputStream is = null;
try {
//获取请求的流信息(这里是微信发的xml格式所有只能使用流来读)
is = request.getInputStream();
String xml = WXPayUtil.inputStream2String(is, "UTF-8");
//将微信发的xml转map
Map<String, String> notifyMap = WXPayUtil.xmlToMap(xml);
if(notifyMap.get("return_code").equals("SUCCESS") && notifyMap.get("result_code").equals("SUCCESS")) {
//商户订单号
String ordersSn = notifyMap.get("out_trade_no");
//实际支付的订单金额:单位 分
String amountpaid = notifyMap.get("total_fee");
//将分转换成元-实际支付金额:元
BigDecimal amountPay = (new BigDecimal(amountpaid).divide(new BigDecimal("100"))).setScale(2);
//String openid = notifyMap.get("openid"); //如果有需要可以获取
//String trade_type = notifyMap.get("trade_type");
//修改订单状态
Order order = orderMapper.getByOrderCode(ordersSn);
if (order.getStatus().equals(ConstantNumber.INTEGER_ZERO)) {
order.setPayType(ConstantNumber.INTEGER_ONE);
order.setStatus(ConstantNumber.INTEGER_ONE);
order.setPayTime(new Date());
orderMapper.update(order);
// //支付成功发送通知短信
// Map<String,String> paramMap = new HashMap<>();
// SmsUtil.sendSms(baseuser.getMobile(),Constant.SIGN_NAME,"SMS_215336433",paramMap);
List<OrderCommodity> orderCommodities = orderCommodityMapper.getByOrderId(order.getId());
if (order.getOrderType()==0) {
//修改商品销量
for (OrderCommodity orderCommodity : orderCommodities) {
Commodity commodity = commodityMapper.getOne(orderCommodity.getCommodityId());
commodity.setSales(commodity.getSales() + orderCommodity.getNum());
commodityMapper.updateSales(commodity);
}
}else {
//修改商品销量
for (OrderCommodity orderCommodity : orderCommodities) {
SeckillCommodityDO commodity = seckillCommodityMapper.getOne(orderCommodity.getCommodityId());
commodity.setSales(commodity.getSales() + orderCommodity.getNum());
seckillCommodityMapper.updateSales(commodity);
}
}
//修改订单中红包和优惠券为已使用
if (order.getCouponId() != null) {
couponReceiveMapper.updateStatus(order.getCouponId(), ConstantNumber.INTEGER_ONE);
}
if (order.getRedEnvelopesId() != null) {
redEnvelopesMapper.updateStatus(order.getRedEnvelopesId(), ConstantNumber.INTEGER_ONE);
}
}
}
//告诉微信服务器收到信息了,不要在调用回调action了========这里很重要回复微信服务器信息用流发送一个xml即可
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("<xml>");
stringBuilder.append("<return_code><![CDATA[SUCCESS]]></return_code>");
stringBuilder.append("<return_msg><![CDATA[OK]]></return_msg>");
stringBuilder.append("</xml>");
// response.getWriter().write("<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>");
response.getWriter().write(stringBuilder.toString());
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
用到的几个weixin工具类
IWXPayDomain
package com.guangyi.project.utils.WXPayUtil;
/**
* 域名管理,实现主备域名自动切换
*/
public abstract interface IWXPayDomain {
/**
* 上报域名网络状况
* @param domain 域名。 比如:api.mch.weixin.qq.com
* @param elapsedTimeMillis 耗时
* @param ex 网络请求中出现的异常。
* null表示没有异常
* ConnectTimeoutException,表示建立网络连接异常
* UnknownHostException, 表示dns解析异常
*/
abstract void report(final String domain, long elapsedTimeMillis, final Exception ex);
/**
* 获取域名
* @param config 配置
* @return 域名
*/
abstract DomainInfo getDomain(final WXPayConfig config);
static class DomainInfo{
public String domain; //域名
public boolean primaryDomain; //该域名是否为主域名。例如:api.mch.weixin.qq.com为主域名
public DomainInfo(String domain, boolean primaryDomain) {
this.domain = domain;
this.primaryDomain = primaryDomain;
}
@Override
public String toString() {
return "DomainInfo{" +
"domain='" + domain + '\'' +
", primaryDomain=" + primaryDomain +
'}';
}
}
}
WXPay
package com.guangyi.project.utils.WXPayUtil;
import java.util.HashMap;
import java.util.Map;
public class WXPay {
private WXPayConfig config;
private WXPayConstants.SignType signType;
private boolean autoReport;
private boolean useSandbox;
private String notifyUrl;
private WXPayRequest wxPayRequest;
public WXPay(final WXPayConfig config) throws Exception {
this(config, null, true, false);
}
public WXPay(final WXPayConfig config, final boolean autoReport) throws Exception {
this(config, null, autoReport, false);
}
public WXPay(final WXPayConfig config, final boolean autoReport, final boolean useSandbox) throws Exception{
this(config, null, autoReport, useSandbox);
}
public WXPay(final WXPayConfig config, final String notifyUrl) throws Exception {
this(config, notifyUrl, true, false);
}
public WXPay(final WXPayConfig config, final String notifyUrl, final boolean autoReport) throws Exception {
this(config, notifyUrl, autoReport, false);
}
public WXPay(final WXPayConfig config, final String notifyUrl, final boolean autoReport, final boolean useSandbox) throws Exception {
this.config = config;
this.notifyUrl = notifyUrl;
this.autoReport = autoReport;
this.useSandbox = useSandbox;
if (useSandbox) {
this.signType = WXPayConstants.SignType.MD5; // 沙箱环境
}
else {
this.signType = WXPayConstants.SignType.HMACSHA256;
}
this.wxPayRequest = new WXPayRequest(config);
}
private void checkWXPayConfig() throws Exception {
if (this.config == null) {
throw new Exception("config is null");
}
if (this.config.getAppID() == null || this.config.getAppID().trim().length() == 0) {
throw new Exception("appid in config is empty");
}
if (this.config.getMchID() == null || this.config.getMchID().trim().length() == 0) {
throw new Exception("appid in config is empty");
}
if (this.config.getCertStream() == null) {
throw new Exception("cert stream in config is empty");
}
if (this.config.getWXPayDomain() == null){
throw new Exception("config.getWXPayDomain() is null");
}
if (this.config.getHttpConnectTimeoutMs() < 10) {
throw new Exception("http connect timeout is too small");
}
if (this.config.getHttpReadTimeoutMs() < 10) {
throw new Exception("http read timeout is too small");
}
}
/**
* 向 Map 中添加 appid、mch_id、nonce_str、sign_type、sign <br>
* 该函数适用于商户适用于统一下单等接口,不适用于红包、代金券接口
*
* @param reqData
* @return
* @throws Exception
*/
public Map<String, String> fillRequestData(Map<String, String> reqData) throws Exception {
reqData.put("appid", config.getAppID());
reqData.put("mch_id", config.getMchID());
reqData.put("nonce_str", WXPayUtil.generateNonceStr());
if (WXPayConstants.SignType.MD5.equals(this.signType)) {
reqData.put("sign_type", WXPayConstants.MD5);
}
else if (WXPayConstants.SignType.HMACSHA256.equals(this.signType)) {
reqData.put("sign_type", WXPayConstants.HMACSHA256);
}
reqData.put("sign", WXPayUtil.generateSignature(reqData, config.getKey(), this.signType));
return reqData;
}
/**
* 判断xml数据的sign是否有效,必须包含sign字段,否则返回false。
*
* @param reqData 向wxpay post的请求数据
* @return 签名是否有效
* @throws Exception
*/
public boolean isResponseSignatureValid(Map<String, String> reqData) throws Exception {
// 返回数据的签名方式和请求中给定的签名方式是一致的
return WXPayUtil.isSignatureValid(reqData, this.config.getKey(), this.signType);
}
/**
* 判断支付结果通知中的sign是否有效
*
* @param reqData 向wxpay post的请求数据
* @return 签名是否有效
* @throws Exception
*/
public boolean isPayResultNotifySignatureValid(Map<String, String> reqData) throws Exception {
String signTypeInData = reqData.get(WXPayConstants.FIELD_SIGN_TYPE);
WXPayConstants.SignType signType;
if (signTypeInData == null) {
signType = WXPayConstants.SignType.MD5;
}
else {
signTypeInData = signTypeInData.trim();
if (signTypeInData.length() == 0) {
signType = WXPayConstants.SignType.MD5;
}
else if (WXPayConstants.MD5.equals(signTypeInData)) {
signType = WXPayConstants.SignType.MD5;
}
else if (WXPayConstants.HMACSHA256.equals(signTypeInData)) {
signType = WXPayConstants.SignType.HMACSHA256;
}
else {
throw new Exception(String.format("Unsupported sign_type: %s", signTypeInData));
}
}
return WXPayUtil.isSignatureValid(reqData, this.config.getKey(), signType);
}
/**
* 不需要证书的请求
* @param urlSuffix String
* @param reqData 向wxpay post的请求数据
* @param connectTimeoutMs 超时时间,单位是毫秒
* @param readTimeoutMs 超时时间,单位是毫秒
* @return API返回数据
* @throws Exception
*/
public String requestWithoutCert(String urlSuffix, Map<String, String> reqData,
int connectTimeoutMs, int readTimeoutMs) throws Exception {
String msgUUID = reqData.get("nonce_str");
String reqBody = WXPayUtil.mapToXml(reqData);
String resp = this.wxPayRequest.requestWithoutCert(urlSuffix, msgUUID, reqBody, connectTimeoutMs, readTimeoutMs, autoReport);
return resp;
}
/**
* 需要证书的请求
* @param urlSuffix String
* @param reqData 向wxpay post的请求数据 Map
* @param connectTimeoutMs 超时时间,单位是毫秒
* @param readTimeoutMs 超时时间,单位是毫秒
* @return API返回数据
* @throws Exception
*/
public String requestWithCert(String urlSuffix, Map<String, String> reqData,
int connectTimeoutMs, int readTimeoutMs) throws Exception {
String msgUUID= reqData.get("nonce_str");
String reqBody = WXPayUtil.mapToXml(reqData);
String resp = this.wxPayRequest.requestWithCert(urlSuffix, msgUUID, reqBody, connectTimeoutMs, readTimeoutMs, this.autoReport);
return resp;
}
/**
* 处理 HTTPS API返回数据,转换成Map对象。return_code为SUCCESS时,验证签名。
* @param xmlStr API返回的XML格式数据
* @return Map类型数据
* @throws Exception
*/
public Map<String, String> processResponseXml(String xmlStr) throws Exception {
String RETURN_CODE = "return_code";
String return_code;
Map<String, String> respData = WXPayUtil.xmlToMap(xmlStr);
if (respData.containsKey(RETURN_CODE)) {
return_code = respData.get(RETURN_CODE);
}
else {
throw new Exception(String.format("No `return_code` in XML: %s", xmlStr));
}
if (return_code.equals(WXPayConstants.FAIL)) {
return respData;
}
else if (return_code.equals(WXPayConstants.SUCCESS)) {
if (this.isResponseSignatureValid(respData)) {
return respData;
}
else {
throw new Exception(String.format("Invalid sign value in XML: %s", xmlStr));
}
}
else {
throw new Exception(String.format("return_code value %s is invalid in XML: %s", return_code, xmlStr));
}
}
/**
* 作用:提交刷卡支付<br>
* 场景:刷卡支付
* @param reqData 向wxpay post的请求数据
* @return API返回数据
* @throws Exception
*/
public Map<String, String> microPay(Map<String, String> reqData) throws Exception {
return this.microPay(reqData, this.config.getHttpConnectTimeoutMs(), this.config.getHttpReadTimeoutMs());
}
/**
* 作用:提交刷卡支付<br>
* 场景:刷卡支付
* @param reqData 向wxpay post的请求数据
* @param connectTimeoutMs 连接超时时间,单位是毫秒
* @param readTimeoutMs 读超时时间,单位是毫秒
* @return API返回数据
* @throws Exception
*/
public Map<String, String> microPay(Map<String, String> reqData, int connectTimeoutMs, int readTimeoutMs) throws Exception {
String url;
if (this.useSandbox) {
url = WXPayConstants.SANDBOX_MICROPAY_URL_SUFFIX;
}
else {
url = WXPayConstants.MICROPAY_URL_SUFFIX;
}
String respXml = this.requestWithoutCert(url, this.fillRequestData(reqData), connectTimeoutMs, readTimeoutMs);
return this.processResponseXml(respXml);
}
/**
* 提交刷卡支付,针对软POS,尽可能做成功
* 内置重试机制,最多60s
* @param reqData
* @return
* @throws Exception
*/
public Map<String, String> microPayWithPos(Map<String, String> reqData) throws Exception {
return this.microPayWithPos(reqData, this.config.getHttpConnectTimeoutMs());
}
/**
* 提交刷卡支付,针对软POS,尽可能做成功
* 内置重试机制,最多60s
* @param reqData
* @param connectTimeoutMs
* @return
* @throws Exception
*/
public Map<String, String> microPayWithPos(Map<String, String> reqData, int connectTimeoutMs) throws Exception {
int remainingTimeMs = 60*1000;
long startTimestampMs = 0;
Map<String, String> lastResult = null;
Exception lastException = null;
while (true) {
startTimestampMs = WXPayUtil.getCurrentTimestampMs();
int readTimeoutMs = remainingTimeMs - connectTimeoutMs;
if (readTimeoutMs > 1000) {
try {
lastResult = this.microPay(reqData, connectTimeoutMs, readTimeoutMs);
String returnCode = lastResult.get("return_code");
if (returnCode.equals("SUCCESS")) {
String resultCode = lastResult.get("result_code");
String errCode = lastResult.get("err_code");
if (resultCode.equals("SUCCESS")) {
break;
}
else {
// 看错误码,若支付结果未知,则重试提交刷卡支付
if (errCode.equals("SYSTEMERROR") || errCode.equals("BANKERROR") || errCode.equals("USERPAYING")) {
remainingTimeMs = remainingTimeMs - (int)(WXPayUtil.getCurrentTimestampMs() - startTimestampMs);
if (remainingTimeMs <= 100) {
break;
}
else {
WXPayUtil.getLogger().info("microPayWithPos: try micropay again");
if (remainingTimeMs > 5*1000) {
Thread.sleep(5*1000);
}
else {
Thread.sleep(1*1000);
}
continue;
}
}
else {
break;
}
}
}
else {
break;
}
}
catch (Exception ex) {
lastResult = null;
lastException = ex;
}
}
else {
break;
}
}
if (lastResult == null) {
throw lastException;
}
else {
return lastResult;
}
}
/**
* 作用:统一下单<br>
* 场景:公共号支付、扫码支付、APP支付
* @param reqData 向wxpay post的请求数据
* @return API返回数据
* @throws Exception
*/
public Map<String, String> unifiedOrder(Map<String, String> reqData) throws Exception {
return this.unifiedOrder(reqData, config.getHttpConnectTimeoutMs(), this.config.getHttpReadTimeoutMs());
}
/**
* 作用:统一下单<br>
* 场景:公共号支付、扫码支付、APP支付
* @param reqData 向wxpay post的请求数据
* @param connectTimeoutMs 连接超时时间,单位是毫秒
* @param readTimeoutMs 读超时时间,单位是毫秒
* @return API返回数据
* @throws Exception
*/
public Map<String, String> unifiedOrder(Map<String, String> reqData, int connectTimeoutMs, int readTimeoutMs) throws Exception {
String url;
if (this.useSandbox) {
url = WXPayConstants.SANDBOX_UNIFIEDORDER_URL_SUFFIX;
}
else {
url = WXPayConstants.UNIFIEDORDER_URL_SUFFIX;
}
if(this.notifyUrl != null) {
reqData.put("notify_url", this.notifyUrl);
}
String respXml = this.requestWithoutCert(url, this.fillRequestData(reqData), connectTimeoutMs, readTimeoutMs);
return this.processResponseXml(respXml);
}
/**
* 作用:查询订单<br>
* 场景:刷卡支付、公共号支付、扫码支付、APP支付
* @param reqData 向wxpay post的请求数据
* @return API返回数据
* @throws Exception
*/
public Map<String, String> orderQuery(Map<String, String> reqData) throws Exception {
return this.orderQuery(reqData, config.getHttpConnectTimeoutMs(), this.config.getHttpReadTimeoutMs());
}
/**
* 作用:查询订单<br>
* 场景:刷卡支付、公共号支付、扫码支付、APP支付
* @param reqData 向wxpay post的请求数据 int
* @param connectTimeoutMs 连接超时时间,单位是毫秒
* @param readTimeoutMs 读超时时间,单位是毫秒
* @return API返回数据
* @throws Exception
*/
public Map<String, String> orderQuery(Map<String, String> reqData, int connectTimeoutMs, int readTimeoutMs) throws Exception {
String url;
if (this.useSandbox) {
url = WXPayConstants.SANDBOX_ORDERQUERY_URL_SUFFIX;
}
else {
url = WXPayConstants.ORDERQUERY_URL_SUFFIX;
}
String respXml = this.requestWithoutCert(url, this.fillRequestData(reqData), connectTimeoutMs, readTimeoutMs);
return this.processResponseXml(respXml);
}
/**
* 作用:撤销订单<br>
* 场景:刷卡支付
* @param reqData 向wxpay post的请求数据
* @return API返回数据
* @throws Exception
*/
public Map<String, String> reverse(Map<String, String> reqData) throws Exception {
return this.reverse(reqData, config.getHttpConnectTimeoutMs(), this.config.getHttpReadTimeoutMs());
}
/**
* 作用:撤销订单<br>
* 场景:刷卡支付<br>
* 其他:需要证书
* @param reqData 向wxpay post的请求数据
* @param connectTimeoutMs 连接超时时间,单位是毫秒
* @param readTimeoutMs 读超时时间,单位是毫秒
* @return API返回数据
* @throws Exception
*/
public Map<String, String> reverse(Map<String, String> reqData, int connectTimeoutMs, int readTimeoutMs) throws Exception {
String url;
if (this.useSandbox) {
url = WXPayConstants.SANDBOX_REVERSE_URL_SUFFIX;
}
else {
url = WXPayConstants.REVERSE_URL_SUFFIX;
}
String respXml = this.requestWithCert(url, this.fillRequestData(reqData), connectTimeoutMs, readTimeoutMs);
return this.processResponseXml(respXml);
}
/**
* 作用:关闭订单<br>
* 场景:公共号支付、扫码支付、APP支付
* @param reqData 向wxpay post的请求数据
* @return API返回数据
* @throws Exception
*/
public Map<String, String> closeOrder(Map<String, String> reqData) throws Exception {
return this.closeOrder(reqData, config.getHttpConnectTimeoutMs(), this.config.getHttpReadTimeoutMs());
}
/**
* 作用:关闭订单<br>
* 场景:公共号支付、扫码支付、APP支付
* @param reqData 向wxpay post的请求数据
* @param connectTimeoutMs 连接超时时间,单位是毫秒
* @param readTimeoutMs 读超时时间,单位是毫秒
* @return API返回数据
* @throws Exception
*/
public Map<String, String> closeOrder(Map<String, String> reqData, int connectTimeoutMs, int readTimeoutMs) throws Exception {
String url;
if (this.useSandbox) {
url = WXPayConstants.SANDBOX_CLOSEORDER_URL_SUFFIX;
}
else {
url = WXPayConstants.CLOSEORDER_URL_SUFFIX;
}
String respXml = this.requestWithoutCert(url, this.fillRequestData(reqData), connectTimeoutMs, readTimeoutMs);
return this.processResponseXml(respXml);
}
/**
* 作用:申请退款<br>
* 场景:刷卡支付、公共号支付、扫码支付、APP支付
* @param reqData 向wxpay post的请求数据
* @return API返回数据
* @throws Exception
*/
public Map<String, String> refund(Map<String, String> reqData) throws Exception {
return this.refund(reqData, this.config.getHttpConnectTimeoutMs(), this.config.getHttpReadTimeoutMs());
}
/**
* 作用:申请退款<br>
* 场景:刷卡支付、公共号支付、扫码支付、APP支付<br>
* 其他:需要证书
* @param reqData 向wxpay post的请求数据
* @param connectTimeoutMs 连接超时时间,单位是毫秒
* @param readTimeoutMs 读超时时间,单位是毫秒
* @return API返回数据
* @throws Exception
*/
public Map<String, String> refund(Map<String, String> reqData, int connectTimeoutMs, int readTimeoutMs) throws Exception {
String url;
if (this.useSandbox) {
url = WXPayConstants.SANDBOX_REFUND_URL_SUFFIX;
}
else {
url = WXPayConstants.REFUND_URL_SUFFIX;
}
String respXml = this.requestWithCert(url, this.fillRequestData(reqData), connectTimeoutMs, readTimeoutMs);
return this.processResponseXml(respXml);
}
/**
* 作用:退款查询<br>
* 场景:刷卡支付、公共号支付、扫码支付、APP支付
* @param reqData 向wxpay post的请求数据
* @return API返回数据
* @throws Exception
*/
public Map<String, String> refundQuery(Map<String, String> reqData) throws Exception {
return this.refundQuery(reqData, this.config.getHttpConnectTimeoutMs(), this.config.getHttpReadTimeoutMs());
}
/**
* 作用:退款查询<br>
* 场景:刷卡支付、公共号支付、扫码支付、APP支付
* @param reqData 向wxpay post的请求数据
* @param connectTimeoutMs 连接超时时间,单位是毫秒
* @param readTimeoutMs 读超时时间,单位是毫秒
* @return API返回数据
* @throws Exception
*/
public Map<String, String> refundQuery(Map<String, String> reqData, int connectTimeoutMs, int readTimeoutMs) throws Exception {
String url;
if (this.useSandbox) {
url = WXPayConstants.SANDBOX_REFUNDQUERY_URL_SUFFIX;
}
else {
url = WXPayConstants.REFUNDQUERY_URL_SUFFIX;
}
String respXml = this.requestWithoutCert(url, this.fillRequestData(reqData), connectTimeoutMs, readTimeoutMs);
return this.processResponseXml(respXml);
}
/**
* 作用:对账单下载(成功时返回对账单数据,失败时返回XML格式数据)<br>
* 场景:刷卡支付、公共号支付、扫码支付、APP支付
* @param reqData 向wxpay post的请求数据
* @return API返回数据
* @throws Exception
*/
public Map<String, String> downloadBill(Map<String, String> reqData) throws Exception {
return this.downloadBill(reqData, this.config.getHttpConnectTimeoutMs(), this.config.getHttpReadTimeoutMs());
}
/**
* 作用:对账单下载<br>
* 场景:刷卡支付、公共号支付、扫码支付、APP支付<br>
* 其他:无论是否成功都返回Map。若成功,返回的Map中含有return_code、return_msg、data,
* 其中return_code为`SUCCESS`,data为对账单数据。
* @param reqData 向wxpay post的请求数据
* @param connectTimeoutMs 连接超时时间,单位是毫秒
* @param readTimeoutMs 读超时时间,单位是毫秒
* @return 经过封装的API返回数据
* @throws Exception
*/
public Map<String, String> downloadBill(Map<String, String> reqData, int connectTimeoutMs, int readTimeoutMs) throws Exception {
String url;
if (this.useSandbox) {
url = WXPayConstants.SANDBOX_DOWNLOADBILL_URL_SUFFIX;
}
else {
url = WXPayConstants.DOWNLOADBILL_URL_SUFFIX;
}
String respStr = this.requestWithoutCert(url, this.fillRequestData(reqData), connectTimeoutMs, readTimeoutMs).trim();
Map<String, String> ret;
// 出现错误,返回XML数据
if (respStr.indexOf("<") == 0) {
ret = WXPayUtil.xmlToMap(respStr);
}
else {
// 正常返回csv数据
ret = new HashMap<String, String>();
ret.put("return_code", WXPayConstants.SUCCESS);
ret.put("return_msg", "ok");
ret.put("data", respStr);
}
return ret;
}
/**
* 作用:交易保障<br>
* 场景:刷卡支付、公共号支付、扫码支付、APP支付
* @param reqData 向wxpay post的请求数据
* @return API返回数据
* @throws Exception
*/
public Map<String, String> report(Map<String, String> reqData) throws Exception {
return this.report(reqData, this.config.getHttpConnectTimeoutMs(), this.config.getHttpReadTimeoutMs());
}
/**
* 作用:交易保障<br>
* 场景:刷卡支付、公共号支付、扫码支付、APP支付
* @param reqData 向wxpay post的请求数据
* @param connectTimeoutMs 连接超时时间,单位是毫秒
* @param readTimeoutMs 读超时时间,单位是毫秒
* @return API返回数据
* @throws Exception
*/
public Map<String, String> report(Map<String, String> reqData, int connectTimeoutMs, int readTimeoutMs) throws Exception {
String url;
if (this.useSandbox) {
url = WXPayConstants.SANDBOX_REPORT_URL_SUFFIX;
}
else {
url = WXPayConstants.REPORT_URL_SUFFIX;
}
String respXml = this.requestWithoutCert(url, this.fillRequestData(reqData), connectTimeoutMs, readTimeoutMs);
return WXPayUtil.xmlToMap(respXml);
}
/**
* 作用:转换短链接<br>
* 场景:刷卡支付、扫码支付
* @param reqData 向wxpay post的请求数据
* @return API返回数据
* @throws Exception
*/
public Map<String, String> shortUrl(Map<String, String> reqData) throws Exception {
return this.shortUrl(reqData, this.config.getHttpConnectTimeoutMs(), this.config.getHttpReadTimeoutMs());
}
/**
* 作用:转换短链接<br>
* 场景:刷卡支付、扫码支付
* @param reqData 向wxpay post的请求数据
* @return API返回数据
* @throws Exception
*/
public Map<String, String> shortUrl(Map<String, String> reqData, int connectTimeoutMs, int readTimeoutMs) throws Exception {
String url;
if (this.useSandbox) {
url = WXPayConstants.SANDBOX_SHORTURL_URL_SUFFIX;
}
else {
url = WXPayConstants.SHORTURL_URL_SUFFIX;
}
String respXml = this.requestWithoutCert(url, this.fillRequestData(reqData), connectTimeoutMs, readTimeoutMs);
return this.processResponseXml(respXml);
}
/**
* 作用:授权码查询OPENID接口<br>
* 场景:刷卡支付
* @param reqData 向wxpay post的请求数据
* @return API返回数据
* @throws Exception
*/
public Map<String, String> authCodeToOpenid(Map<String, String> reqData) throws Exception {
return this.authCodeToOpenid(reqData, this.config.getHttpConnectTimeoutMs(), this.config.getHttpReadTimeoutMs());
}
/**
* 作用:授权码查询OPENID接口<br>
* 场景:刷卡支付
* @param reqData 向wxpay post的请求数据
* @param connectTimeoutMs 连接超时时间,单位是毫秒
* @param readTimeoutMs 读超时时间,单位是毫秒
* @return API返回数据
* @throws Exception
*/
public Map<String, String> authCodeToOpenid(Map<String, String> reqData, int connectTimeoutMs, int readTimeoutMs) throws Exception {
String url;
if (this.useSandbox) {
url = WXPayConstants.SANDBOX_AUTHCODETOOPENID_URL_SUFFIX;
}
else {
url = WXPayConstants.AUTHCODETOOPENID_URL_SUFFIX;
}
String respXml = this.requestWithoutCert(url, this.fillRequestData(reqData), connectTimeoutMs, readTimeoutMs);
return this.processResponseXml(respXml);
}
} // end class
WXPayConfig
package com.guangyi.project.utils.WXPayUtil;
import java.io.InputStream;
public abstract class WXPayConfig {
/**
* 获取 App ID
*
* @return App ID
*/
abstract String getAppID();
/**
* 获取 Mch ID
*
* @return Mch ID
*/
abstract String getMchID();
/**
* 获取 API 密钥
*
* @return API密钥
*/
abstract String getKey();
/**
* 获取商户证书内容
*
* @return 商户证书内容
*/
abstract InputStream getCertStream();
/**
* HTTP(S) 连接超时时间,单位毫秒
*
* @return
*/
public int getHttpConnectTimeoutMs() {
return 6*1000;
}
/**
* HTTP(S) 读数据超时时间,单位毫秒
*
* @return
*/
public int getHttpReadTimeoutMs() {
return 8*1000;
}
/**
* 获取WXPayDomain, 用于多域名容灾自动切换
* @return
*/
abstract IWXPayDomain getWXPayDomain();
/**
* 是否自动上报。
* 若要关闭自动上报,子类中实现该函数返回 false 即可。
*
* @return
*/
public boolean shouldAutoReport() {
return true;
}
/**
* 进行健康上报的线程的数量
*
* @return
*/
public int getReportWorkerNum() {
return 6;
}
/**
* 健康上报缓存消息的最大数量。会有线程去独立上报
* 粗略计算:加入一条消息200B,10000消息占用空间 2000 KB,约为2MB,可以接受
*
* @return
*/
public int getReportQueueMaxSize() {
return 10000;
}
/**
* 批量上报,一次最多上报多个数据
*
* @return
*/
public int getReportBatchSize() {
return 10;
}
}
WxPayConfigImpl
package com.guangyi.project.utils.WXPayUtil;
import com.guangyi.project.config.Constant;
import com.guangyi.project.utils.FileUtils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
public class WxPayConfigImpl extends WXPayConfig {
public static String url = "你设置的回调接口";
private static WxPayConfigImpl wxPayConfig;
private byte[] certData = null;
public static WxPayConfigImpl getInstance() {
if (wxPayConfig == null) {
synchronized (WxPayConfigImpl.class) {
wxPayConfig = new WxPayConfigImpl();
}
}
return wxPayConfig;
}
public WxPayConfigImpl() {
try {
//这个证书的位置不是瞎鸡儿填的,你要在这个路径真的有一个证书
InputStream is = new FileInputStream(FileUtils.getResourcesPath()+"refund_certificate/apiclient_cert.p12");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] bs = new byte[1024];
int cnt = -1;
while ((cnt = is.read(bs)) != -1) {
baos.write(bs, 0, cnt);
}
is.close();
certData = baos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public String getAppID() {
return Constant.WX_LOGIN_APPID;
}
@Override
public String getMchID() {
return Constant.MCH_ID;
}
@Override
public String getKey() {
return Constant.PATERNER_KEY;
}
@Override
public InputStream getCertStream() {
ByteArrayInputStream certBis;
certBis = new ByteArrayInputStream(this.certData);
return certBis;
}
@Override
public int getHttpConnectTimeoutMs() {
// TODO Auto-generated method stub
return 8000;
}
@Override
public int getHttpReadTimeoutMs() {
// TODO Auto-generated method stub
return 10000;
}
@Override
public IWXPayDomain getWXPayDomain() {
// 这个方法需要这样实现, 否则无法正常初始化WXPay
IWXPayDomain iwxPayDomain = new IWXPayDomain() {
@Override
public void report(String domain, long elapsedTimeMillis, Exception ex) {
}
@Override
public DomainInfo getDomain(WXPayConfig config) {
return new IWXPayDomain.DomainInfo(WXPayConstants.DOMAIN_API, true);
}
};
return iwxPayDomain;
}
public String getPrimaryDomain() {
return WXPayConstants.DOMAIN_API;
}
public String getNotifyUrl(){
return url;
}
}
WXPayConstants
package com.guangyi.project.utils.WXPayUtil;
import org.apache.http.client.HttpClient;
/**
* 常量
*/
public class WXPayConstants {
public enum SignType {
MD5, HMACSHA256
}
public static final String DOMAIN_API = "api.mch.weixin.qq.com";
public static final String DOMAIN_API2 = "api2.mch.weixin.qq.com";
public static final String DOMAIN_APIHK = "apihk.mch.weixin.qq.com";
public static final String DOMAIN_APIUS = "apius.mch.weixin.qq.com";
public static final String FAIL = "FAIL";
public static final String SUCCESS = "SUCCESS";
public static final String HMACSHA256 = "HMAC-SHA256";
public static final String MD5 = "MD5";
public static final String FIELD_SIGN = "sign";
public static final String FIELD_SIGN_TYPE = "sign_type";
public static final String WXPAYSDK_VERSION = "WXPaySDK/3.0.9";
public static final String USER_AGENT = WXPAYSDK_VERSION +
" (" + System.getProperty("os.arch") + " " + System.getProperty("os.name") + " " + System.getProperty("os.version") +
") Java/" + System.getProperty("java.version") + " HttpClient/" + HttpClient.class.getPackage().getImplementationVersion();
public static final String MICROPAY_URL_SUFFIX = "/pay/micropay";
public static final String UNIFIEDORDER_URL_SUFFIX = "/pay/unifiedorder";
public static final String ORDERQUERY_URL_SUFFIX = "/pay/orderquery";
public static final String REVERSE_URL_SUFFIX = "/secapi/pay/reverse";
public static final String CLOSEORDER_URL_SUFFIX = "/pay/closeorder";
public static final String REFUND_URL_SUFFIX = "/secapi/pay/refund";
public static final String REFUNDQUERY_URL_SUFFIX = "/pay/refundquery";
public static final String DOWNLOADBILL_URL_SUFFIX = "/pay/downloadbill";
public static final String REPORT_URL_SUFFIX = "/payitil/report";
public static final String SHORTURL_URL_SUFFIX = "/tools/shorturl";
public static final String AUTHCODETOOPENID_URL_SUFFIX = "/tools/authcodetoopenid";
// sandbox
public static final String SANDBOX_MICROPAY_URL_SUFFIX = "/sandboxnew/pay/micropay";
public static final String SANDBOX_UNIFIEDORDER_URL_SUFFIX = "/sandboxnew/pay/unifiedorder";
public static final String SANDBOX_ORDERQUERY_URL_SUFFIX = "/sandboxnew/pay/orderquery";
public static final String SANDBOX_REVERSE_URL_SUFFIX = "/sandboxnew/secapi/pay/reverse";
public static final String SANDBOX_CLOSEORDER_URL_SUFFIX = "/sandboxnew/pay/closeorder";
public static final String SANDBOX_REFUND_URL_SUFFIX = "/sandboxnew/secapi/pay/refund";
public static final String SANDBOX_REFUNDQUERY_URL_SUFFIX = "/sandboxnew/pay/refundquery";
public static final String SANDBOX_DOWNLOADBILL_URL_SUFFIX = "/sandboxnew/pay/downloadbill";
public static final String SANDBOX_REPORT_URL_SUFFIX = "/sandboxnew/payitil/report";
public static final String SANDBOX_SHORTURL_URL_SUFFIX = "/sandboxnew/tools/shorturl";
public static final String SANDBOX_AUTHCODETOOPENID_URL_SUFFIX = "/sandboxnew/tools/authcodetoopenid";
}
WXPayReport
package com.guangyi.project.utils.WXPayUtil;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
/**
* 交易保障
*/
public class WXPayReport {
public static class ReportInfo {
/**
* 布尔变量使用int。0为false, 1为true。
*/
// 基本信息
private String version = "v1";
private String sdk = WXPayConstants.WXPAYSDK_VERSION;
private String uuid; // 交易的标识
private long timestamp; // 上报时的时间戳,单位秒
private long elapsedTimeMillis; // 耗时,单位 毫秒
// 针对主域名
private String firstDomain; // 第1次请求的域名
private boolean primaryDomain; //是否主域名
private int firstConnectTimeoutMillis; // 第1次请求设置的连接超时时间,单位 毫秒
private int firstReadTimeoutMillis; // 第1次请求设置的读写超时时间,单位 毫秒
private int firstHasDnsError; // 第1次请求是否出现dns问题
private int firstHasConnectTimeout; // 第1次请求是否出现连接超时
private int firstHasReadTimeout; // 第1次请求是否出现连接超时
public ReportInfo(String uuid, long timestamp, long elapsedTimeMillis, String firstDomain, boolean primaryDomain, int firstConnectTimeoutMillis, int firstReadTimeoutMillis, boolean firstHasDnsError, boolean firstHasConnectTimeout, boolean firstHasReadTimeout) {
this.uuid = uuid;
this.timestamp = timestamp;
this.elapsedTimeMillis = elapsedTimeMillis;
this.firstDomain = firstDomain;
this.primaryDomain = primaryDomain;
this.firstConnectTimeoutMillis = firstConnectTimeoutMillis;
this.firstReadTimeoutMillis = firstReadTimeoutMillis;
this.firstHasDnsError = firstHasDnsError?1:0;
this.firstHasConnectTimeout = firstHasConnectTimeout?1:0;
this.firstHasReadTimeout = firstHasReadTimeout?1:0;
}
@Override
public String toString() {
return "ReportInfo{" +
"version='" + version + '\'' +
", sdk='" + sdk + '\'' +
", uuid='" + uuid + '\'' +
", timestamp=" + timestamp +
", elapsedTimeMillis=" + elapsedTimeMillis +
", firstDomain='" + firstDomain + '\'' +
", primaryDomain=" + primaryDomain +
", firstConnectTimeoutMillis=" + firstConnectTimeoutMillis +
", firstReadTimeoutMillis=" + firstReadTimeoutMillis +
", firstHasDnsError=" + firstHasDnsError +
", firstHasConnectTimeout=" + firstHasConnectTimeout +
", firstHasReadTimeout=" + firstHasReadTimeout +
'}';
}
/**
* 转换成 csv 格式
*
* @return
*/
public String toLineString(String key) {
String separator = ",";
Object[] objects = new Object[] {
version, sdk, uuid, timestamp, elapsedTimeMillis,
firstDomain, primaryDomain, firstConnectTimeoutMillis, firstReadTimeoutMillis,
firstHasDnsError, firstHasConnectTimeout, firstHasReadTimeout
};
StringBuffer sb = new StringBuffer();
for(Object obj: objects) {
sb.append(obj).append(separator);
}
try {
String sign = WXPayUtil.HMACSHA256(sb.toString(), key);
sb.append(sign);
return sb.toString();
}
catch (Exception ex) {
return null;
}
}
}
private static final String REPORT_URL = "http://report.mch.weixin.qq.com/wxpay/report/default";
// private static final String REPORT_URL = "http://127.0.0.1:5000/test";
private static final int DEFAULT_CONNECT_TIMEOUT_MS = 6*1000;
private static final int DEFAULT_READ_TIMEOUT_MS = 8*1000;
private LinkedBlockingQueue<String> reportMsgQueue = null;
private WXPayConfig config;
private ExecutorService executorService;
private volatile static WXPayReport INSTANCE;
private WXPayReport(final WXPayConfig config) {
this.config = config;
reportMsgQueue = new LinkedBlockingQueue<String>(config.getReportQueueMaxSize());
// 添加处理线程
executorService = Executors.newFixedThreadPool(config.getReportWorkerNum(), new ThreadFactory() {
public Thread newThread(Runnable r) {
Thread t = Executors.defaultThreadFactory().newThread(r);
t.setDaemon(true);
return t;
}
});
if (config.shouldAutoReport()) {
WXPayUtil.getLogger().info("report worker num: {}", config.getReportWorkerNum());
for (int i = 0; i < config.getReportWorkerNum(); ++i) {
executorService.execute(new Runnable() {
public void run() {
while (true) {
// 先用 take 获取数据
try {
StringBuffer sb = new StringBuffer();
String firstMsg = reportMsgQueue.take();
WXPayUtil.getLogger().info("get first report msg: {}", firstMsg);
String msg = null;
sb.append(firstMsg); //会阻塞至有消息
int remainNum = config.getReportBatchSize() - 1;
for (int j=0; j<remainNum; ++j) {
WXPayUtil.getLogger().info("try get remain report msg");
// msg = reportMsgQueue.poll(); // 不阻塞了
msg = reportMsgQueue.take();
WXPayUtil.getLogger().info("get remain report msg: {}", msg);
if (msg == null) {
break;
}
else {
sb.append("\n");
sb.append(msg);
}
}
// 上报
WXPayReport.httpRequest(sb.toString(), DEFAULT_CONNECT_TIMEOUT_MS, DEFAULT_READ_TIMEOUT_MS);
}
catch (Exception ex) {
WXPayUtil.getLogger().warn("report fail. reason: {}", ex.getMessage());
}
}
}
});
}
}
}
/**
* 单例,双重校验,请在 JDK 1.5及更高版本中使用
*
* @param config
* @return
*/
public static WXPayReport getInstance(WXPayConfig config) {
if (INSTANCE == null) {
synchronized (WXPayReport.class) {
if (INSTANCE == null) {
INSTANCE = new WXPayReport(config);
}
}
}
return INSTANCE;
}
public void report(String uuid, long elapsedTimeMillis,
String firstDomain, boolean primaryDomain, int firstConnectTimeoutMillis, int firstReadTimeoutMillis,
boolean firstHasDnsError, boolean firstHasConnectTimeout, boolean firstHasReadTimeout) {
long currentTimestamp = WXPayUtil.getCurrentTimestamp();
ReportInfo reportInfo = new ReportInfo(uuid, currentTimestamp, elapsedTimeMillis,
firstDomain, primaryDomain, firstConnectTimeoutMillis, firstReadTimeoutMillis,
firstHasDnsError, firstHasConnectTimeout, firstHasReadTimeout);
String data = reportInfo.toLineString(config.getKey());
WXPayUtil.getLogger().info("report {}", data);
if (data != null) {
reportMsgQueue.offer(data);
}
}
@Deprecated
private void reportSync(final String data) throws Exception {
httpRequest(data, DEFAULT_CONNECT_TIMEOUT_MS, DEFAULT_READ_TIMEOUT_MS);
}
@Deprecated
private void reportAsync(final String data) throws Exception {
new Thread(new Runnable() {
public void run() {
try {
httpRequest(data, DEFAULT_CONNECT_TIMEOUT_MS, DEFAULT_READ_TIMEOUT_MS);
}
catch (Exception ex) {
WXPayUtil.getLogger().warn("report fail. reason: {}", ex.getMessage());
}
}
}).start();
}
/**
* http 请求
* @param data
* @param connectTimeoutMs
* @param readTimeoutMs
* @return
* @throws Exception
*/
private static String httpRequest(String data, int connectTimeoutMs, int readTimeoutMs) throws Exception{
BasicHttpClientConnectionManager connManager;
connManager = new BasicHttpClientConnectionManager(
RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", SSLConnectionSocketFactory.getSocketFactory())
.build(),
null,
null,
null
);
HttpClient httpClient = HttpClientBuilder.create()
.setConnectionManager(connManager)
.build();
HttpPost httpPost = new HttpPost(REPORT_URL);
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(readTimeoutMs).setConnectTimeout(connectTimeoutMs).build();
httpPost.setConfig(requestConfig);
StringEntity postEntity = new StringEntity(data, "UTF-8");
httpPost.addHeader("Content-Type", "text/xml");
httpPost.addHeader("User-Agent", WXPayConstants.USER_AGENT);
httpPost.setEntity(postEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
return EntityUtils.toString(httpEntity, "UTF-8");
}
}
WXPayRequest
package com.guangyi.project.utils.WXPayUtil;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import java.io.InputStream;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.security.KeyStore;
import java.security.SecureRandom;
import static com.guangyi.project.utils.WXPayUtil.WXPayConstants.USER_AGENT;
public class WXPayRequest {
private WXPayConfig config;
public WXPayRequest(WXPayConfig config) throws Exception{
this.config = config;
}
/**
* 请求,只请求一次,不做重试
* @param domain
* @param urlSuffix
* @param uuid
* @param data
* @param connectTimeoutMs
* @param readTimeoutMs
* @param useCert 是否使用证书,针对退款、撤销等操作
* @return
* @throws Exception
*/
private String requestOnce(final String domain, String urlSuffix, String uuid, String data, int connectTimeoutMs, int readTimeoutMs, boolean useCert) throws Exception {
BasicHttpClientConnectionManager connManager;
if (useCert) {
// 证书
char[] password = config.getMchID().toCharArray();
InputStream certStream = config.getCertStream();
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.load(certStream, password);
// 实例化密钥库 & 初始化密钥工厂
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, password);
// 创建 SSLContext
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(kmf.getKeyManagers(), null, new SecureRandom());
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
sslContext,
new String[]{"TLSv1"},
null,
new DefaultHostnameVerifier());
connManager = new BasicHttpClientConnectionManager(
RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslConnectionSocketFactory)
.build(),
null,
null,
null
);
}
else {
connManager = new BasicHttpClientConnectionManager(
RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", SSLConnectionSocketFactory.getSocketFactory())
.build(),
null,
null,
null
);
}
HttpClient httpClient = HttpClientBuilder.create()
.setConnectionManager(connManager)
.build();
String url = "https://" + domain + urlSuffix;
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(readTimeoutMs).setConnectTimeout(connectTimeoutMs).build();
httpPost.setConfig(requestConfig);
StringEntity postEntity = new StringEntity(data, "UTF-8");
httpPost.addHeader("Content-Type", "text/xml");
httpPost.addHeader("User-Agent", USER_AGENT + " " + config.getMchID());
httpPost.setEntity(postEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
return EntityUtils.toString(httpEntity, "UTF-8");
}
private String request(String urlSuffix, String uuid, String data, int connectTimeoutMs, int readTimeoutMs, boolean useCert, boolean autoReport) throws Exception {
Exception exception = null;
long elapsedTimeMillis = 0;
long startTimestampMs = WXPayUtil.getCurrentTimestampMs();
boolean firstHasDnsErr = false;
boolean firstHasConnectTimeout = false;
boolean firstHasReadTimeout = false;
IWXPayDomain.DomainInfo domainInfo = config.getWXPayDomain().getDomain(config);
if(domainInfo == null){
throw new Exception("WXPayConfig.getWXPayDomain().getDomain() is empty or null");
}
try {
String result = requestOnce(domainInfo.domain, urlSuffix, uuid, data, connectTimeoutMs, readTimeoutMs, useCert);
elapsedTimeMillis = WXPayUtil.getCurrentTimestampMs()-startTimestampMs;
config.getWXPayDomain().report(domainInfo.domain, elapsedTimeMillis, null);
WXPayReport.getInstance(config).report(
uuid,
elapsedTimeMillis,
domainInfo.domain,
domainInfo.primaryDomain,
connectTimeoutMs,
readTimeoutMs,
firstHasDnsErr,
firstHasConnectTimeout,
firstHasReadTimeout);
return result;
}
catch (UnknownHostException ex) { // dns 解析错误,或域名不存在
exception = ex;
firstHasDnsErr = true;
elapsedTimeMillis = WXPayUtil.getCurrentTimestampMs()-startTimestampMs;
WXPayUtil.getLogger().warn("UnknownHostException for domainInfo {}", domainInfo);
WXPayReport.getInstance(config).report(
uuid,
elapsedTimeMillis,
domainInfo.domain,
domainInfo.primaryDomain,
connectTimeoutMs,
readTimeoutMs,
firstHasDnsErr,
firstHasConnectTimeout,
firstHasReadTimeout
);
}
catch (ConnectTimeoutException ex) {
exception = ex;
firstHasConnectTimeout = true;
elapsedTimeMillis = WXPayUtil.getCurrentTimestampMs()-startTimestampMs;
WXPayUtil.getLogger().warn("connect timeout happened for domainInfo {}", domainInfo);
WXPayReport.getInstance(config).report(
uuid,
elapsedTimeMillis,
domainInfo.domain,
domainInfo.primaryDomain,
connectTimeoutMs,
readTimeoutMs,
firstHasDnsErr,
firstHasConnectTimeout,
firstHasReadTimeout
);
}
catch (SocketTimeoutException ex) {
exception = ex;
firstHasReadTimeout = true;
elapsedTimeMillis = WXPayUtil.getCurrentTimestampMs()-startTimestampMs;
WXPayUtil.getLogger().warn("timeout happened for domainInfo {}", domainInfo);
WXPayReport.getInstance(config).report(
uuid,
elapsedTimeMillis,
domainInfo.domain,
domainInfo.primaryDomain,
connectTimeoutMs,
readTimeoutMs,
firstHasDnsErr,
firstHasConnectTimeout,
firstHasReadTimeout);
}
catch (Exception ex) {
exception = ex;
elapsedTimeMillis = WXPayUtil.getCurrentTimestampMs()-startTimestampMs;
WXPayReport.getInstance(config).report(
uuid,
elapsedTimeMillis,
domainInfo.domain,
domainInfo.primaryDomain,
connectTimeoutMs,
readTimeoutMs,
firstHasDnsErr,
firstHasConnectTimeout,
firstHasReadTimeout);
}
config.getWXPayDomain().report(domainInfo.domain, elapsedTimeMillis, exception);
throw exception;
}
/**
* 可重试的,非双向认证的请求
* @param urlSuffix
* @param uuid
* @param data
* @return
*/
public String requestWithoutCert(String urlSuffix, String uuid, String data, boolean autoReport) throws Exception {
return this.request(urlSuffix, uuid, data, config.getHttpConnectTimeoutMs(), config.getHttpReadTimeoutMs(), false, autoReport);
}
/**
* 可重试的,非双向认证的请求
* @param urlSuffix
* @param uuid
* @param data
* @param connectTimeoutMs
* @param readTimeoutMs
* @return
*/
public String requestWithoutCert(String urlSuffix, String uuid, String data, int connectTimeoutMs, int readTimeoutMs, boolean autoReport) throws Exception {
return this.request(urlSuffix, uuid, data, connectTimeoutMs, readTimeoutMs, false, autoReport);
}
/**
* 可重试的,双向认证的请求
* @param urlSuffix
* @param uuid
* @param data
* @return
*/
public String requestWithCert(String urlSuffix, String uuid, String data, boolean autoReport) throws Exception {
return this.request(urlSuffix, uuid, data, config.getHttpConnectTimeoutMs(), config.getHttpReadTimeoutMs(), true, autoReport);
}
/**
* 可重试的,双向认证的请求
* @param urlSuffix
* @param uuid
* @param data
* @param connectTimeoutMs
* @param readTimeoutMs
* @return
*/
public String requestWithCert(String urlSuffix, String uuid, String data, int connectTimeoutMs, int readTimeoutMs, boolean autoReport) throws Exception {
return this.request(urlSuffix, uuid, data, connectTimeoutMs, readTimeoutMs, true, autoReport);
}
}
WXPayUtil
package com.guangyi.project.utils.WXPayUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.*;
public class WXPayUtil {
private static final String SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final Random RANDOM = new SecureRandom();
/**
* XML格式字符串转换为Map
*
* @param strXML XML字符串
* @return XML数据转换后的Map
* @throws Exception
*/
public static Map<String, String> xmlToMap(String strXML) throws Exception {
try {
Map<String, String> data = new HashMap<String, String>();
DocumentBuilder documentBuilder = WXPayXmlUtil.newDocumentBuilder();
InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
org.w3c.dom.Document doc = documentBuilder.parse(stream);
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getDocumentElement().getChildNodes();
for (int idx = 0; idx < nodeList.getLength(); ++idx) {
Node node = nodeList.item(idx);
if (node.getNodeType() == Node.ELEMENT_NODE) {
org.w3c.dom.Element element = (org.w3c.dom.Element) node;
data.put(element.getNodeName(), element.getTextContent());
}
}
try {
stream.close();
} catch (Exception ex) {
// do nothing
}
return data;
} catch (Exception ex) {
WXPayUtil.getLogger().warn("Invalid XML, can not convert to map. Error message: {}. XML content: {}", ex.getMessage(), strXML);
throw ex;
}
}
/**
* 将Map转换为XML格式的字符串
*
* @param data Map类型数据
* @return XML格式的字符串
* @throws Exception
*/
public static String mapToXml(Map<String, String> data) throws Exception {
org.w3c.dom.Document document = WXPayXmlUtil.newDocument();
org.w3c.dom.Element root = document.createElement("xml");
document.appendChild(root);
for (String key: data.keySet()) {
String value = data.get(key);
if (value == null) {
value = "";
}
value = value.trim();
org.w3c.dom.Element filed = document.createElement(key);
filed.appendChild(document.createTextNode(value));
root.appendChild(filed);
}
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
DOMSource source = new DOMSource(document);
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
transformer.transform(source, result);
String output = writer.getBuffer().toString(); //.replaceAll("\n|\r", "");
try {
writer.close();
}
catch (Exception ex) {
}
return output;
}
/**
* 生成带有 sign 的 XML 格式字符串
*
* @param data Map类型数据
* @param key API密钥
* @return 含有sign字段的XML
*/
public static String generateSignedXml(final Map<String, String> data, String key) throws Exception {
return generateSignedXml(data, key, WXPayConstants.SignType.MD5);
}
/**
* 生成带有 sign 的 XML 格式字符串
*
* @param data Map类型数据
* @param key API密钥
* @param signType 签名类型
* @return 含有sign字段的XML
*/
public static String generateSignedXml(final Map<String, String> data, String key, WXPayConstants.SignType signType) throws Exception {
String sign = generateSignature(data, key, signType);
data.put(WXPayConstants.FIELD_SIGN, sign);
return mapToXml(data);
}
/**
* 判断签名是否正确
*
* @param xmlStr XML格式数据
* @param key API密钥
* @return 签名是否正确
* @throws Exception
*/
public static boolean isSignatureValid(String xmlStr, String key) throws Exception {
Map<String, String> data = xmlToMap(xmlStr);
if (!data.containsKey(WXPayConstants.FIELD_SIGN) ) {
return false;
}
String sign = data.get(WXPayConstants.FIELD_SIGN);
return generateSignature(data, key).equals(sign);
}
/**
* 判断签名是否正确,必须包含sign字段,否则返回false。使用MD5签名。
*
* @param data Map类型数据
* @param key API密钥
* @return 签名是否正确
* @throws Exception
*/
public static boolean isSignatureValid(Map<String, String> data, String key) throws Exception {
return isSignatureValid(data, key, WXPayConstants.SignType.MD5);
}
/**
* 判断签名是否正确,必须包含sign字段,否则返回false。
*
* @param data Map类型数据
* @param key API密钥
* @param signType 签名方式
* @return 签名是否正确
* @throws Exception
*/
public static boolean isSignatureValid(Map<String, String> data, String key, WXPayConstants.SignType signType) throws Exception {
if (!data.containsKey(WXPayConstants.FIELD_SIGN) ) {
return false;
}
String sign = data.get(WXPayConstants.FIELD_SIGN);
return generateSignature(data, key, signType).equals(sign);
}
/**
* 生成签名
*
* @param data 待签名数据
* @param key API密钥
* @return 签名
*/
public static String generateSignature(final Map<String, String> data, String key) throws Exception {
return generateSignature(data, key, WXPayConstants.SignType.MD5);
}
/**
* 生成签名. 注意,若含有sign_type字段,必须和signType参数保持一致。
*
* @param data 待签名数据
* @param key API密钥
* @param signType 签名方式
* @return 签名
*/
public static String generateSignature(final Map<String, String> data, String key, WXPayConstants.SignType signType) throws Exception {
Set<String> keySet = data.keySet();
String[] keyArray = keySet.toArray(new String[keySet.size()]);
Arrays.sort(keyArray);
StringBuilder sb = new StringBuilder();
for (String k : keyArray) {
if (k.equals(WXPayConstants.FIELD_SIGN)) {
continue;
}
if (data.get(k).trim().length() > 0) // 参数值为空,则不参与签名
sb.append(k).append("=").append(data.get(k).trim()).append("&");
}
sb.append("key=").append(key);
if (WXPayConstants.SignType.MD5.equals(signType)) {
return MD5(sb.toString()).toUpperCase();
}
else if (WXPayConstants.SignType.HMACSHA256.equals(signType)) {
return HMACSHA256(sb.toString(), key);
}
else {
throw new Exception(String.format("Invalid sign_type: %s", signType));
}
}
/**
* 获取随机字符串 Nonce Str
*
* @return String 随机字符串
*/
public static String generateNonceStr() {
char[] nonceChars = new char[32];
for (int index = 0; index < nonceChars.length; ++index) {
nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
}
return new String(nonceChars);
}
/**
* 生成 MD5
*
* @param data 待处理数据
* @return MD5结果
*/
public static String MD5(String data) throws Exception {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] array = md.digest(data.getBytes("UTF-8"));
StringBuilder sb = new StringBuilder();
for (byte item : array) {
sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
}
return sb.toString().toUpperCase();
}
/**
* 生成 HMACSHA256
* @param data 待处理数据
* @param key 密钥
* @return 加密结果
* @throws Exception
*/
public static String HMACSHA256(String data, String key) throws Exception {
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
sha256_HMAC.init(secret_key);
byte[] array = sha256_HMAC.doFinal(data.getBytes("UTF-8"));
StringBuilder sb = new StringBuilder();
for (byte item : array) {
sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
}
return sb.toString().toUpperCase();
}
/**
* 日志
* @return
*/
public static Logger getLogger() {
Logger logger = LoggerFactory.getLogger("wxpay java sdk");
return logger;
}
/**
* 获取当前时间戳,单位秒
* @return
*/
public static long getCurrentTimestamp() {
return System.currentTimeMillis()/1000;
}
/**
* 获取当前时间戳,单位毫秒
* @return
*/
public static long getCurrentTimestampMs() {
return System.currentTimeMillis();
}
public static String inputStream2String(InputStream inStream, String encoding){
String result = null;
ByteArrayOutputStream outStream = null;
try {
if(inStream != null){
outStream = new ByteArrayOutputStream();
byte[] tempBytes = new byte[1024];
int count = 0;
while((count = inStream.read(tempBytes)) != -1){
outStream.write(tempBytes, 0, count);
}
tempBytes = null;
outStream.flush();
result = new String(outStream.toByteArray(), encoding);
outStream.close();
}
} catch (Exception e) {
result = null;
}
return result;
}
}
WXPayXmlUtil
package com.guangyi.project.utils.WXPayUtil;
import org.w3c.dom.Document;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
/**
* 2018/7/3
*/
public final class WXPayXmlUtil {
public static DocumentBuilder newDocumentBuilder() throws ParserConfigurationException {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
documentBuilderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
documentBuilderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
documentBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
documentBuilderFactory.setXIncludeAware(false);
documentBuilderFactory.setExpandEntityReferences(false);
return documentBuilderFactory.newDocumentBuilder();
}
public static Document newDocument() throws ParserConfigurationException {
return newDocumentBuilder().newDocument();
}
}
WechatUtil
package com.guangyi.project.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.guangyi.project.config.Constant;
import com.guangyi.project.config.ErrorEnum;
import com.guangyi.project.model.system.ApiAccessEntity;
import com.guangyi.project.model.system.JsApiTicketEntity;
import com.guangyi.project.model.system.ShareModel;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.Cache;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import sun.misc.BASE64Encoder;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.encoders.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.Security;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* @ClassName WechatUtil
* @Description 微信工具类
* @Author LWL
* @Date 9:44 2021/04/20
* @Version 1.0
*/
public class WechatUtil {
private static Logger logger = LoggerFactory.getLogger(WechatUtil.class);
public static void main(String[] args) throws Exception {
//获取access_token
String url = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", Constant.WX_LOGIN_APPID, Constant.WX_LOGIN_SECRET);
//发送post请求读取调用微信接口获取openid用户唯一标识
ApiAccessEntity apiAccessEntity = JSON.parseObject(HttpClientUtil.doGet(url), ApiAccessEntity.class);
//获取ticket
String accessToken = apiAccessEntity.getAccess_token();
//TODO 如果缓存中没有jsApiTicketEntity,重新从微信服务端获取,并保存在缓存中
String url2 = String.format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi",accessToken);
//发送post请求读取调用微信接口获取openid用户唯一标识
JsApiTicketEntity jsApiTicketEntity = JSON.parseObject(HttpClientUtil.doGet(url2), JsApiTicketEntity.class);
String noncestr = WechatUtil.GenerateNonceStr();
String timestamp = WechatUtil.GenerateTimeStamp();
String jsapi_ticket = jsApiTicketEntity.getTicket();
String strSha1 = WechatUtil.getSHA1String(String.format("jsapi_ticket=%s&noncestr=%s×tamp=%s&url=%s", jsapi_ticket, noncestr, timestamp, "http://www.ad618.com/agysc/mini/index.html#/home/entry")).toLowerCase();
System.out.println(strSha1);
}
public static JSONObject getSessionKeyOrOpenId(String code) {
Map<String, String> requestUrlParam = new HashMap<String, String>();
// https://mp.weixin.qq.com/wxopen/devprofile?action=get_profile&token=164113089&lang=zh_CN
//小程序appId
requestUrlParam.put("appid", Constant.WX_LOGIN_APPID);
//小程序secret
requestUrlParam.put("secret", Constant.WX_LOGIN_SECRET);
//小程序端返回的code
requestUrlParam.put("js_code", code);
//默认参数
requestUrlParam.put("grant_type", Constant.WX_LOGIN_GRANT_TYPE);
//发送post请求读取调用微信接口获取openid用户唯一标识
JSONObject jsonObject = JSON.parseObject(HttpClientUtil.doPost(Constant.WX_LOGIN_URL, requestUrlParam));
return jsonObject;
}
public static JSONObject getAccessTokenOrOpenId(String code) {
String grant_type = "authorization_code";
String url = String.format("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=%s",
Constant.WX_LOGIN_APPID, Constant.WX_LOGIN_SECRET, code, grant_type);
//发送post请求读取调用微信接口获取openid用户唯一标识
JSONObject jsonObject = JSON.parseObject(HttpClientUtil.doGet(url));
return jsonObject;
}
/**
* {@code description: 获取微信access_token,并保存在缓存中}
* @param
* @author LWL
* @since 2020/9/5 12:04
*/
public static ApiAccessEntity getCachedAccessToken() {
//获取缓存中的token
EhCacheCacheManager cacheCacheManager = SpringContextUtil.context.getBean(EhCacheCacheManager.class);
//获取Cache
Cache cache = cacheCacheManager.getCache("apiAccessEntityCache");
ApiAccessEntity apiAccessEntity = cache.get(Constant.API_ACCESS_ENTITY, ApiAccessEntity.class);
if(apiAccessEntity == null){
//TODO 如果缓存中没有apiAccessEntity,重新从微信服务端获取,并保存在缓存中
String url = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", Constant.WX_LOGIN_APPID, Constant.WX_LOGIN_SECRET);
//发送post请求读取调用微信接口获取openid用户唯一标识
apiAccessEntity = JSON.parseObject(HttpClientUtil.doGet(url), ApiAccessEntity.class);
cache.put(Constant.API_ACCESS_ENTITY, apiAccessEntity);
}
return apiAccessEntity;
}
/**
* {@code description: 获取ticket}
* @param
* @author LWL
* @since 2020/9/5 12:32
*/
public static JsApiTicketEntity getCachedJsApiTicket() {
//获取缓存中的token
EhCacheCacheManager cacheCacheManager = SpringContextUtil.context.getBean(EhCacheCacheManager.class);
//获取Cache
Cache cache = cacheCacheManager.getCache("JsApiTicketEntityCache");
JsApiTicketEntity jsApiTicketEntity = cache.get(Constant.JS_API_TICKET_ENTITY, JsApiTicketEntity.class);
if(jsApiTicketEntity == null){
String accessToken = getCachedAccessToken().getAccess_token();
//TODO 如果缓存中没有jsApiTicketEntity,重新从微信服务端获取,并保存在缓存中
String url = String.format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi",accessToken);
//发送post请求读取调用微信接口获取openid用户唯一标识
jsApiTicketEntity = JSON.parseObject(HttpClientUtil.doGet(url), JsApiTicketEntity.class);
cache.put(Constant.JS_API_TICKET_ENTITY, jsApiTicketEntity);
}
return jsApiTicketEntity;
}
/**
*
* @description: 生成时间戳,标准北京时间,时区为东八区,自1970年1月1日 0点0分0秒以来的秒数
* @param
* @return: java.lang.String 时间戳
* @author: LWL
* @time: 2021/4/20 17:31
*/
public static String GenerateTimeStamp()
{
//获取秒数
Long second = LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
//获取毫秒数
// Long milliSecond = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
return second.toString();
}
/**
*
* @description: 生成随机串,随机串包含字母或数字
* @param
* @return: java.lang.String 随机串
* @author: LWL
* @time: 2021/4/20 17:32
*/
public static String GenerateNonceStr()
{
return UUID.randomUUID().toString().replaceAll("-","");
}
/**
*
* @description: 获取制定字符串的SHA1散列值
* @param source
* @return: java.lang.String
* @author: LWL
* @time: 2021/4/20 17:32
*/
public static String getSHA1String(String source)
{
return DigestUtils.sha1Hex(source);
}
/**
* 生成小程序二维码
*/
public static BufferedImage scanCode(String scene,String page,int width){
try {
//获取access_token
String url1 = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", Constant.WX_LOGIN_APPID, Constant.WX_LOGIN_SECRET);
//发送post请求读取调用微信接口获取openid用户唯一标识
ApiAccessEntity apiAccessEntity = JSON.parseObject(HttpClientUtil.doGet(url1), ApiAccessEntity.class);
//获取accessToken
String accessToken = apiAccessEntity.getAccess_token();
URL url = new URL("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+accessToken);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");// 提交模式
// conn.setConnectTimeout(10000);//连接超时 单位毫秒
// conn.setReadTimeout(2000);//读取超时 单位毫秒
// 发送POST请求必须设置如下两行
httpURLConnection.setDoOutput(true);// 打开写入属性
httpURLConnection.setDoInput(true);// 打开读取属性
// 设置响应头
httpURLConnection.setRequestProperty("Content-Type", "application/x-javascript; charset=UTF-8");
// 获取URLConnection对象对应的输出流
PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
// 发送请求参数
JSONObject paramJson = new JSONObject();
paramJson.put("scene", scene);//自定义参数
paramJson.put("page", page);
paramJson.put("width", width);
// paramJson.put("auto_color", true);
//line_color生效
// paramJson.put("auto_color", false);
JSONObject lineColor = new JSONObject();
lineColor.put("r", 0);
lineColor.put("g", 0);
lineColor.put("b", 0);
paramJson.put("line_color", lineColor);
printWriter.write(paramJson.toString());
// flush输出流的缓冲
printWriter.flush();
return ImageIO.read(httpURLConnection.getInputStream());
}catch (Exception e) {
e.printStackTrace();
}
return null ;
}
/**
* @description: 分享
* @param shareModel
* @return: void
* @author: LWL
* @time: 2021/6/21 12:10
*/
public static String share(ShareModel shareModel) throws Exception {
//创建图片
BufferedImage img = new BufferedImage(750, 1234, BufferedImage.TYPE_INT_RGB);
//开启画图
Graphics g = img.getGraphics();
//背景 -- 读取互联网图片
BufferedImage back = ImageIO.read(new URL(shareModel.getBackdrop()));
g.drawImage(back.getScaledInstance(750, 1234, Image.SCALE_DEFAULT), 0, 0, null); // 绘制缩小后的图
//商品 banner图
//读取互联网图片
BufferedImage priductUrl = ImageIO.read(new URL(shareModel.getCommodityPic())); //TODO
g.drawImage(priductUrl.getScaledInstance(690,690,Image.SCALE_DEFAULT),30,30,null);
//文案标题
g.setFont(new Font("微软雅黑", Font.BOLD, 34));
g.setColor(new Color(29,29,29));
//绘制文字
g.drawString(shareModel.getCommodityName(), 30, 800);//TODO
//文案
g.setFont(new Font("微软雅黑", Font.PLAIN, 30));
g.setColor(new Color(47,47,47));
int fontlen = getWatermarkLength(shareModel.getInfo(), g);//TODO
//文字长度相对于图片宽度应该有多少行
int line = (new BigDecimal(fontlen).divide((new BigDecimal(back.getWidth()).subtract(new BigDecimal(60))),0,BigDecimal.ROUND_UP)).intValue();
//高度
int y = back.getHeight() - (line + 1) * 30 - 440;
//文字叠加,自动换行叠加
int tempX = 30;
int tempY = y;
//单字符长度
int tempCharLen = 0;
//单行字符总长度临时计算
int tempLineLen = 0;
StringBuffer sb =new StringBuffer();
for(int i=0; i < shareModel.getInfo().length(); i++) {//TODO
char tempChar = shareModel.getInfo().charAt(i);//TODO
tempCharLen = getCharLen(tempChar, g);
tempLineLen += tempCharLen;
if(tempLineLen >= (back.getWidth()-60)) {
//长度已经满一行,进行文字叠加
g.drawString(sb.toString(), tempX, tempY + 40);
//清空内容,重新追加
sb.delete(0, sb.length());
//每行文字间距50
tempY += 50;
tempLineLen =0;
}
//追加字符
sb.append(tempChar);
}
//最后叠加余下的文字
g.drawString(sb.toString(), tempX, tempY + 50);
// //价格背景
// //读取互联网图片
// BufferedImage bground = ImageIO.read(new File("C:\\Users\\Administrator\\Desktop\\beijing.png"));//TODO
// // 绘制缩小后的图
// g.drawImage(bground.getScaledInstance(160, 40, Image.SCALE_DEFAULT), 30, 953, null);
// //限时促销价
// g.setFont(new Font("微软雅黑", Font.PLAIN, 24));
// g.setColor(new Color(255,255,255));
// g.drawString("限时促销价", 50, 980);
//价格
g.setFont(new Font("微软雅黑", Font.PLAIN, 50));
g.setColor(new Color(249,64,64));
g.drawString("¥" + shareModel.getPrice(), 29, 980);//TODO
// //原价
// g.setFont(new Font("微软雅黑", Font.PLAIN, 36));
// g.setColor(new Color(171,171,171));
// String price = "¥" + "14999";//TODO
// g.drawString(price, 260, 1060);
// g.drawLine(250,1048,260+150,1048);
// //商品名称
// g.setFont(new Font("微软雅黑", Font.PLAIN, 32));
// g.setColor(new Color(29,29,29));
// g.drawString("Apple/苹果 iphone12", 30, 1129);//TODO
//头像
BufferedImage head = ImageIO.read(new URL(shareModel.getAvatar())); //TODO
BufferedImage bufferedImage = PicUtils.setRadius(head,100,0);
g.drawImage(bufferedImage.getScaledInstance(100,100,Image.SCALE_DEFAULT),30,1060,null);
//用户昵称
g.setFont(new Font("微软雅黑", Font.PLAIN, 30));
g.setColor(new Color(47,47,47));
g.drawString(shareModel.getNickname(), 150, 1100);//TODO
//文案
g.setFont(new Font("微软雅黑", Font.PLAIN, 25));
g.setColor(new Color(153, 153, 153, 141));
g.drawString("推荐您享受天意商城内购优惠", 150, 1145);//TODO
//生成微信小程序二维码
// BufferedImage qrCode = ImageIO.read(new File("C:\\Users\\Administrator\\Desktop\\qrcode.png"));
BufferedImage qrCode = scanCode(shareModel.getScene(),shareModel.getPage(),shareModel.getWidth());
// 绘制缩小后的图
g.drawImage(qrCode.getScaledInstance(174, 174, Image.SCALE_DEFAULT), 536, 940, null);
//二维码字体
g.setFont(new Font("微软雅黑", Font.PLAIN, 25));
g.setColor(new Color(171,171,171));
//绘制文字
g.drawString("扫描或长按小程序码", 515, 1143);
g.dispose();
//输出流
ByteArrayOutputStream stream = new ByteArrayOutputStream();
ImageIO.write(img, "png", stream);
BASE64Encoder encoder = new BASE64Encoder();
String base64 = encoder.encode(stream.toByteArray());
stream.flush();
stream.close();
return base64;
}
/**
* 获取水印文字总长度
*@paramwaterMarkContent水印的文字
*@paramg
*@return水印文字总长度
*/
public static int getWatermarkLength(String waterMarkContent, Graphics g) {
return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(),0, waterMarkContent.length());
}
public static int getCharLen(char c, Graphics g) {
return g.getFontMetrics(g.getFont()).charWidth(c);
}
public static String decryptData(String encryptDataB64, String sessionKeyB64, String ivB64) {
return new String(
decryptOfDiyIV(
Base64.decode(encryptDataB64),
Base64.decode(sessionKeyB64),
Base64.decode(ivB64)
)
);
}
private static final String KEY_ALGORITHM = "AES";
private static final String ALGORITHM_STR = "AES/CBC/PKCS7Padding";
private static Key key;
private static Cipher cipher;
private static void init(byte[] keyBytes) {
try {
// 如果密钥不足16位,那么就补足. 这个if 中的内容很重要
int base = 16;
if (keyBytes.length % base != 0) {
int groups = keyBytes.length / base + (keyBytes.length % base != 0 ? 1 : 0);
byte[] temp = new byte[groups * base];
Arrays.fill(temp, (byte) 0);
System.arraycopy(keyBytes, 0, temp, 0, keyBytes.length);
keyBytes = temp;
}
// 初始化
Security.addProvider(new BouncyCastleProvider());
// 转化成JAVA的密钥格式
key = new SecretKeySpec(keyBytes, KEY_ALGORITHM);
// 初始化cipher
cipher = Cipher.getInstance(ALGORITHM_STR, "BC");
} catch (Exception e) {
logger.error(ErrorInfoUtil.getErrorInfo(e));
throw ExceptionFormatUtil.formatException(e, ErrorEnum.GETINFO_ERROR);
}
}
/**
* 解密方法
*
* @param encryptedData 要解密的字符串
* @param keyBytes 解密密钥
* @param ivs 自定义对称解密算法初始向量 iv
* @return 解密后的字节数组
*/
private static byte[] decryptOfDiyIV(byte[] encryptedData, byte[] keyBytes, byte[] ivs) {
byte[] encryptedText = null;
init(keyBytes);
try {
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(ivs));
encryptedText = cipher.doFinal(encryptedData);
} catch (Exception e) {
e.printStackTrace();
}
return encryptedText;
}
}
CusAccessObjectUtil
package com.guangyi.project.utils;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletRequest;
/**
* @Auther: LWL
* @Date: 2019/3/6 14:33
* @Description:
*/
public class CusAccessObjectUtil {
/**
* @param request
* @return
*/
public static String getIpAdrress(HttpServletRequest request) {
String Xip = request.getHeader("X-Real-IP");
String XFor = request.getHeader("X-Forwarded-For");
if(!StringUtils.isEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor)){
//多次反向代理后会有多个ip值,第一个ip才是真实ip
int index = XFor.indexOf(",");
if(index != -1){
return XFor.substring(0,index);
}else{
return XFor;
}
}
XFor = Xip;
if(!StringUtils.isEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor)){
return XFor;
}
if (StringUtils.isEmpty(XFor) || "unknown".equalsIgnoreCase(XFor)) {
XFor = request.getHeader("Proxy-Client-IP");
}
if (StringUtils.isEmpty(XFor) || "unknown".equalsIgnoreCase(XFor)) {
XFor = request.getHeader("WL-Proxy-Client-IP");
}
if (StringUtils.isEmpty(XFor) || "unknown".equalsIgnoreCase(XFor)) {
XFor = request.getHeader("HTTP_CLIENT_IP");
}
if (StringUtils.isEmpty(XFor) || "unknown".equalsIgnoreCase(XFor)) {
XFor = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (StringUtils.isEmpty(XFor) || "unknown".equalsIgnoreCase(XFor)) {
XFor = request.getRemoteAddr();
}
return XFor;
}
}
HttpClientUtil
package com.guangyi.project.utils;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.*;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class HttpClientUtil {
public static String doGet(String url, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
String resultString = "";
CloseableHttpResponse response = null;
try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build();
// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
// 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doGet(String url) {
return doGet(url, null);
}
public static String doPost(String url, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建参数列表
if (param != null) {
List<NameValuePair> paramList = new ArrayList<NameValuePair>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
httpPost.setEntity(entity);
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doPost(String url) {
return doPost(url, null);
}
public static String doPostJson(String url, String json) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建请求内容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
/**
* 向指定URL发送GET方法的请求
*
* @param url
* 发送请求的URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return URL 所代表远程资源的响应结果
*/
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
System.out.println(urlNameString);
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(),"UTF8"));
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream(),"UTF8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
}