java微信支付v2代码
时间: 2023-07-10 18:25:01 浏览: 55
以下是 Java 版本的微信支付 v2 代码示例:
1. 统一下单接口
```java
public String unifiedOrder(String body, String out_trade_no, int total_fee, String spbill_create_ip, String notify_url, String trade_type, String openid) throws Exception {
// 构造请求参数
SortedMap<String, Object> params = new TreeMap<>();
params.put("appid", appid);
params.put("mch_id", mch_id);
params.put("nonce_str", WXPayUtil.generateNonceStr());
params.put("body", body);
params.put("out_trade_no", out_trade_no);
params.put("total_fee", total_fee);
params.put("spbill_create_ip", spbill_create_ip);
params.put("notify_url", notify_url);
params.put("trade_type", trade_type);
if (trade_type.equals("JSAPI")) {
params.put("openid", openid);
}
// 生成签名
String sign = WXPayUtil.generateSignature(params, key);
params.put("sign", sign);
// 请求微信支付统一下单接口
String xml = WXPayUtil.mapToXml(params);
String responseXml = HttpUtil.postData(WXPayConstants.UNIFIED_ORDER_URL, xml);
Map<String, String> responseMap = WXPayUtil.xmlToMap(responseXml);
// 检查返回结果
if (!"SUCCESS".equals(responseMap.get("return_code"))) {
throw new Exception(responseMap.get("return_msg"));
}
if (!"SUCCESS".equals(responseMap.get("result_code"))) {
throw new Exception(responseMap.get("err_code_des"));
}
// 返回预支付交易会话标识
if (trade_type.equals("JSAPI")) {
return responseMap.get("prepay_id");
} else {
return responseMap.get("code_url");
}
}
```
2. 支付结果通知处理
```java
public String handleNotify(HttpServletRequest request) throws Exception {
String xml = IOUtils.toString(request.getInputStream(), StandardCharsets.UTF_8);
Map<String, String> params = WXPayUtil.xmlToMap(xml);
if (!WXPayUtil.isSignatureValid(params, key)) {
throw new Exception("签名校验失败");
}
if (!"SUCCESS".equals(params.get("return_code"))) {
throw new Exception(params.get("return_msg"));
}
if (!"SUCCESS".equals(params.get("result_code"))) {
throw new Exception(params.get("err_code_des"));
}
// TODO: 处理支付结果通知
// ...
return WXPayUtil.mapToXml(Collections.singletonMap("return_code", "SUCCESS"));
}
```
以上代码仅供参考,实际使用时需要根据具体业务场景进行调整。同时,建议使用官方提供的 SDK 或第三方库来简化开发。