【Java】Apache HttpClient调用微信支付API v3报错:找不到证书序列号对应的证书
在使用微信支付API v3版本时,需要在【API安全】中设置商户API证书、API v3秘钥,如下:
下载下来的文件夹如下,包含p12格式、pem格式的商户API证书,和pem格式的商户API私钥:
如题,“找不到证书序列号对应的证书”,是因为在使用 wechatpay-apache-httpclient 调用微信支付时,使用的 wechatPayCertificates 参数为 微信支付平台证书,而不是商户API证书:
WechatPayHttpClientBuilder builder = WechatPayHttpClientBuilder.create()
.withMerchant(merchantId, merchantSerialNumber, merchantPrivateKey)
.withWechatPay(wechatPayCertificates); //微信支付平台证书
“平台证书”需要调用 “获取平台证书接口“ 进行获取,可以使用微信官方提供的Postman脚本进行获取,如下获取到的结果:
还需要通过其中的associated_data、nonce、ciphertext参数 和 APIv3秘钥,解密出平台证书,参考代码:
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class AesUtil {
static final int KEY_LENGTH_BYTE = 32;
static final int TAG_LENGTH_BIT = 128;
static final byte[] aesKey = "5BAkGA1UdE3CQCMAAw3uiPA9375JXNYN".getBytes();
public static String decryptToString(byte[] associatedData, byte[] nonce, String ciphertext)
throws GeneralSecurityException, IOException {
try {
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
SecretKeySpec key = new SecretKeySpec(aesKey, "AES");
GCMParameterSpec spec = new GCMParameterSpec(TAG_LENGTH_BIT, nonce);
cipher.init(Cipher.DECRYPT_MODE, key, spec);
cipher.updateAAD(associatedData);
return new String(cipher.doFinal(Base64.getDecoder().decode(ciphertext)), "utf-8");
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
throw new IllegalStateException(e);
} catch (InvalidKeyException | InvalidAlgorithmParameterException e) {
throw new IllegalArgumentException(e);
}
}
}
将获得平台证书字符串,去掉换行符\n,写入.pem格式证书文件即可:
另外官方建议定期去更新平台证书,见平台证书更新指引。