引入dom4j依赖
- 配置文件在项目中新增一个配置文件,例如
wechat.properties
,并添加以下内容:
# 微信支付相关配置
# 公众账号ID
weixin.appId = YOUR_APP_ID
# 商户号
weixin.mchId = YOUR_MCH_ID
# API密钥,用于签名
weixin.apiKey = YOUR_API_KEY
# 支付成功后的回调地址
weixin.notifyUrl = YOUR_NOTIFY_URL
- 发起微信支付定义一个
pay
方法,用于发起微信支付:
public class WeChatPayService {
private static final String UNIFIED_ORDER_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
private final String appId;
private final String mchId;
private final String apiKey;
private final String notifyUrl;
public WeChatPayService(String appId, String mchId, String apiKey, String notifyUrl) {
this.appId = appId;
this.mchId = mchId;
this.apiKey = apiKey;
this.notifyUrl = notifyUrl;
}
public String pay(String openid, String orderId, int totalFee, String ipAddress) throws Exception {
Map<String, String> params = new HashMap<>();
params.put("appid", appId);
params.put("mch_id", mchId);
params.put("nonce_str", UUID.randomUUID().toString().replaceAll("-", ""));
params.put("",", "商品描述");
params.put("out_trade_no", orderId);
params.put("total_fee", String.valueOf(totalFee));
params.put("spbill_create_ip", ipAddress);
params.put("notify_url", notifyUrl);
params.put("trade_type", "JSAPI");
params.put("openid", openid);
String xml = buildXml(params);
String responseXml = HttpUtil.post(UNIFIED_ORDER_URL, xml);
Map<String, String> resultMap = parseXml(responseXml);
String returnCode = resultMap.get("return_code");
if (!"SUCCESS".equals(returnCode)) {
throw new Exception(resultMap.get("return_msg"));
}
String resultCode = resultMap.get("result_code");
if (!"SUCCESS".equals(resultCode)) {
throw new Exception(resultMap.get("err_code_des"));
}
String prepayId = resultMap.get("prepay_id");
String nonceStr = UUID.randomUUID().toString().replaceAll("-", "");
long timestamp = System.currentTimeMillis() / 1000;
String packageStr = "prepay_id=" + prepayId;
String signType = "MD5";
String sign = sign(appId, mchId, nonceStr, packageStr, signType, apiKey, timestamp);
Map<String, String> result = new HashMap<>();
result.put("appId", appId);
result.put("timeStamp", String.valueOf(timestamp));
result.put("nonceStr", nonceStr);
result.put("package", packageStr);
result.put("signType", signType);
result.put("paySign", sign);
return new ObjectMapper().writeValueAsString(result);
}
private String buildXml(Map<String, String> params) throws Exception {
Document document = DocumentHelper.createDocument();
Element root = document.addElement("xml");
for (Map.Entry<String, String> entry : params.entrySet()) {
root.addElement(entry.getKey()).addText(entry.getValue());
}
return document.asXML();
}
private Map<String, String> parseXml(String xml) throws Exception {
Map<String, String> resultMap = new HashMap<>();
Document document = DocumentHelper.parseText(xml);
Element root = document.getRootElement();
List<Element> elements = root.elements();
for (Element element : elements) {
resultMap.put(element.getName(), element.getText());
}
return resultMap;
}
private String sign(String appId, String mchId, String nonceStr, String packageStr, String signType, String apiKey, long timestamp) throws Exception {
Map<String, String> params = new HashMap<>();
params.put("appId", appId);
params.put("timeStamp", String.valueOf(timestamp));
params.put("nonceStr", nonceStr);
params.put("package", packageStr);
params.put("signType", signType);
List<String> sortedKeys = new ArrayList<>(params.keySet());
Collections.sort(sortedKeys);
StringBuilder sb = new StringBuilder();
for (String key : sortedKeys) {
sb.append(key).append("=").append(params.get(key)).append("&");
}
sb.append("key=").append(apiKey);
String sign = DigestUtils.md5Hex(sb.toString()).toUpperCase();
return sign;
}
}
- 支付结果通知定义一个
notify
方法,用于处理微信支付结果通知:
public class WeChatPayService {
public boolean notify(String requestBody) throws Exception {
Map<String, String> params = parseXml(requestBody);
String returnCode = params.get("return_code");
if (!"SUCCESS".equals(returnCode)) {
return false;
}
String resultCode = params.get("result_code");
if (!"SUCCESS".equals(resultCode)) {
return false;
}
String appId = params.get("appid");
String mchId = params.get("mch_id");
String openid = params.get("openid");
String orderId = params.get("out_trade_no");
String transactionId = params.get("transaction_id");
int totalFee = Integer.parseInt(params.get("total_fee"));
String sign = params.get("sign");
String signType = params.get("sign_type");
params.remove("sign");
params.remove("sign_type");
List<String> sortedKeys = new ArrayList<>(params.keySet());
Collections.sort(sortedKeys);
StringBuilder sb = new StringBuilder();
for (String key : sortedKeys) {
sb.append(key).append("=").append(params.get(key)).append("&");
}
sb.append("key=").append(apiKey);
String calculatedSign = DigestUtils.md5Hex(sb.toString()).toUpperCase();
if (!calculatedSign.equals(sign)) {
return false;
}
// 在这里处理支付结果
// ...
return true;
}
}
- 使用示例
public class Main {
public static void main(String[] args) throws Exception {
Properties props = new Properties();
props.load(Main.class.getClassLoader().getResourceAsStream("wechat.properties"));
String appId = props.getProperty("weixin.appId");
String mchId = props.getProperty("weixin.mch");
String apiKey = props.getProperty("weixin.apiKey");
String notifyUrl = props.getProperty("weixin.notifyUrl");
WeChatPayService payService = new WeChatPayService(appId, mchId, apiKey, notifyUrl);
// 发起支付
String openid = "YOUR_OPENID";
String orderId = "YOUR_ORDER_ID";
int totalFee = 100;
String ipAddress = "YOUR_IP_ADDRESS";
String result = payService.pay(openid, orderId, totalFee, ipAddress);
}
}