From 2c57405e9731250331ac57216a8509947391b13f Mon Sep 17 00:00:00 2001 From: Anyon Date: Thu, 19 Apr 2018 15:00:44 +0800 Subject: [PATCH] =?UTF-8?q?[=E6=9B=B4=E6=96=B0]=E5=BE=AE=E4=BF=A1=E5=B0=8F?= =?UTF-8?q?=E7=A8=8B=E5=BA=8F=E5=A2=9E=E5=8A=A0=E7=99=BB=E5=BD=95=E8=A7=A3?= =?UTF-8?q?=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- WeMini/Crypt.php | 40 ++++++++++++++++++++++++++++++++- WeMini/crypt/wxBizDataCrypt.php | 2 +- 2 files changed, 40 insertions(+), 2 deletions(-) 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"; } /**