若干年前接过微信和支付宝,当时微信还是xml,接完以后当时就觉着微信的接口弄的烂的一批,,,。最近又有接入微信支付,相比之前好了一点吧,但是感觉微信还是弄的太散乱了。
以下内容仅为减少代码的重复劳动,并不提供接入流程、字段、配置说明,开始前请明确已经阅读过微信支付文档,了解接入流程,并获取了秘钥证书相关内容
包含的接口有,jsapi下单、小程序调起支付加签、回调数据处理、微信支付平台证书更新。功能包括数据加验签,加解密
代码中注意使用官方类库,以保证资金安全。当前为2021年8月,时间久远内容可能出现差异,注意识别
maven引入微信支付sdk
<dependency>
<groupId>com.github.wechatpay-apiv3</groupId>
<artifactId>wechatpay-apache-httpclient</artifactId>
<version>0.2.2</version>
</dependency>
aes解密方法(AesUtil)直接复制官方示例
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个字节");
}
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);
}
}
}
参数配置类
public class WeiXinProties {
@Getter
private static final String APP_ID = "微信小程序APPID";
@Getter
private static final String MERC_ID = "微信支付商户号";
@Getter
private static final String SECRET = "微信小程序安全码";
@Getter
private static final String SERIAL_NO = "微信支付证书编号";
@Getter
private static final String PRIVATE_KEY = "微信支付证书私钥,就是下载的apiclient_key.pem内容,去掉头尾换行";
@Getter
private static final String NOTIFY_URL = "支付结果回调地址";
@Getter
private static final String WEIXINPAY_URL = "https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi";//微信jsapi下单地址
@Getter
private static final String APIV3_KEY = "apiv3秘钥";
@Getter
private static final String API_KEY = "api秘钥,新版本v3接口好像没用";