PHP记录微信小程序解密失败

app.js 这里生成了一个code 传到后台是第一次的code 以及解密的sessionkey
index.js 中又一次生成code 第二次覆盖了第一次的记录

!!!!!在回调中调用 wx.login 登录,可能会刷新登录态。此时服务器使用 code 换取的 sessionKey 不是加密时使用的 sessionKey,导致解密失败。建议开发者提前进行 login;或者在回调中先使用 checkSession 进行登录态检查,避免 login 刷新登录态。!!!!

<?php
//PHP解密代码
$appid = 'wx4f4bc4dec97d474b';
$sessionKey = 'tiihtNczf5v6AKRyjwEUhQ==';
$encryptedData="CiyLU1Aw2KjvrjMdj8YKliAjtP4gsMZM
                QmRzooG2xrDcvSnxIMXFufNstNGTyaGS
                9uT5geRa0W4oTOb1WT7fJlAC+oNPdbB+
                3hVbJSRgv+4lGOETKUQz6OYStslQ142d
                NCuabNPGBzlooOmB231qMM85d2/fV6Ch
                evvXvQP8Hkue1poOFtnEtpyxVLW1zAo6
                /1Xx1COxFvrc2d7UL/lmHInNlxuacJXw
                u0fjpXfz/YqYzBIBzD6WUfTIF9GRHpOn
                /Hz7saL8xz+W//FRAUid1OksQaQx4CMs
                8LOddcQhULW4ucetDf96JcR3g0gfRK4P
                C7E/r7Z6xNrXd2UIeorGj5Ef7b1pJAYB
                6Y5anaHqZ9J6nKEBvB4DnNLIVWSgARns
                /8wR2SiRS7MNACwTyrGvt9ts8p12PKFd
                lqYTopNHR1Vf7XjfhQlVsAJdNiKdYmYV
                oKlaRv85IfVunYzO0IKXsyl7JCUjCpoG
                20f0a04COwfneQAGGwd5oa+T8yO5hzuy
                Db/XcxxmK01EpqOyuxINew==";

$iv = 'r7BXXKkLb8qrSNn05n0qiA==';

$pc = new WXBizDataCrypt($appid, $sessionKey);
$errCode = $pc->decryptData($encryptedData, $iv, $data );

if ($errCode == 0) {
    print($data . "\n");
} else {
    print($errCode . "\n");
}

//解密类
class WXBizDataCrypt {
     private $appid;
     private $sessionKey;
public function __construct( $appid, $sessionKey) {
    $this->sessionKey = $sessionKey;
    $this->appid = $appid;
}
public function decryptData( $encryptedData, $iv, &$data ) {
    if (strlen($this->sessionKey) != 24) {
        return ErrorCode::$IllegalAesKey;
    }
    $aesKey=base64_decode($this->sessionKey);
    if (strlen($iv) != 24) {
        return ErrorCode::$IllegalIv;
    }
    $aesIV=base64_decode($iv);
    $aesCipher=base64_decode($encryptedData);
    $result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
    $dataObj=json_decode( $result );
    if( $dataObj  == NULL )
    {
        return ErrorCode::$IllegalBuffer;
    }
    if( $dataObj->watermark->appid != $this->appid )
    {
        return ErrorCode::$IllegalBuffer;
    }
    $data = $result;
    return ErrorCode::$OK;
}
//错误类
class ErrorCode {
	public static $OK = 0;
	public static $IllegalAesKey = -41001;
	public static $IllegalIv = -41002;
	public static $IllegalBuffer = -41003;
	public static $DecodeBase64Error = -41004;
}
点赞

发表评论