微信支付接入
ztj100 2025-08-01 22:14 4 浏览 0 评论
商户平台产品中心配置
开发配置
- 开通JSAPI支付、Native支付
- JSAPI支付授权目录(前端项目域名)
- Native支付回调链接
appid账号配置
这一步,完成商户与微信公众号关联
账户中心配置
- 申请api证书
- 设置apiV3秘钥
微信公众号配置
微信支付配置
商户平台关联完公众号,在公众号平台,微信支付页面,需要点击确认,完成关联操作。
微信支付关键数据清单
名称 | 说明 |
appid | 公众账号ID |
mch_no | 商户号 |
mch_api_cert | 商户api证书 |
mch_api_private_key | 商户api私钥 |
mch_api_cert_serial_no | 商户api证书序号 |
wx_platform_cert | 微信支付平台证书 |
wx_platform_cert_serial_no | 微信支付平台证书序号 |
wx_platform_private_key | 微信支付平台私钥 |
api_v3_key | APIv3密钥 |
微信平台证书获取
postman调用
https://api.mch.weixin.qq.com/v3/certificates?,获取证书
解密证书密文
package com.insuresmart.claim.postback;
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;
private final byte[] aesKey;
public AesUtil(byte[] key) {
if (key.length != KEY_LENGTH_BYTE) {
throw new IllegalArgumentException("无效的ApiV3Key,长度必须为32个字节");
}
//密钥为apiv3密钥
this.aesKey = key;
}
public 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);
}
}
}
商户api证书VS微信平台证书
微信支付需要用到两种证书,商户api证书和微信平台证书,当时做接入的时候,懵逼。。。。微信的接入文档当时没看明白,不知道两者的作用是什么。
后面看了这个文档
https://pay.weixin.qq.com/wiki/doc/apiv3/wechatpay/wechatpay4_0.shtml,整明白了。
商户api证书,用作签名
微信支付API v3 要求商户对请求进行签名。微信支付会在收到请求后进行签名的验证。如果签名验证不通过,微信支付API v3将会拒绝处理请求,并返回401 Unauthorized
商户api证书中包含了签名所需要的私钥和商户证书,如何签名,参考 签名生成,或者使用微信提供的sdk
wechatpay-apache-httpclient
微信平台证书,验签
微信平台证书,对微信应答签名的验签。
如果验证商户的请求签名正确,微信支付会在应答的HTTP头部中包括应答签名。我们建议商户验证应答签名。
同样的,微信支付会在回调的HTTP头部中包括回调报文的签名。商户必须 验证回调的签名,以确保回调是由微信支付发送。
apiv3-key 用作解密
微信支付签名工具类
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import org.springframework.util.Base64Utils;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.security.*;
/**
* @author:shixianqing
* @Date:2021/8/17 17:36
* @Description:
**/
public class SignUtils {
/**
* @param signStr 签名字符串
* @param privateKeyStr 商户证书私钥
*/
public static String createSign(String signStr, String privateKeyStr) throws InvalidKeyException,
NoSuchAlgorithmException,
SignatureException {
PrivateKey privateKey = PemUtil.loadPrivateKey(new ByteArrayInputStream(privateKeyStr
.getBytes(StandardCharsets.UTF_8)));
Signature sign = Signature.getInstance("SHA256withRSA");
sign.initSign(privateKey);
sign.update(signStr.getBytes(StandardCharsets.UTF_8));
return Base64Utils.encodeToString(sign.sign());
}
}
微信支付验签
public class WechatVerifyServiceImpl implements WechatVerifyService {
/**
* 验签
* @param wxPlatformCert 微信支付平台证书
* @param request
* @param requestBody 请求报文体
* @return
*/
@Override
public boolean verify(String wxPlatformCert, HttpServletRequest request, String requestBody) {
String timestamp = request.getHeader("Wechatpay-Timestamp");
String nonce = request.getHeader("Wechatpay-Nonce");
String serial = request.getHeader("Wechatpay-Serial");
String signature = request.getHeader("Wechatpay-Signature");
log.info("支付通知,验签开始,timestamp:{},nonce:{},serial:{},signature:{}",timestamp,nonce,serial,signature);
// 验签处理器
Verifier verifier = WechatVerifierUtils.getVerifier(wxPlatformCert);
String body = requestBody;
String beforeSign = String.format("%s\n%s\n%s\n",
timestamp,
nonce,
body);
return verifier.verify(serial,beforeSign.getBytes(StandardCharsets.UTF_8),signature);
}
}
public class WechatVerifierUtils {
public static Verifier getVerifier(String wxPlatformCert){
X509Certificate wechatPayPlatformCertificate = PemUtil.loadCertificate(
new ByteArrayInputStream(wxPlatformCert.getBytes(StandardCharsets.UTF_8)));
ArrayList<X509Certificate> wxPlatformCertList = new ArrayList<>();
wxPlatformCertList.add(wechatPayPlatformCertificate);
Verifier certificatesVerifier = new CertificatesVerifier(wxPlatformCertList);
return certificatesVerifier;
}
}
微信支付解密
package com.insuresmart.base.pay.common.util;
import com.google.common.base.CharMatcher;
import com.google.common.io.BaseEncoding;
import com.insuresmart.base.common.utils.StringUtils;
import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
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 java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
public class AesUtils {
static final int KEY_LENGTH_BYTE = 32;
static final int TAG_LENGTH_BIT = 128;
private final byte[] aesKey;
public AesUtils(byte[] key) {
if (key.length != KEY_LENGTH_BYTE) {
throw new IllegalArgumentException("无效的ApiV3Key,长度必须为32个字节");
}
// apiv3私钥
this.aesKey = key;
}
public static byte[] decryptToByte(byte[] nonce, byte[] cipherData, byte[] key)
throws GeneralSecurityException {
return decryptToByte(null, nonce, cipherData, key);
}
public static byte[] decryptToByte(byte[] associatedData, byte[] nonce, byte[] cipherData, byte[] key)
throws GeneralSecurityException {
try {
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
GCMParameterSpec spec = new GCMParameterSpec(TAG_LENGTH_BIT, nonce);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, spec);
if (associatedData != null) {
cipher.updateAAD(associatedData);
}
return cipher.doFinal(cipherData);
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
throw new IllegalStateException(e);
} catch (InvalidKeyException | InvalidAlgorithmParameterException e) {
throw new IllegalArgumentException(e);
}
}
public 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(BaseEncoding.base64().decode(CharMatcher.whitespace().removeFrom(ciphertext))), "utf-8");
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
throw new IllegalStateException(e);
} catch (InvalidKeyException | InvalidAlgorithmParameterException e) {
throw new IllegalArgumentException(e);
}
}
public static String decryptToString(String associatedData, String nonce, String ciphertext,String apiV3Key)
throws GeneralSecurityException, IOException {
try {
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
SecretKeySpec key = new SecretKeySpec(apiV3Key.getBytes(), "AES");
GCMParameterSpec spec = new GCMParameterSpec(TAG_LENGTH_BIT, nonce.getBytes());
cipher.init(Cipher.DECRYPT_MODE, key, spec);
associatedData = StringUtils.isNotBlank(associatedData) ? associatedData : "";
cipher.updateAAD(associatedData.getBytes());
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);
}
}
public static String HMACSHA256(String data, String key) {
try {
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
sha256_HMAC.init(secret_key);
byte[] array = sha256_HMAC.doFinal(data.getBytes("UTF-8"));
StringBuilder sb = new StringBuilder();
for (byte item : array) {
sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
}
return sb.toString().toUpperCase();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
附录
微信接入规范地址
https://pay.weixin.qq.com/wiki/doc/apiv3/wechatpay/wechatpay3_1.shtml
微信支付接口文档地址
https://pay.weixin.qq.com/wiki/doc/apiv3/wechatpay/wechatpay3_1.shtml
相关推荐
- Java的SPI机制详解
-
作者:京东物流杨苇苇1.SPI简介SPI(ServiceProvicerInterface)是Java语言提供的一种接口发现机制,用来实现接口和接口实现的解耦。简单来说,就是系统只需要定义接口规...
- 一文读懂 Spring Boot 启动原理,开发效率飙升!
-
在当今的Java开发领域,SpringBoot无疑是最热门的框架之一。它以其“约定大于配置”的理念,让开发者能够快速搭建和启动应用,极大地提高了开发效率。但是,你是否真正了解Spring...
- ServiceLoader
-
ServiceLoader是Java提供的一种服务发现机制(ServiceProviderInterface,SPI)...
- 深入探索 Spring Boot3 中的自定义扩展操作
-
在当今互联网软件开发领域,SpringBoot无疑是最受欢迎的框架之一。随着其版本迭代至SpringBoot3,它为开发者们带来了更多强大的功能和特性,其中自定义扩展操作更是为我们在项目开发中...
- Spring Boot启动过程全面解析:从入门到精通
-
一、SpringBoot概述SpringBoot是一个基于Spring框架的快速开发脚手架,它通过"约定优于配置"的原则简化了Spring应用的初始搭建和开发过程。...
- Spring Boot 3.x 自定义 Starter 详解
-
今天星期六,继续卷springboot3.x。在SpringBoot3.x中,自定义Starter是封装和共享通用功能、实现“约定优于配置”理念的强大机制。通过创建自己的Starte...
- Spring Boot 的 3 种动态 Bean 注入技巧
-
在SpringBoot开发中,动态注入Bean是一种强大的技术,它允许我们根据特定条件或运行时环境灵活地创建和管理Bean。相比于传统的静态Bean定义,动态注入提供了更高的灵活性和可...
- 大佬用4000字带你彻底理解SpringBoot的运行原理!
-
SpringBoot的运行原理从前面创建的SpringBoot应用示例中可以看到,启动一个SpringBoot工程都是从SpringApplication.run()方法开始的。这个方法具体完成...
- Springboot是如何实现自动配置的
-
SpringBoot的自动配置功能极大地简化了基于Spring的应用程序的配置过程。它能够根据类路径中的依赖和配置文件中的属性,自动配置应用程序。下面是SpringBoot实现自动配置的...
- Spring Boot3.x 应用的生命周期深度解析
-
SpringBoot应用的生命周期可以清晰地划分为三个主要阶段:启动阶段(Startup)...
- Springboot 启动流程及各类事件生命周期那点事
-
前言本文通过Springboot启动方法分析SpringApplication逻辑。从静态run方法执行到各个阶段发布不同事件完成整个应用启动。...
- Spring框架基础知识-常用的接口1
-
BeanDefinition基本概念BeanDefinition是Spring框架中描述bean配置信息的核心接口,它包含了创建bean实例所需的所有元数据。...
- Java 技术岗面试全景备战!从基础到架构的系统性通关攻略分享
-
Java技术岗的面试往往是一项多维度的能力检验。本文将会从核心知识点、项目经验到面试策略,为你梳理一份系统性的备战攻略!...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- idea eval reset (50)
- vue dispatch (70)
- update canceled (42)
- order by asc (53)
- spring gateway (67)
- 简单代码编程 贪吃蛇 (40)
- transforms.resize (33)
- redisson trylock (35)
- 卸载node (35)
- np.reshape (33)
- torch.arange (34)
- npm 源 (35)
- vue3 deep (35)
- win10 ssh (35)
- vue foreach (34)
- idea设置编码为utf8 (35)
- vue 数组添加元素 (34)
- std find (34)
- tablefield注解用途 (35)
- python str转json (34)
- java websocket客户端 (34)
- tensor.view (34)
- java jackson (34)
- vmware17pro最新密钥 (34)
- mysql单表最大数据量 (35)