新接入商户号,配置后提示错误《下载平台证书返回状态码异常,状态码为:500》,查了下之前有人反馈《新商户不再签发平台证书,需要使用商户公钥进行敏感信息加密和验签》,这个商户公钥是通过 https://pay.weixin.qq.com/doc/v3/merchant/4012153196 这里获取的吗,但是下载的文件pub_key.pem 在加载的时候提示错误,《无效的证书》, 《Unable to initialize, java.io.IOException: Too short》,加载的代码如下 使用的是 https://github.com/wechatpay-apiv3/wechatpay-apache-httpclient
得如何加载和使用这个公钥呢
X509Certificate publicKey = PemUtil.loadCertificate(new ClassPathResource(merchantId + "/pub_key.pem").getInputStream());
Verifier verifier = new CertificatesVerifier(Collections.singletonList(publicKey));
为了帮助商户规避未能及时完成平台证书更换或更换过程中出现系统风险影响线上业务,新申请的微信支付商户号需要使用公私钥模式进行接口验签,针对微信支付公钥使用介绍可参考:https://pay.weixin.qq.com/docs/merchant/products/platform-certificate/wxp-pub-key-guide.html
用https://search.maven.org/artifact/com.github.wechatpay-apiv3/wechatpay-java
// 可以根据实际情况使用publicKeyFromPath或publicKey加载公钥 Config config = new RSAPublicKeyConfig.Builder() .merchantId(merchantId) .privateKeyFromPath(privateKeyPath) .publicKeyFromPath(publicKeyPath) .publicKeyId(publicKeyId) .merchantSerialNumber(merchantSerialNumber) .apiV3Key(apiV3Key) .build();
// 这是以前的使用方式
ClassPathResource classPathResource = new ClassPathResource(MerchantConfig.getV3KeyPath(merchantId));
PrivateKey privateKey = PemUtil.loadPrivateKey(classPathResource.getInputStream());
// 获取证书管理器实例
CertificatesManager certificatesManager = CertificatesManager.getInstance();
// 向证书管理器增加需要自动更新平台证书的商户信息
certificatesManager.putMerchant(
merchantId,
new WechatPay2Credentials(
merchantId, new PrivateKeySigner(merchantConfig.getSerialNumber(), privateKey)),
merchantConfig.getApiV3Key().getBytes(StandardCharsets.UTF_8));
// ... 若有多个商户号,可继续调用putMerchant添加商户信息
// 从证书管理器中获取verifier
Verifier verifier = certificatesManager.getVerifier(merchantId);
CloseableHttpClient builder = WechatPayHttpClientBuilder.create()
.withMerchant(merchantId, merchantConfig.getSerialNumber(), privateKey)
.withValidator(new WechatPay2Validator(verifier))
.build();
WxpayFeignService wxpayFeignService = Feign.builder()
.client(new ApacheHttpClient(builder))
.encoder(new SpringEncoder(messageConverters()))
.decoder(new SpringDecoder(messageConverters()))
.requestInterceptor(template -> template.header("Content-Type", "application/json; charset=utf-8"))
.logLevel(loggerLevel)
.logger(new Slf4jLogger(WxpayFeignService.class))
.contract(new SpringMvcContract())
.target(WxpayFeignService.class, "https://api.mch.weixin.qq.com");
PublicKey publicKey = PemUtil.loadCertificate(new ClassPathResource(merchantId + "/pub_key.pem").getInputStream());
Verifier verifier = new CertificatesVerifier(Collections.singletonList(publicKey));
.withMerchant(merchantId, merchantConfig.getSerialNumber(), privateKey)