首页 » PHP » 正文

微信支付-退款结果通知 req_info解密

【方法一】 助手类
class WxpayRefundNotifyHelper
{
private $app_key;

public function __construct($app_key)
{
$this->app_key = $app_key;
}

public function decryptMessage($message)
{
if (empty($this->app_key) || empty($message)) {
return null;
}

$strXml = $this->decrypt(
base64_decode($message, true), md5($this->app_key), ”, OPENSSL_RAW_DATA, ‘AES-256-ECB’
);

return $this->parse($strXml);
}

public static function parse($xml)
{
return self::normalize(simplexml_load_string($xml, ‘SimpleXMLElement’, LIBXML_COMPACT | LIBXML_NOCDATA | LIBXML_NOBLANKS));
}

protected static function normalize($obj)
{
$result = null;

if (is_object($obj)) {
$obj = (array) $obj;
}

if (is_array($obj)) {
foreach ($obj as $key => $value) {
$res = self::normalize($value);
if ((‘@attributes’ === $key) && ($key)) {
$result = $res; // @codeCoverageIgnore
} else {
$result[$key] = $res;
}
}
} else {
$result = $obj;
}

return $result;
}

public static function decrypt(string $data, string $password, string $iv, int $option = OPENSSL_RAW_DATA, $method = null): string
{
return openssl_decrypt($data, $method ?: self::getMode($password), $password, $option, $iv);
}

public static function getMode($key)
{
return ‘aes-‘.(8 * strlen($key)).’-cbc’;
}
}
使用例子:
$key = ”;//商户平台密钥
$objWXPay = new WxpayRefundNotifyHelper($key);
$result_params = $objWXPay->decryptMessage($arrXml[‘req_info’]);

=====================================================================================================================================================
【方法二】快速解密方法
function decrypt($encrypted, $key)
{
$data = base64_decode($encrypted,true);
$decrypted = openssl_decrypt($data, ‘AES-256-ECB’, md5($key), OPENSSL_RAW_DATA);
return xml2array($decrypted);
}
使用例子:
$key = ”;//商户平台密钥
$result_params = $this->decrypt($arrXml[‘req_info’], $key);

附:
function xml2array($strXml)
{
//禁止引用外部xml实体
libxml_disable_entity_loader(true);
$arrXml = json_decode(json_encode(simplexml_load_string($strXml, ‘SimpleXMLElement’, LIBXML_NOCDATA)), true);
return $arrXml;
}

发表评论