用java 对接微信支付的代码
以下是一个简单的Java代码示例,用于将微信支付集成到你的应用程序中:
-
首先,你需要在微信支付官网上注册并获取你的应用程序的AppID和密钥。
-
接下来,你需要在你的Java应用程序中创建一个WeChatPay类,并在其中实现必要的方法:
public class WeChatPay {
private String appID; // 微信支付AppID
private String mchID; // 商户号
private String apiKey; // API密钥
public WeChatPay(String appID, String mchID, String apiKey) {
this.appID = appID;
this.mchID = mchID;
this.apiKey = apiKey;
}
// 生成签名
public String generateSignature(Map<String, String> data) {
String stringA = MapUtils.mapJoin(data, false, false);
String stringSignTemp = stringA + "&key=" + apiKey;
return DigestUtils.md5Hex(stringSignTemp).toUpperCase();
}
// 将请求数据转换为XML格式
public String generateXML(Map<String, String> data) {
StringBuilder sb = new StringBuilder();
sb.append("<xml>");
for (String key : data.keySet()) {
sb.append("<").append(key).append(">")
.append(data.get(key))
.append("</").append(key).append(">");
}
sb.append("</xml>");
return sb.toString();
}
// 发送支付请求
public String sendPaymentRequest(Map<String, String> data) throws Exception {
String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
data.put("appid", appID);
data.put("mch_id", mchID);
data.put("nonce_str", RandomStringUtils.randomAlphanumeric(32));
data.put("sign", generateSignature(data));
String xml = generateXML(data);
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(xml, ContentType.APPLICATION_XML);
httpPost.setEntity(entity);
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
HttpEntity responseEntity = response.getEntity();
String responseXML = EntityUtils.toString(responseEntity, "UTF-8");
return responseXML;
} finally {
response.close();
}
}
}
- 接下来,你可以使用上述类来发送支付请求。例如,以下是一个简单的Java代码示例,用于向微信支付发送一笔支付请求:
Map<String, String> data = new HashMap<>();
data.put("body", "测试商品");
data.put("out_trade_no", "20210101000001");
data.put("total_fee", "100");
data.put("spbill_create_ip", "127.0.0.1");
data.put("notify_url", "http://example.com/wechatpay/notify");
data.put("trade_type", "APP");
WeChatPay weChatPay = new WeChatPay("your_app_id", "your_mch_id", "your_api_key");
String responseXML = weChatPay.sendPaymentRequest(data);
- 最后,你需要处理微信支付服务器发送的支付通知。你可以使用Spring框架中的
@RequestMapping注解来处理HTTP POST请求,如下所示:
@RequestMapping(value = "/wechatpay/notify", method = RequestMethod.POST)
public void handlePaymentNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
String responseXML = IOUtils.toString(request.getInputStream(), "UTF-8");
// 解析XML并处理支付通知
// ...
}
注意,你需要在微信支付官网上设置你的应用程序的支付通知URL,并在支付请求中指定该URL。微信支付服务器将使用该URL向你的应用程序发送支付通知。
原文地址: https://www.cveoy.top/t/topic/EWH 著作权归作者所有。请勿转载和采集!