diff --git a/WeMini/Crypt.php b/WeMini/Crypt.php index ece1b01..c593176 100644 --- a/WeMini/Crypt.php +++ b/WeMini/Crypt.php @@ -15,8 +15,10 @@ namespace WeMini; use WeChat\Contracts\BasicWeChat; +use WeChat\Contracts\Tools; +use WeChat\Exceptions\InvalidDecryptException; +use WeChat\Exceptions\InvalidResponseException; -require_once __DIR__ . DIRECTORY_SEPARATOR . 'crypt' . DIRECTORY_SEPARATOR . 'wxBizDataCrypt.php'; /** * 数据加密处理 @@ -35,6 +37,7 @@ class Crypt extends BasicWeChat */ public function decode($iv, $sessionKey, $encryptedData) { + require_once __DIR__ . DIRECTORY_SEPARATOR . 'crypt' . DIRECTORY_SEPARATOR . 'wxBizDataCrypt.php'; $pc = new \WXBizDataCrypt($this->config->get('appid'), $sessionKey); $errCode = $pc->decryptData($encryptedData, $iv, $data); if ($errCode == 0) { @@ -42,4 +45,39 @@ class Crypt extends BasicWeChat } return false; } + + /** + * 登录凭证校验 + * @param string $code 登录时获取的 code + * @return array + */ + public function session($code) + { + $appid = $this->config->get('appid'); + $secret = $this->config->get('appsecret'); + $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code"; + return json_decode(Tools::get($url), true); + } + + /** + * 换取用户信息 + * @param string $code 用户登录凭证(有效期五分钟) + * @param string $iv 加密算法的初始向量 + * @param string $encryptedData 加密数据( encryptedData ) + * @return array + * @throws InvalidDecryptException + * @throws InvalidResponseException + */ + public function userInfo($code, $iv, $encryptedData) + { + $result = $this->session($code); + if (empty($result['session_key'])) { + throw new InvalidResponseException('Code换取SessionKey失败', 403); + } + $userinfo = $this->decode($iv, $result['session_key'], $encryptedData); + if (empty($userinfo)) { + throw new InvalidDecryptException('用户信息解析失败', 403); + } + return array_merge($result, $userinfo); + } } \ No newline at end of file diff --git a/WeMini/crypt/wxBizDataCrypt.php b/WeMini/crypt/wxBizDataCrypt.php index d253e96..43769f2 100644 --- a/WeMini/crypt/wxBizDataCrypt.php +++ b/WeMini/crypt/wxBizDataCrypt.php @@ -6,7 +6,6 @@ * @copyright Copyright (c) 1998-2014 Tencent Inc. */ -include_once __DIR__ . DIRECTORY_SEPARATOR . "errorCode.php"; class WXBizDataCrypt { @@ -22,6 +21,7 @@ class WXBizDataCrypt { $this->appid = $appid; $this->sessionKey = $sessionKey; + include_once __DIR__ . DIRECTORY_SEPARATOR . "errorCode.php"; } /**