










微信支付api v3服務(wù)商開發(fā)接口文檔參數(shù)解密說明確實(shí)寫得不清楚,官方的介紹是:
1、用商戶平臺上設(shè)置的APIv3密鑰【微信商戶平臺—>賬戶設(shè)置—>API安全—>設(shè)置APIv3密鑰】,記為key;
2、針對resource.algorithm中描述的算法(目前為AEAD_AES_256_GCM),取得對應(yīng)的參數(shù)nonce和associated_data;
3、使用key、nonce和associated_data,對數(shù)據(jù)密文resource.ciphertext進(jìn)行解密,得到JSON形式的資源對象;
注: AEAD_AES_256_GCM算法的接口細(xì)節(jié),請參考rfc5116。微信支付使用的密鑰key長度為32個字節(jié),隨機(jī)串nonce長度12個字節(jié),associated_data長度小于16個字節(jié)并可能為空字符串。
這里的rfc5116參考:https://datatracker.ietf.org/doc/html/rfc5116
然取到三個參數(shù)基本不知如何去解,在百度查了很久,基本找不到什么相關(guān)信息,好在最后還是在一個開源文檔里找到了接口,現(xiàn)分享出來,也供大家作為參考:
首先建個文檔wxapire.php,內(nèi)容如下:
<?php
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,長度應(yīng)為32個字節(jié)');
}
$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');
}
}
?>
在通知頁引用類頁,如下代碼:
<?php
require('wxapire.php');
$data_array=json_decode((new AesUtil($key))->decryptToString($associated_data,$nonce,$ciphertext),true);
//參數(shù)說明:$key=》apiv3密鑰,$associated_data,$nonce,$ciphertext這三個是按返回來的字段信息,可以按名稱對應(yīng)即可
//$data_array就是解密后的數(shù)組,大家可以跟據(jù)實(shí)際情況使用到場景中
?>
實(shí)際界面效果:
首先生成支付二維碼
支付后,后端接收到通知,改變訂單狀態(tài)
生成的二維碼付款頁間隔幾秒就去分析是否訂單狀態(tài),如改變就提示,如下圖:
至此微信支付服務(wù)商開發(fā)api v3 "Native支付"支付和通知的業(yè)務(wù)場景完成。