wechatpay-apache-httpclient完全指南:10分钟上手微信支付APIv3开发

wechatpay-apache-httpclient完全指南:10分钟上手微信支付APIv3开发

【免费下载链接】wechatpay-apache-httpclient微信支付 APIv3 Apache HttpClient装饰器(decorator)项目地址: https://gitcode.com/gh_mirrors/we/wechatpay-apache-httpclient

wechatpay-apache-httpclient是微信支付APIv3的Apache HttpClient扩展,实现了请求签名的生成和应答签名的验证。如果你是使用Apache HttpClient的商户开发者,可以使用它构造HttpClient,自动携带身份认证信息并检查应答的微信支付签名,快速实现微信支付功能。

📋 准备工作:环境与依赖

环境要求

  • Java 1.8+

快速安装

最新版本已在Maven Central发布,你可以通过以下方式引入依赖:

Gradle

build.gradle文件中加入:

implementation 'com.github.wechatpay-apiv3:wechatpay-apache-httpclient:0.5.0'
Maven

pom.xml中加入:

<dependency> <groupId>com.github.wechatpay-apiv3</groupId> <artifactId>wechatpay-apache-httpclient</artifactId> <version>0.5.0</version> </dependency>

🔑 核心概念:关键名词解释

在开始开发前,需要了解以下核心概念:

  • 商户API证书:证实商户身份,包含商户号、证书序列号等信息,由CA签发。
  • 商户API私钥:申请商户API证书时生成,保存在本地apiclient_key.pem文件中,需妥善保管。
  • 微信支付平台证书:微信支付提供的包含公钥信息的证书,用于验证应答签名。
  • 证书序列号:CA颁发的证书唯一编号。
  • API v3密钥:用于AES-256-GCM加密的对称密钥,在商户平台设置。

🚀 快速上手:3步构建HttpClient

第1步:获取必要参数

准备以下参数:

  • merchantId:商户号
  • merchantSerialNumber:商户API证书序列号
  • merchantPrivateKey:商户API私钥(可通过PemUtil.loadPrivateKey()加载)
  • wechatPayCertificates:微信支付平台证书列表(或使用定时更新功能)

第2步:构建WechatPayHttpClient

使用WechatPayHttpClientBuilder替换原生HttpClientBuilder

import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder; // 构建HttpClient WechatPayHttpClientBuilder builder = WechatPayHttpClientBuilder.create() .withMerchant(merchantId, merchantSerialNumber, merchantPrivateKey) .withWechatPay(wechatPayCertificates); // 可继续设置其他参数(如超时时间、连接池等) CloseableHttpClient httpClient = builder.build();

第3步:发送支付请求

使用构建好的httpClient发送请求,自动处理签名和验签:

// 示例:JSAPI下单 HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi"); httpPost.addHeader("Accept", "application/json"); httpPost.addHeader("Content-type", "application/json; charset=utf-8"); // 构造请求体(使用Jackson示例) ObjectMapper objectMapper = new ObjectMapper(); ObjectNode rootNode = objectMapper.createObjectNode(); rootNode.put("mchid", "1900009191") .put("appid", "wxd678efh567hg6787") .put("description", "Image形象店-深圳腾大-QQ公仔") .put("notify_url", "https://www.weixin.qq.com/wxpay/pay.php") .put("out_trade_no", "1217752501201407033233368018"); rootNode.putObject("amount").put("total", 1); rootNode.putObject("payer").put("openid", "oUpF8uMuAJO_M2pxb1Q9zNjWeS6o"); httpPost.setEntity(new StringEntity(objectMapper.writeValueAsString(rootNode), "UTF-8")); // 发送请求并获取响应 CloseableHttpResponse response = httpClient.execute(httpPost); String bodyAsString = EntityUtils.toString(response.getEntity()); System.out.println(bodyAsString);

⚡ 高级功能:提升开发效率

定时更新平台证书

版本≥0.4.0支持自动更新平台证书,无需手动维护:

// 获取证书管理器实例 CertificatesManager certificatesManager = CertificatesManager.getInstance(); // 添加商户信息 certificatesManager.putMerchant(merchantId, new WechatPay2Credentials(merchantId, new PrivateKeySigner(merchantSerialNumber, merchantPrivateKey)), apiV3Key.getBytes(StandardCharsets.UTF_8)); // 获取自动更新的验签器 Verifier verifier = certificatesManager.getVerifier(merchantId); // 构建HttpClient时使用该验签器 WechatPayHttpClientBuilder builder = WechatPayHttpClientBuilder.create() .withMerchant(merchantId, merchantSerialNumber, merchantPrivateKey) .withValidator(new WechatPay2Validator(verifier));

回调通知处理

版本≥0.4.2提供NotificationHandler处理回调通知的验签与解密:

// 构建回调请求 NotificationRequest request = new NotificationRequest.Builder() .withSerialNumber(wechatPaySerial) .withNonce(nonce) .withTimestamp(timestamp) .withSignature(signature) .withBody(body) .build(); // 处理回调 NotificationHandler handler = new NotificationHandler(verifier, apiV3Key.getBytes(StandardCharsets.UTF_8)); Notification notification = handler.parse(request); System.out.println("解密后数据:" + notification.getDecryptData());

图片/视频上传

使用WechatPayUploadHttpPost简化媒体文件上传:

String filePath = "/your/home/hellokitty.png"; URI uri = new URI("https://api.mch.weixin.qq.com/v3/merchant/media/upload"); File file = new File(filePath); try (FileInputStream ins1 = new FileInputStream(file)) { String sha256 = DigestUtils.sha256Hex(ins1); try (InputStream ins2 = new FileInputStream(file)) { HttpPost request = new WechatPayUploadHttpPost.Builder(uri) .withImage(file.getName(), sha256, ins2) .build(); CloseableHttpResponse response = httpClient.execute(request); } }

❓ 常见问题解决

如何加载商户私钥?

使用PemUtil.loadPrivateKey()方法:

// 从文件加载 PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(new FileInputStream("/path/to/apiclient_key.pem")); // 从字符串加载 PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(new ByteArrayInputStream(privateKey.getBytes("utf-8")));

如何下载平台证书?

首次使用时可临时跳过验签下载证书:

CloseableHttpClient httpClient = WechatPayHttpClientBuilder.create() .withMerchant(merchantId, merchantSerialNumber, merchantPrivateKey) .withValidator(response -> true) // 仅用于首次下载证书,业务请求需验证签名 .build();

依赖冲突解决

若出现JacksonNoSuchMethodError,可引入Jackson BOM统一版本:

// Gradle implementation(platform("com.fasterxml.jackson:jackson-bom:2.13.2.20220328"))
<!-- Maven --> <parent> <groupId>com.fasterxml.jackson</groupId> <artifactId>jackson-bom</artifactId> <version>2.13.2.20220328</version> </parent>

📚 更多资源

  • 完整示例代码:AutoUpdateVerifierTest.uploadImageTest
  • 回调处理示例:NotificationHandlerTest
  • 升级指南:UPGRADING.md

通过wechatpay-apache-httpclient,开发者可以快速集成微信支付APIv3,减少签名验签等繁琐工作,专注于业务逻辑开发。立即尝试,10分钟开启微信支付开发之旅!

【免费下载链接】wechatpay-apache-httpclient微信支付 APIv3 Apache HttpClient装饰器(decorator)项目地址: https://gitcode.com/gh_mirrors/we/wechatpay-apache-httpclient

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考