百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

微信支付接入

haoteby 2025-03-10 16:05 31 浏览

商户平台产品中心配置

开发配置

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

相关推荐

Chrome OS 41 用 Freon 取代 X11_chrome os atom

在刚发布的ChromeOS41里,除了常规的Wi-Fi稳定性提升(几乎所有系统的changelog里都会包含这一项)、访客模式壁纸等之外,还存在底层改变。这一更新中Google移除...

苹果iPad Pro再曝光 有望今年六月发布

自进入2015年以后,有关大屏iPad的消息便一直不绝于耳,之前就有不少媒体猜想这款全新的平板电脑将会在三月发布,不过可惜的是我么只在那次发布会上看到了MacBookPro。近日@Ubuntu团队便...

雷卯针对香橙派Orange Pi 5 Max开发板防雷防静电方案

一、应用场景高端平板、边缘计算、人工智能、云计算、AR/VR、智能安防、智能家居、Linux桌面计算机、Linux网络服务器、Android平板、Android游戏机...

Ubuntu Server无法更新问题解决_ubuntu server not found

上周老家的一台运行UbuntuServer的盒子无法连接上了,中秋这两天回来打开,顺手更新一下发现更新报错。提示`E:Releasefileforhttps://mirrors.aliyun...

虚幻引擎5正式版发布:古墓丽影&amp;巫师新作采用、新一代实时渲染

机器之心报道编辑:杜伟、陈萍虚幻引擎5的目标是「助力各种规模的团队在视觉领域和互动领域挑战极限,施展无限潜能」。...

AMD Milan-X双路霄龙7773X平台基准测试曝光 CPU缓存总量超1.5GB

OpenBenchmarking基准测试数据库刚刚曝光了AMDMilan-X双路霄龙7773X平台的跑分成绩,虽然很快就被撤下,但我们还是知晓了高达1.6GB的总CPU缓存。早些时...

ROS机器人建模_ros机器人硬件搭建

...

全网最新的Dify(1.7.2)私有化离线部署教程(ARM架构)

Hello,大家好!近期工作中有涉及到Dify私有化离线部署,特别是针对于一些国产设备。因此特别整理了该教程,实测有效!有需要的小伙伴可以参考下!本文主要针对Dify1.7.2最新版本+国产操作系...

在ubuntu下新建asp.net core项目_创建ubuntu

本文一步步讲述在ubuntu下用visualstudiocode创建asp.netcore项目的过程。step1:环境操作系统:virtualbox下安装的lubuntu。请不要开启“硬件...

在晶晨A311D2处理器上进行Linux硬件视频编码
在晶晨A311D2处理器上进行Linux硬件视频编码

在KhadasVIM4AmogicA311D2SBC上,我更多的时间是在使用Ubuntu22.04。它的总体性能还不错,只不过缺少3D图形加速和硬件视...

2025-08-26 17:22 haoteby

Nacos3.0重磅来袭!全面拥抱AI,单机及集群模式安装详细教程!

之前和大家分享过JDK17的多版本管理及详细安装过程,然后在项目升级完jdk17后又发现之前的注册和配置中心nacos又用不了,原因是之前的nacos1.3版本的,版本太老了,已经无法适配当前新的JD...

电影质量级渲染来了!虚幻引擎5.3正式发布:已开放下载

快科技9月8日消息,日前,Unrealengine正式发布了虚幻引擎5.3,带来了大量全方位的改进。...

2025如何选购办公电脑?极摩客mini主机英特尔系列选购指南

当下,迷你主机的性能越来越强,品类也越来越多。但是CPU是不变的,基本都是AMD和英特尔的。有一个小伙伴在评论区提问,我应该如何在众多机器中选购一台符合自己的迷你主机呢?那今天我们优先把我们的系列,分...

ubuntu 20.04+RTX4060 Ti+CUDA 11.7+cudnn

ububtu添加国内源sudocp/etc/apt/sources.list/etc/apt/sources.list.backupsudovim/etc/apt/sources.lis...

Linux Mint 18将重新基于Ubuntu 16.04 带来更好硬件支持

项目负责人ClementLefebvre在本月6日披露了关于LinuxMint18“Sarah”操作系统的大量信息,包括带来全新扁平化体验的Mint-Y主题。而现在,这款将于年底之前上线的操作...