微信支付接入

微信支付接入

精选文章moguli202025-04-23 14:49:1312A+A-

商户平台产品中心配置

开发配置

  • 开通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

点击这里复制本文地址 以上内容由莫古技术网整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!
qrcode

莫古技术网 © All Rights Reserved.  滇ICP备2024046894号-2