<?php /** * Created by PhpStorm. * User: Administrator * Date: 2017/6/14 * Time: 10:29 * 解码获取微信unionID * 小程序端: * 1,wx.login 后获取code * 2 wx.getUserInfo({withCredentials:true})获得$encrptedData和$iv * 3 将$session_key $encrptedData $iv 传递到客户api服务器 * * 客户api服务器端 * 1 将本类设置为组件 * 2 code换session_key * https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code * 3 $wx = Yii::$app->WxBizDataCrypt * $wx->setData($session_key $encrptedData $iv) * $wx->decryptData() */ namespace backend\components\wx_decode; use Yii; use yii\base\Component; use yii\base\Exception; class WxBizDataCrypt extends Component { public $appid = 'wxaxxxxxxxxxxxxxxxxxxx' ; //public $session_key; public $aesKey ; public $aesIv ; public $aesCipher ; public static $error_code = [ 'ok' => 0, 'IllegalAesKey' => -41001, 'IllegalIv' => -41002, 'IllegalBuffer' => -41003, 'DecodeBase64Error' => -41004 ]; public function setData( $session_key , $encryptedData , $iv ){ if ( strlen ( $session_key ) != 24) { return static :: $error_code [ 'IllegalAesKey' ]; } $this ->aesKey = base64_decode ( $session_key ); if ( strlen ( $iv ) != 24) { return static :: $error_code [ 'IllegalIv' ]; } $this ->aesIv= base64_decode ( $iv ); $this ->aesCipher= base64_decode ( $encryptedData ); return true; } public function decryptData() { //$pc = new Prpcrypt($aesKey); $result = $this ->decrypt(); if ( $result [0] != 0) { return $result [0]; } $dataObj =json_decode( $result [1] ); if ( $dataObj == NULL ) { return static :: $error_code [ 'IllegalBuffer' ]; } if ( $dataObj ->watermark->appid != $this ->appid ) { return static :: $error_code [ 'IllegalBuffer' ]; } return $result [1]; } /** * 对密文进行解密 * @param string $aesCipher 需要解密的密文 * @param string $aesIV 解密的初始向量 * @return string 解密得到的明文 */ public function decrypt() { try { $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '' , MCRYPT_MODE_CBC, '' ); mcrypt_generic_init( $module , $this ->aesKey, $this ->aesIv); //解密 $decrypted = mdecrypt_generic( $module , $this ->aesCipher); mcrypt_generic_deinit( $module ); mcrypt_module_close( $module ); } catch (Exception $e ) { return array ( static :: $error_code [ 'IllegalBuffer' ], null); } try { //去除补位字符 //$pkc_encoder = new PKCS7Encoder; $result = $this ->decode( $decrypted ); } catch (Exception $e ) { //print $e; return array ( static :: $error_code [ 'IllegalBuffer' ], null); } return array (0, $result ); } /** * 对解密后的明文进行补位删除 * @param decrypted 解密后的明文 * @return 删除填充补位后的明文 */ public function decode( $text ) { $pad = ord( substr ( $text , -1)); if ( $pad < 1 || $pad > 32) { $pad = 0; } return substr ( $text , 0, ( strlen ( $text ) - $pad )); } } |