微信退款的回调中有个字段是req_info。该字段微信官方给的解密方法是:
解密步骤如下:
(1)对加密串A做base64解码,得到加密串B
(2)对商户key做md5,得到32位小写key* ( key设置路径:微信商户平台(pay.weixin.qq.com)-->账户设置-->API安全-->密钥设置 )
(3)用key*对加密串B做AES-256-ECB解密(PKCS7Padding)
解密方法如下:
1 <?php 2 /** 3 * 微信退款回调参数解密类 4 * User Demo 5 * Data 2018-07-18 6 */ 7 namespace App\Services\Payment\wxpay; 8 use Exception; 9 10 class WxEncrypt { 11 12 //解密秘钥,默认应该为用户的秘钥key 13 private $key = ''; 14 15 //加密的串 16 private $encStr = ""; 17 18 19 public function __construct($str, $key) { 20 21 if (empty($str) || empty($key)) { 22 throw new Exception('解密参数错误!'); 23 } 24 $this->encStr = base64_decode($str); 25 $this->key = md5($key); 26 } 27 28 /** 29 * 获取解密的串 30 */ 31 public function getDecStr() { 32 return $this->decrypt($this->encStr); 33 } 34 35 /** 36 * 对密文进行解密 37 * @param string $encrypted 需要解密的密文 38 * @return string 解密得到的明文 39 */ 40 public function decrypt($encrypted) 41 { 42 $str = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $this->key, $this->encStr, MCRYPT_MODE_ECB); 43 $block = mcrypt_get_block_size('rijndael_128', 'ecb'); 44 $pad = ord($str[($len = strlen($str)) - 1]); 45 $len = strlen($str); 46 $pad = ord($str[$len - 1]); 47 return substr($str, 0, strlen($str) - $pad); 48 } 49 50 /** 51 * xml 转换成数组 52 * @param string $xml 53 * @return array 54 */ 55 function xmlToArray($xml) 56 { 57 $xmlObj = simplexml_load_string( 58 $xml, 59 'SimpleXMLIterator', //可迭代对象 60 LIBXML_NOCDATA 61 ); 62 63 $arr = []; 64 $xmlObj->rewind(); //指针指向第一个元素 65 while (1) { 66 if( ! is_object($xmlObj->current()) ) 67 { 68 break; 69 } 70 $arr[$xmlObj->key()] = $xmlObj->current()->__toString(); 71 $xmlObj->next(); //指向下一个元素 72 } 73 74 return $arr; 75 } 76 77 }
使用方法如下:
use App\Services\Payment\wxpay\WxEncrypt;
$obj = new WxEncrypt($req_info, $mch_key);//传入的第一个参数是req_info,第二个参数是商户key
$dec_xml = $obj->getDecStr();//此处获取的就是解密后的xml.
$dec_arr = $obj->xmlToArray($dec_xml); //此处获取的是xml解析成的数组。
此处需要注意的是使用该解密类需要php中有mcrypt加密模块
原文:https://blog.csdn.net/eaglejiawo1120/article/details/81106746
浙公网安备 33010602011771号