Java对接微信支付
String spbill_create_ip = PaymentUtils.getIpAddress(request);
if (!PaymentUtils.isIp(spbill_create_ip)) {
spbill_create_ip = "127.0.0.1";
}
String nonce_str = 1 + CommonUtil.getVerificationCode(15);
// 微信app支付十个必须要传入的参数
Map<String, Object> params = new HashMap<>();
// 商户号
params.put("mch_id", “mch_id”);
// 随机字符串
params.put("nonce_str", nonce_str);
// 商品描述trade_type
params.put("body", "App weChat pay!");
// 商户订单号
params.put("out_trade_no", order.getOrderSn());
// 总金额(分)
params.put("total_fee", 1);
// 终端IP
params.put("spbill_create_ip", spbill_create_ip);
// 通知地址
params.put("notify_url", appProperties.getWx().getNotify_url());
// 交易类型:JS_API=公众号支付、NATIVE=扫码支付、APP=app支付
//type为0时APP支付 type为1时小程序支付
if (type == 0) {
params.put("trade_type", "APP");
// 应用ID
params.put("appid", appProperties.getWx().getApp_id());
} else {
params.put("trade_type", "JSAPI");
params.put("openid", userService.getInfo().getOpenid());
params.put("appid", appProperties.getWx().getJsapi_app_id());
}
// 签名
String sign = PaymentUtils.sign(params, appProperties.getWx().getApi_key());
params.put("sign", sign);
String xmlData = PaymentUtils.mapToXml(params);
System.out.println("----------------- >>>> " + xmlData);
// 向微信发起预支付
String wxRetXmlData = HttpUtil.sendPostXml(appProperties.getWx().getCreate_order_url(), xmlData, null);
Map wxRetMapData = PaymentUtils.xmlToMap(wxRetXmlData);
Assert.notNull(wxRetMapData, ErrerMsg.ERRER20517.getMessage());
log.info("weChat pre pay ResponseObj data: {}", wxRetMapData);
// 封装参数返回App端
Map<String, Object> responseObj = new HashMap<>();
String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
//type=0的时候是对接APP支付
if (type == 0) {
responseObj.put("appid", appProperties.getWx().getApp_id());
responseObj.put("package", "Sign=WXPay");
responseObj.put("partnerid", appProperties.getWx().getMch_id());
responseObj.put("prepayid", wxRetMapData.get("prepay_id").toString());
responseObj.put("noncestr", nonce_str);
responseObj.put("timestamp", timestamp);
} else {
//type != 0 对接小程序开发
responseObj.put("appId", appProperties.getWx().getJsapi_app_id());
responseObj.put("signType", "MD5");
responseObj.put("package", "prepay_id=" + wxRetMapData.get("prepay_id").toString());
responseObj.put("nonceStr", nonce_str);
responseObj.put("timeStamp", timestamp);
}
// 对返回给App端的数据进行签名
responseObj.put("sign", PaymentUtils.sign(responseObj, appProperties.getWx().getApi_key()));
PaymentUtils.sign(Map<String, Object> params, String apiKey)
public static String sign(Map<String, Object> params) {
StringBuilder sb = new StringBuilder();
Set<Map.Entry<String, Object>> set = new TreeMap<>(params).entrySet();
for (Map.Entry<String, Object> entry : set) {
String k = entry.getKey();
Object v = entry.getValue();
sb.append(k).append("=").append(v).append("&");
}
String s = sb.toString();
return Objects.requireNonNull(MD5(s.substring(0, s.length() - 1))).toUpperCase();
}
PaymentUtils.xmlToMap(String xmlStr)
public static Map<String, String> xmlToMap(String xmlStr) {
try (InputStream inputStream = new ByteArrayInputStream(xmlStr.getBytes(StandardCharsets.UTF_8))) {
Map<String, String> data = new HashMap<>();
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document doc = documentBuilder.parse(inputStream);
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) {
Element element = (Element) node;
data.put(element.getNodeName(), element.getTextContent());
}
}
return data;
} catch (Exception ex) {
log.warn("xml convert to map failed message: {}", ex.getMessage());
return null;
}
}
PaymentUtils.mapToXml(Map<String, Object> params)
public static String mapToXml(Map<String, Object> params) {
StringBuilder sb = new StringBuilder();
Set<Map.Entry<String, Object>> es = params.entrySet();
Iterator<Map.Entry<String, Object>> it = es.iterator();
sb.append("<xml>");
while (it.hasNext()) {
Map.Entry<String, Object> entry = it.next();
String k = entry.getKey();
Object v = entry.getValue();
sb.append("<").append(k).append(">").append(v).append("</").append(k).append(">");
}
sb.append("</xml>");
return sb.toString();
}
HttpUtil.sendPostXml(String url, String xml, Map<String, Object> headers)
public static String sendPostXml(String url, String xml, Map<String, Object> headers) {
String ResponseObj = null;
try {
HttpPost httpPost = new HttpPost(url);
setHeaders(headers, httpPost);
StringEntity entity = new StringEntity(xml, StandardCharsets.UTF_8);
httpPost.addHeader("Content-Type", "text/xml");
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity responseData = response.getEntity();
ResponseObj = EntityUtils.toString(responseData, StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
return ResponseObj;
}
转载自原文链接, 如需删除请联系管理员。
原文链接:Java对接微信支付预下单,转载请注明来源!