package com.lunhan.water.common.wechat;
|
|
import com.lunhan.water.common.security.RSAUtil;
|
import com.lunhan.water.common.util.LocalDateTimeUtil;
|
import com.lunhan.water.common.util.RandVerifyCode;
|
|
import java.nio.charset.StandardCharsets;
|
import java.security.Signature;
|
import java.util.Base64;
|
|
public class WechatAuthorization {
|
public String schema;
|
public String merchantId;
|
public String certificateSerialNo;
|
public String privateKeyPath;
|
|
public WechatAuthorization(String merchantId, String certificateSerialNo, String privateKeyPath) {
|
this.schema = "WECHATPAY2-SHA256-RSA2048";
|
this.merchantId = merchantId;
|
this.certificateSerialNo = certificateSerialNo;
|
this.privateKeyPath = privateKeyPath;
|
}
|
|
public WechatAuthorization(String schema, String merchantId, String certificateSerialNo, String privateKeyPath) {
|
this.schema = schema;
|
this.merchantId = merchantId;
|
this.certificateSerialNo = certificateSerialNo;
|
this.privateKeyPath = privateKeyPath;
|
}
|
|
/**
|
* 构建授权信息 GET - getToken("GET", httpurl, ""); POST - getToken("POST", httpurl, json)
|
* @param method 请求方法 GET/POST
|
* @param url 请求接口地址
|
* @param body 请求正文内容,GET请求传空字符串
|
*/
|
public String getAuthorization(String method, String url, String body) {
|
return String.format("%s %s", schema, this.getToken(method, url, body));
|
}
|
|
// Authorization: <schema> <token>
|
// GET - getToken("GET", httpurl, "")
|
// POST - getToken("POST", httpurl, json)
|
String getToken(String method, String url, String body) {
|
String nonceStr = RandVerifyCode.complexCode(8);
|
long timestamp = LocalDateTimeUtil.nowTimeStampSec();
|
String message = buildMessage(method, url, timestamp, nonceStr, body);
|
String signature = sign(message.getBytes(StandardCharsets.UTF_8));
|
|
return "mchid=\"" + merchantId + "\","
|
+ "nonce_str=\"" + nonceStr + "\","
|
+ "timestamp=\"" + timestamp + "\","
|
+ "serial_no=\"" + certificateSerialNo + "\","
|
+ "signature=\"" + signature + "\"";
|
}
|
|
public String sign(byte[] message) {
|
try {
|
Signature sign = Signature.getInstance("SHA256withRSA");
|
sign.initSign(RSAUtil.getPrivateKey(privateKeyPath));
|
sign.update(message);
|
|
return Base64.getEncoder().encodeToString(sign.sign());
|
} catch (Exception e) {
|
throw new RuntimeException("RSA错误: " + e.getMessage());
|
}
|
}
|
|
String buildMessage(String method, String url, long timestamp, String nonceStr, String body) {
|
return method + "\n"
|
+ url + "\n"
|
+ timestamp + "\n"
|
+ nonceStr + "\n"
|
+ body + "\n";
|
}
|
}
|