You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
< ? php
class WeiXin
{
/**
* 检验数据的真实性,并且获取解密后的明文.
* @param $encryptedData string 加密的用户数据
* @param $iv string 与用户数据一同返回的初始向量
* @param $data string 解密后的原文
*
* @return int 成功0, 失败返回对应的错误码
*/
public static function decryptData ( $encryptedData , $iv , $code , & $data )
{
$res = self :: codeLogin ( $code );
if ( ! isset ( $res [ 'session_key' ])) return $res ;
$sessionKey = $res [ 'session_key' ];
if ( strlen ( $sessionKey ) != 24 ) return 2 ;
$aesKey = base64_decode ( $sessionKey );
if ( strlen ( $iv ) != 24 ) return 3 ;
$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 4 ;
if ( $dataObj -> watermark -> appid != env ( 'WX_APP_ID' )) return 5 ;
$data = $result ;
return true ;
}
public static function codeLogin ( $code )
{
$url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . env ( 'WX_APP_ID' ) . '&secret=' . env ( 'WX_APP_SECRET' ) . '&js_code=' . $code . '&grant_type=authorization_code' ;
$info = file_get_contents ( $url );
$json = json_decode ( $info );
return get_object_vars ( $json );
}
}