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

微信支付接入

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

商户平台产品中心配置

开发配置

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

相关推荐

蜗牛矿机改NAS后远程访问教程,花生壳盒子完美解决

今年不少烧友都在玩星际蜗牛的机器,,我也跟风入手一台,用星际蜗牛改装了一台NAS,在星际蜗牛上安装了多个版本的NAS系统,各方面都不错,就是远程访问功能实现不了。由于本地运营商不提供公网IP,就只能考...

不吹不黑,揭秘网工提升效率的7大神器!

作为一个网络工程师,在日常工作中肯定会使用许多方便的实用软件来提高效率,下面就简单介绍一下网络工程师常用的7种软件。01、FileZilla...

有线网间歇性断网?3个步骤帮你解决 90% 有线网中断问题

有线网络偶尔中断可能由硬件故障、网络设置、线路问题或外部干扰等多种因素导致。一、常见原因及验证方法1.硬件设备...

「这 25 年我被天气 PUA 的日常」

翻出手机相册里每年6月拍的天空,白到发亮的云层下总配着同一句文案:"热到裂开"。掐指一算被高温暴打的四分之一个世纪里,每个夏天都在上演《关于我和天气互相折磨的那些年》。2003年绝对...

数码爱好者必备工具:POWER-Z KM001C多功能测试仪

作为一名数码类爱好者,平时要测试手机、平板、充电器、充电宝等等电子产品,一款好用的测试工具尤为重要。近期,通过充电头网购入了一款POWER-ZKM001C多功能测试仪,主要用来平日里测试快充头和充电...

监控摄像头常用测试命令大全(摄像头测试项目)

以下是监控摄像头在Linux系统中常用的测试命令大全,涵盖设备检测、参数调整、视频录制、网络监控等方面,结合多个来源的信息整理而成:一、摄像头设备检测与调用1.查看摄像头设备①`ls/dev/v...

中级消防设施操作员考试-计算机基础知识学习笔记

消防设施操作员模块八计算机基础课程摘要消防设施操作员模块八主要介绍了计算机基础知识,包括计算机系统的组成和功能、硬件和软件、输入输出设备、外存储器、内存条、中央处理器、机箱等硬件部分,以及系统软件和应...

今日揭秘:上网行为监控软件是如何监控的?7个功能图文介绍

同事A:“哎,你们听说了吗?隔壁部门小王昨天上班刷短视频被领导抓包了!”同事B:“真的假的?公司不是没装摄像头吗?怎么知道的?”...

USB详细介绍(usb简介)

USB概念1.概念USB是通用串行总线(UniversalSerialBus),分为HOST/DEVICE两个角色,所有的数据传输都由主机主动发起,而设备只是被动的负责应答。例如,在读数据时,U...

程序员必备,Fiddler和spy-debugger的远程调试手机APP

背景笔者从事Web开发,不论是PC端还是APP端,调试抓包都是必不可少的环节,懂前端的人都知道,PC端调试非常方便,Chrome或者火狐等浏览器等都自带了非常方便且易于使用的开发者工具,便于我们抓包调...

通用无线网络破解抓包跑包教程(wifi抓包跑包教程)

由于很多的信号很强,但是后面都没有带WPS,怎么办呢,现在我给大家介绍一个简单的抓包跑字典的办法来解决这个难题,首先搜索信号,水滴,关注我的这个应该都会了吧!选择一个信号,点击启动,记住不是点...

抓包神器wireshark安装保姆级教程

简介当我们进行网络抓包时,我们通常需要借助其他的工具进行抓取,比如Charles,fiddler等,今天我们给大家介绍一款同样非常流行的抓包工具——wireshark,本文将介绍wireshark的安...

别让资料拖后腿!STM32开发‘作弊包’开源,工程师直呼内行!

一、开发环境与编译工具...

背完这套 Java 面试八股文,自动解锁面试牛逼症被动技能

前言国内的互联网面试,恐怕是现存的、最接近科举考试的制度。很多人对八股文都嗤之以鼻,认为无法衡量出一个程序员的真是水平。还有一部分人则是深恶痛绝,因为实在太难背了。但是国内大环境如此,互联网IT行...

混合云的多活架构指南(混合云架构图)

文/董晓聪吕亚霖在之前的《如何正确选择多云架构?》一文中介绍了混合云(广义的多云)的诸多架构以及各自的优势,本篇会重点来介绍下混合云下的多活架构。...