/**
* 获取预支付id
* @param response
*/
@Override
public String getPrepayId( String ipAddr,HttpServletResponse response) throws IOException, NoSuchAlgorithmException, SignatureException, InvalidKeyException {
// 加载商户私钥(privateKey:私钥字符串)
PrivateKey merchantPrivateKey = PemUtil
.loadPrivateKey(new ByteArrayInputStream(weixinpayProperties.getPrivateKey().getBytes("utf-8")));
// 加载平台证书(mchId:商户号,mchSerialNo:商户证书序列号,apiV3Key:V3密钥)
AutoUpdateCertificatesVerifier verifier = new AutoUpdateCertificatesVerifier(
new WechatPay2Credentials(weixinpayProperties.getMchId(), new PrivateKeySigner(weixinpayProperties.getMchSerialNo(), merchantPrivateKey)),weixinpayProperties.getApiKey().getBytes("utf-8"));
// 初始化httpClient
HttpClient httpClient = WechatPayHttpClientBuilder.create()
.withMerchant(weixinpayProperties.getMchId(), weixinpayProperties.getMchSerialNo(), merchantPrivateKey)
.withValidator(new WechatPay2Validator(verifier)).build();
// 请求URL
HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi");
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-Type", "application/json");
// 订单名称,必填
String subject = "福利兑换测试商品";
// 付款金额,必填
int totalAmount = 1;
// 商品描述,可空
String body = subject + ";";
String outTradeNo = IdUtil.fastSimpleUUID();
// 公用回传参数
String passbackParams = "123456";
Map reqDataMap = new HashMap();
reqDataMap.put("appid", weixinpayProperties.getAppId());
reqDataMap.put("mchid", weixinpayProperties.getMchId());
reqDataMap.put("description", body);
reqDataMap.put("out_trade_no", outTradeNo);
// reqDataMap.put("attach", passbackParams);
reqDataMap.put("notify_url", weixinpayProperties.getNotifyUrl());
Map amountMap = new HashMap();
amountMap.put("total", totalAmount);
amountMap.put("currency", "CNY");
reqDataMap.put("amount", amountMap);
Map payer = new HashMap();
payer.put("openid", "oHj106RQfovPJ549Xhd-iVn2FIns");
reqDataMap.put("payer", payer);
// Map sceneInfoMap = new HashMap();
// sceneInfoMap.put("payer_client_ip", ipAddr);
// Map h5InfoMap = new HashMap();
// h5InfoMap.put("type", "MWEB");
// sceneInfoMap.put("h5_info", h5InfoMap);
// reqDataMap.put("scene_info", sceneInfoMap);
logger.warn("请求参数:{}", JSONObject.toJSONString(reqDataMap));
StringEntity entity = new StringEntity(JSONObject.toJSONString(reqDataMap),"utf-8");
logger.warn("请求参数实体:{}", JSONObject.toJSONString(entity));
httpPost.setEntity(entity);
entity.setContentType("application/json");
Header[] allHeaders = httpPost.getAllHeaders();
logger.warn("allHeaders=============={}",JSONUtil.toJsonStr(allHeaders));
// String token = WeixinTokenUtil.getToken("POST", "https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi", JSONObject.toJSONString(reqDataMap));
// logger.warn("获取到的token:{}", token);
// httpPost.setHeader("Authorization", token);
// 完成签名并执行请求
HttpResponse payResponse = httpClient.execute(httpPost);
Header[] allHeaders2 = httpPost.getAllHeaders();
logger.warn("allHeaders2=============={}",JSONUtil.toJsonStr(allHeaders2));
int statusCode = payResponse.getStatusLine().getStatusCode();
logger.warn("statusCode:{}", statusCode);
String prepay_id = "";
if (statusCode == 200) {
logger.warn("success,return body {} ", EntityUtils.toString(payResponse.getEntity()));
prepay_id = JSONObject.parseObject(EntityUtils.toString(payResponse.getEntity())).get("prepay_id").toString();
logger.warn("prepay_id {} ", prepay_id);
// response.getWriter().write(h5_url);
} else if (statusCode == 204) {
logger.warn("success");
} else {
logger.warn("failed,resp code = " + statusCode + ",return body = " + JSONObject.toJSONString(payResponse));
throw new IOException("request failed");
}
return prepay_id;
}
错误日志,找不到错误原因?
resp code = 400,return body = {"allHeaders":[{"buffer":{"empty":false,"full":false},"elements":[{"name":"nginx","parameterCount":0,"parameters":[]}],"name":"Server","value":"nginx","valuePos":7},{"buffer":{"empty":false,"full":false},"elements":[{"name":"Sat","parameterCount":0,"parameters":[]},{"name":"04 Jan 2025 03:10:19 GMT","parameterCount":0,"parameters":[]}],"name":"Date","value":"Sat, 04 Jan 2025 03:10:19 GMT","valuePos":5},{"buffer":{"empty":false,"full":false},"elements":[{"name":"application/json","parameterCount":1,"parameters":[{"name":"charset","value":"utf-8"}]}],"name":"Content-Type","value":"application/json; charset=utf-8","valuePos":13},{"buffer":{"empty":false,"full":false},"elements":[{"name":"58","parameterCount":0,"parameters":[]}],"name":"Content-Length","value":"58","valuePos":15},{"buffer":{"empty":false,"full":false},"elements":[{"name":"keep-alive","parameterCount":0,"parameters":[]}],"name":"Connection","value":"keep-alive","valuePos":11},{"buffer":{"empty":false,"full":false},"elements":[{"name":"timeout","parameterCount":0,"parameters":[],"value":"8"}],"name":"Keep-Alive","value":"timeout=8","valuePos":11},{"buffer":{"empty":false,"full":false},"elements":[{"name":"no-cache","parameterCount":0,"parameters":[]},{"name":"must-revalidate","parameterCount":0,"parameters":[]}],"name":"Cache-Control","value":"no-cache, must-revalidate","valuePos":14},{"buffer":{"empty":false,"full":false},"elements":[{"name":"nosniff","parameterCount":0,"parameters":[]}],"name":"X-Content-Type-Options","value":"nosniff","valuePos":23},{"buffer":{"empty":false,"full":false},"elements":[{"name":"089BCDE2BB0610B6031896CD8C58209FA00E28F68E03-268501091","parameterCount":0,"parameters":[]}],"name":"Request-ID","value":"089BCDE2BB0610B6031896CD8C58209FA00E28F68E03-268501091","valuePos":11},{"buffer":{"empty":false,"full":false},"elements":[{"name":"zh-CN","parameterCount":0,"parameters":[]}],"name":"Content-Language","value":"zh-CN","valuePos":17},{"buffer":{"empty":false,"full":false},"elements":[{"name":"46dd8158e7c75b1798e6c44fb5692707","parameterCount":0,"parameters":[]}],"name":"Wechatpay-Nonce","value":"46dd8158e7c75b1798e6c44fb5692707","valuePos":16},{"buffer":{"empty":false,"full":true},"elements":[{"name":"F311nyMKh6n5W0FJuWR8JisX0xyPjQlaiExUi+/137ntNU2Yz0kVFOB8MXxLBcono0Fasb5Ezgfj2qnSnpEQlVeKVtH8dEalKT75s9UXCsTNFUCAcW+/eDI/i8kdSWUyHqnMQdVNX4a3hx2hiS6E78iuDH4GuRTew5HEToKX1WOeD+ETQ1bAeF0ry0HVXCNDdM4xncMZL2pOnQqGgvjjjXo9UM8KYMQ1lz7OzH6eK0bJWnkuly7Bv45b5BaUPB7OmVQ1zS+EC7XMk7ivpcHWLVSVmA3Jpij4ojZ6Q4gysMsGjSF58oTT9M9Diqdxn2jXeUExd8z6khzd0LFk+I0DjA","parameterCount":0,"parameters":[],"value":"="}],"name":"Wechatpay-Signature","value":"F311nyMKh6n5W0FJuWR8JisX0xyPjQlaiExUi+/137ntNU2Yz0kVFOB8MXxLBcono0Fasb5Ezgfj2qnSnpEQlVeKVtH8dEalKT75s9UXCsTNFUCAcW+/eDI/i8kdSWUyHqnMQdVNX4a3hx2hiS6E78iuDH4GuRTew5HEToKX1WOeD+ETQ1bAeF0ry0HVXCNDdM4xncMZL2pOnQqGgvjjjXo9UM8KYMQ1lz7OzH6eK0bJWnkuly7Bv45b5BaUPB7OmVQ1zS+EC7XMk7ivpcHWLVSVmA3Jpij4ojZ6Q4gysMsGjSF58oTT9M9Diqdxn2jXeUExd8z6khzd0LFk+I0DjA==","valuePos":20},{"buffer":{"empty":false,"full":false},"elements":[{"name":"1735960219","parameterCount":0,"parameters":[]}],"name":"Wechatpay-Timestamp","value":"1735960219","valuePos":20},{"buffer":{"empty":false,"full":false},"elements":[{"name":"53ACA85B1F0054C927E51A48FC2C69D16D7A2886","parameterCount":0,"parameters":[]}],"name":"Wechatpay-Serial","value":"53ACA85B1F0054C927E51A48FC2C69D16D7A2886","valuePos":17},{"buffer":{"empty":false,"full":false},"elements":[{"name":"WECHATPAY2-SHA256-RSA2048","parameterCount":0,"parameters":[]}],"name":"Wechatpay-Signature-Type","value":"WECHATPAY2-SHA256-RSA2048","valuePos":25}],"entity":{"chunked":false,"contentLength":58,"contentType":{"$ref":"$.allHeaders[2]"},"repeatable":false,"streaming":true},"locale":"en_US","params":{"names":[]},"protocolVersion":{"major":1,"minor":1,"protocol":"HTTP"},"statusLine":{"protocolVersion":{"$ref":"$.protocolVersion"},"reasonPhrase":"Bad Request","statusCode":400}}
问题解决:openid传入错误,使用了微信的unionid,导致400。
"openid", "oHj106RQfovPJ549Xhd-iVn2FIns",替换成正确的openid即可