wechatpay-apache-httpclient验签
时间: 2024-12-25 12:13:25 浏览: 4
微信支付的Apache HttpClient集成主要用于发起HTTPS请求,并对返回的微信支付API响应进行签名验证。首先,你需要设置HttpClient并配置SSLContext来支持加密通信。以下是基本步骤:
1. **创建HttpClient实例**:
```java
CloseableHttpClient httpClient = HttpClients.createDefault();
```
2. **构建HTTPS请求**:
```java
HttpGet request = new HttpGet("https://api.mch.weixin.qq.com/pay/unifiedorder");
request.setHeader(HttpHeaders.CONTENT_TYPE, "application/json; charset=utf-8");
```
3. **获取服务器响应**:
```java
HttpResponse response = httpClient.execute(request);
```
4. **解析响应内容并获取待验证的数据**:
```java
String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
JSONObject jsonResponse = JSON.parseObject(responseBody);
String signatureField = jsonResponse.getString("sign");
String rawResponseData = jsonResponse.toJSONString(); // 去掉sign字段后再转字符串
```
5. **按照微信官方提供的验签算法计算原始数据的签名**:
```java
Map<String, String> signMap = new HashMap<>();
signMap.put("appid", "your_appid");
signMap.put("noncestr", jsonResponse.getString("nonce_str"));
// ... 其他需要签名的参数
signMap.remove("sign"); // 验证前从原始数据中移除签名字段
String computedSignature = WechatPaySignature.computeSignature(signMap);
```
6. **比较服务器签名与自动生成的签名**:
```java
if (!computedSignature.equals(signatureField)) {
throw new SignatureException("Invalid signature from WeChat Pay API response.");
}
```
阅读全文