微信支付api v3获取平台证书

编辑于 2021-05-20 11:04:28 阅读 2708

GET 获取平台证书列表

https://api.mch.weixin.qq.com/v3/certificates

访问成功可得到类似数据

[
    {
        "effective_time": "2021-05-19T18:40:14+08:00",
        "encrypt_certificate": {
            "algorithm": "AEAD_AES_256_GCM",
            "associated_data": "certificate",
            "ciphertext": "...==",
            "nonce": "c20fb6175ecb"
        },
        "expire_time": "2026-05-18T18:40:14+08:00",
        "serial_no": "50E3553125B..."
    }
]

解密

$obj=new AesUtil('API v3密钥');//商户后台->账户中心->API安全->APIv3密钥
echo $obj->decryptToString('associated_data...', 'nonce...', 'ciphertext...').PHP_EOL;

将以上结果保存到wxp_cert.pem文件

然后获取公钥

openssl x509 -in wxp_cert.pem -pubkey -noout > wxp_pub.pem

附件

官方提供的解密工具类

class AesUtil{
  /**
    * AES key
    *
    * @var string
    */
  private $aesKey;

  const KEY_LENGTH_BYTE = 32;
  const AUTH_TAG_LENGTH_BYTE = 16;

  /**
    * Constructor
    */
  public function __construct($aesKey)
  {
      if (strlen($aesKey) != self::KEY_LENGTH_BYTE) {
          throw new InvalidArgumentException('无效的ApiV3Key,长度应为32个字节');
      }
      $this->aesKey = $aesKey;
  }

  /**
    * Decrypt AEAD_AES_256_GCM ciphertext
    *
    * @param string    $associatedData     AES GCM additional authentication data
    * @param string    $nonceStr           AES GCM nonce
    * @param string    $ciphertext         AES GCM cipher text
    *
    * @return string|bool      Decrypted string on success or FALSE on failure
    */
  public function decryptToString($associatedData, $nonceStr, $ciphertext)
  {
      $ciphertext = \base64_decode($ciphertext);
      if (strlen($ciphertext) <= self::AUTH_TAG_LENGTH_BYTE) {
          return false;
      }

      // ext-sodium (default installed on >= PHP 7.2)
      if (function_exists('\sodium_crypto_aead_aes256gcm_is_available') &&
          \sodium_crypto_aead_aes256gcm_is_available()) {
          return \sodium_crypto_aead_aes256gcm_decrypt($ciphertext, $associatedData, $nonceStr, $this->aesKey);
      }

      // ext-libsodium (need install libsodium-php 1.x via pecl)
      if (function_exists('\Sodium\crypto_aead_aes256gcm_is_available') &&
          \Sodium\crypto_aead_aes256gcm_is_available()) {
          return \Sodium\crypto_aead_aes256gcm_decrypt($ciphertext, $associatedData, $nonceStr, $this->aesKey);
      }

      // openssl (PHP >= 7.1 support AEAD)
      if (PHP_VERSION_ID >= 70100 && in_array('aes-256-gcm', \openssl_get_cipher_methods())) {
          $ctext = substr($ciphertext, 0, -self::AUTH_TAG_LENGTH_BYTE);
          $authTag = substr($ciphertext, -self::AUTH_TAG_LENGTH_BYTE);

          return \openssl_decrypt($ctext, 'aes-256-gcm', $this->aesKey, \OPENSSL_RAW_DATA, $nonceStr,
              $authTag, $associatedData);
      }

      throw new \RuntimeException('AEAD_AES_256_GCM需要PHP 7.1以上或者安装libsodium-php');
  }
}

广而告之,我的新作品《语音助手》上架Google Play了,欢迎下载体验