当我使用的微信的依赖版本大于0.4.2的时候,就可以使用一下方法进行验签和解密
现在我是用的版本是0.4.8
<dependency>
<groupId>com.github.wechatpay-apiv3</groupId>
<artifactId>wechatpay-apache-httpclient</artifactId>
<version>0.4.8</version>
</dependency>
以下是我写的回调函数,也就是回调接口
@PostMapping("/wx-pay-call-back.json")
public String wxPayCallBack(HttpServletRequest request, HttpServletResponse response) throws ValidationException, ParseException, GeneralSecurityException {
String readData = HttpUtils.readData(request);
NotificationRequest notificationRequest = new NotificationRequest.Builder()
.withSerialNumber(request.getHeader(WechatPayHttpHeaders.WECHAT_PAY_SERIAL))
.withNonce(request.getHeader(WechatPayHttpHeaders.WECHAT_PAY_NONCE))
.withTimestamp(request.getHeader(WechatPayHttpHeaders.WECHAT_PAY_TIMESTAMP))
.withSignature(request.getHeader(WechatPayHttpHeaders.WECHAT_PAY_SIGNATURE))
.withBody(readData)
.build();
NotificationHandler handler = new NotificationHandler(
verifier, config.getApiV3Key().getBytes(StandardCharsets.UTF_8));
// 验签和解析请求体
Notification notification = handler.parse(notificationRequest);
log.info("====================验签和解析请求体=================>>{}",notification.toString());
AesUtil util = new AesUtil(config.getApiV3Key().getBytes(StandardCharsets.UTF_8));
Notification.Resource resource = notification.getResource();
String ciphertext = resource.getCiphertext();
log.info("===密文==={}",ciphertext);
String associatedData = resource.getAssociatedData();
String nonce = resource.getNonce();
String plainText = util.decryptToString(associatedData.getBytes(StandardCharsets.UTF_8),nonce.getBytes(StandardCharsets.UTF_8),ciphertext);
log.info("===明文==={}",plainText);
response.setStatus(200);
Map<String,String> result = new HashMap<>();
result.put("code","SUCCESS");
result.put("message","成功");
return JSONObject.toJSONString(result);
}
工具类
//处理微信回diao xin xi
public class HttpUtils {
/**
* 将通知参数转化为字符串
* @param request
* @return
*/
public static String readData(HttpServletRequest request) {
BufferedReader br = null;
try {
StringBuilder result = new StringBuilder();
br = request.getReader();
for (String line; (line = br.readLine()) != null; ) {
if (result.length() > 0) {
result.append("\n");
}
result.append(line);
}
return result.toString();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}