wesmiler пре 2 месеци
родитељ
комит
2a8555853d
2 измењених фајлова са 114 додато и 84 уклоњено
  1. 7 0
      app/Services/Api/MemberService.php
  2. 107 84
      app/Services/MpService.php

+ 7 - 0
app/Services/Api/MemberService.php

@@ -166,6 +166,7 @@ class MemberService extends BaseService
         $openid = isset($userInfo['openid']) ? $userInfo['openid'] : '';
         $unionid = isset($userInfo['unionid']) ? $userInfo['unionid'] : '';
         $sessionKey = isset($userInfo['session_key']) ? $userInfo['session_key'] : '';
+        $accessToken = isset($userInfo['access_token']) ? $userInfo['access_token'] : '';
         if (empty($userInfo)) {
             $this->error = MpService::make()->getError();
             return false;
@@ -185,6 +186,12 @@ class MemberService extends BaseService
             $unionid = isset($loginInfo['unionid'])? $loginInfo['unionid'] : '';
         }
 
+        // 公众号获取用户信息
+        if($platform == 'wechat' && $accessToken){
+            $loginInfo = MpService::make()->getWechatUserInfo($accessToken, $openid);
+            var_dump($loginInfo);
+        }
+
         // 验证是否注册,没有则注册
         $where = ['openid' => $openid];
         // 关联账号

+ 107 - 84
app/Services/MpService.php

@@ -24,19 +24,21 @@ class MpService extends BaseService
     // 接口地址
     protected $apiUrls = [
         // 小程序授权登录
-        'auth'=> 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code',
+        'auth' => 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code',
         // 网页版授权
-        'authorize'=>'https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_userinfo&state=%s#wechat_redirect',
+        'authorize' => 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_userinfo&state=%s#wechat_redirect',
         // 获取token
-        'getToken'=>'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s',
+        'getToken' => 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s',
         // 获取二维码
-        'getQrcode'=>'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=%s&scene=%s&page=%s&env_version=%s',
+        'getQrcode' => 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=%s&scene=%s&page=%s&env_version=%s',
         // 获取用户信息
-        'getUserInfo'=>'https://api.weixin.qq.com/sns/jscode2session',
+        'getUserInfo' => 'https://api.weixin.qq.com/sns/jscode2session',
         // 获取公众号accessToken和openid
-        'getWechatAccessToken'=>'https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code',
+        'getWechatAccessToken' => 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code',
+        // 公众号用户信息
+        'getWechatUserInfo' => 'https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN',
         // 获取手机号
-        'getPhoneNumber'=>'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=%s',
+        'getPhoneNumber' => 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=%s',
     ];
 
 
@@ -66,47 +68,47 @@ class MpService extends BaseService
      * @param false $refresh
      * @return false|mixed|string
      */
-    public function getAccessToken($refresh = false, $platform='mp')
+    public function getAccessToken($refresh = false, $platform = 'mp')
     {
         try {
             $appId = $this->mpAppid;
             $appSecret = $this->mpAppSecret;
-            if ($platform == 'wechat'){
+            if ($platform == 'wechat') {
                 $appId = $this->wechatAppid;
                 $appSecret = $this->wechatAppSecret;
-                if(empty($this->wechatAppid) || empty($this->wechatAppSecret)){
+                if (empty($this->wechatAppid) || empty($this->wechatAppSecret)) {
                     $this->error = '公众号参数未配置';
                     return false;
                 }
-            }else{
-                if(empty($this->mpAppid) || empty($this->mpAppSecret)){
+            } else {
+                if (empty($this->mpAppid) || empty($this->mpAppSecret)) {
                     $this->error = '小程序参数未配置';
                     return false;
                 }
             }
 
             $cacheKey = "caches:mpApp:{$platform}_{$appId}:";
-            $tokenData = RedisService::get($cacheKey.'access_token');
-            $token = isset($tokenData['access_token'])? $tokenData['access_token'] : '';
-            if($token && !$refresh){
+            $tokenData = RedisService::get($cacheKey . 'access_token');
+            $token = isset($tokenData['access_token']) ? $tokenData['access_token'] : '';
+            if ($token && !$refresh) {
                 return $token;
             }
 
             $url = sprintf($this->apiUrls["getToken"], $appId, $appSecret);
-            $result = httpRequest($url,'', 'get','',5);
-            $this->saveLog($cacheKey.'tokens:request', ['url'=>$url,'result'=>$result,'date'=>date('Y-m-d H:i:s')]);
-            $token = isset($result['access_token'])? $result['access_token'] : '';
-            if(empty($result) || empty($token)){
+            $result = httpRequest($url, '', 'get', '', 5);
+            $this->saveLog($cacheKey . 'tokens:request', ['url' => $url, 'result' => $result, 'date' => date('Y-m-d H:i:s')]);
+            $token = isset($result['access_token']) ? $result['access_token'] : '';
+            if (empty($result) || empty($token)) {
                 $this->error = '获取TOKEN失败';
                 return false;
             }
 
             $result['date'] = date('Y-m-d H:i:s');
-            RedisService::set($cacheKey.'access_token', $result, 7000);
+            RedisService::set($cacheKey . 'access_token', $result, 7000);
             return $token;
-        }catch (\Exception $e){
+        } catch (\Exception $e) {
             $this->error = $e->getMessage();
-            $this->saveLog($cacheKey.'tokens:error', ['error'=>$this->error,'trace'=>$e->getTrace(),'date'=>date('Y-m-d H:i:s')]);
+            $this->saveLog($cacheKey . 'tokens:error', ['error' => $this->error, 'trace' => $e->getTrace(), 'date' => date('Y-m-d H:i:s')]);
             return false;
         }
     }
@@ -120,78 +122,77 @@ class MpService extends BaseService
      * @param false $refresh
      * @return false|string
      */
-    public function getMiniQrcode($page, $scene, $version='release', $refresh=false)
+    public function getMiniQrcode($page, $scene, $version = 'release', $refresh = false)
     {
-        if (!in_array($version,['release','trial','develop'])) {
-            $version='release';
+        if (!in_array($version, ['release', 'trial', 'develop'])) {
+            $version = 'release';
         }
 
         try {
-            if(empty($page) || empty($scene)){
+            if (empty($page) || empty($scene)) {
                 $this->error = '缺少二维码参数';
                 return false;
             }
 
-            if(empty($this->mpAppid) || empty($this->mpAppSecret)){
+            if (empty($this->mpAppid) || empty($this->mpAppSecret)) {
                 $this->error = '小程序参数未配置';
                 return false;
             }
 
-            if(!$token = $this->getAccessToken())
-            {
+            if (!$token = $this->getAccessToken()) {
                 $this->error = '获取token失败';
                 return false;
             }
 
             $cacheKey = "caches:members:mp_{$this->mpAppid}:";
             $filePath = base_path('public/uploads');
-            $qrFile = '/qrcodes/mp_'.date("YmdHis")."_".md5($page.$scene).".png";
-            $qrKey = md5(date("Ym").$page.$scene);
-            if(RedisService::get($cacheKey.$qrKey) && file_exists($filePath.'/'.$qrFile) && !$refresh){
+            $qrFile = '/qrcodes/mp_' . date("YmdHis") . "_" . md5($page . $scene) . ".png";
+            $qrKey = md5(date("Ym") . $page . $scene);
+            if (RedisService::get($cacheKey . $qrKey) && file_exists($filePath . '/' . $qrFile) && !$refresh) {
                 return $qrFile;
             }
 
-            if(!is_dir($filePath.'/qrcodes/')){
-                @mkdirs($filePath.'/qrcodes/');
+            if (!is_dir($filePath . '/qrcodes/')) {
+                @mkdirs($filePath . '/qrcodes/');
             }
 
-            $data=['page' => $page,'scene'=>$scene,'check_path'=>false,'env_version'=>$version];
+            $data = ['page' => $page, 'scene' => $scene, 'check_path' => false, 'env_version' => $version];
             $url = sprintf($this->apiUrls['getQrcode'], $token, $scene, $page, $version);
             $result = curl_post($url, json_encode($data));
-            $datas = $result? json_decode($result, true) : [];
-            $this->saveLog($cacheKey.'qrcode:request', ['page'=>$page,'scene'=>$scene,'url'=>$url,'result'=>$result,'date'=>date('Y-m-d H:i:s')]);
-            $errcode = isset($datas['errcode'])? $datas['errcode'] : '';
-            $errmsg = isset($datas['errmsg'])? $datas['errmsg'] : '';
-            if($errcode){
-                $this->error = $errmsg? $errmsg : '获取二维码失败';
+            $datas = $result ? json_decode($result, true) : [];
+            $this->saveLog($cacheKey . 'qrcode:request', ['page' => $page, 'scene' => $scene, 'url' => $url, 'result' => $result, 'date' => date('Y-m-d H:i:s')]);
+            $errcode = isset($datas['errcode']) ? $datas['errcode'] : '';
+            $errmsg = isset($datas['errmsg']) ? $datas['errmsg'] : '';
+            if ($errcode) {
+                $this->error = $errmsg ? $errmsg : '获取二维码失败';
                 return false;
             }
 
-            file_put_contents($filePath.'/'.$qrFile, $result);
-            if(!file_exists($filePath.'/'.$qrFile)){
+            file_put_contents($filePath . '/' . $qrFile, $result);
+            if (!file_exists($filePath . '/' . $qrFile)) {
                 $this->error = '生成二维码失败';
                 return false;
             }
 
-            RedisService::set($cacheKey.$qrKey, ['page'=>$page,'scene'=>$scene,'qrcode'=>$qrFile,'date'=>date('Y-m-d H:i:s')], 30 * 86400);
+            RedisService::set($cacheKey . $qrKey, ['page' => $page, 'scene' => $scene, 'qrcode' => $qrFile, 'date' => date('Y-m-d H:i:s')], 30 * 86400);
             return $qrFile;
-        }catch (\Exception $e){
+        } catch (\Exception $e) {
             $this->error = $e->getMessage();
-            $this->saveLog($cacheKey.'qrcode:error', ['page'=>$page,'scene'=>$scene,'error'=>$this->error,'trace'=>$e->getTrace(),'date'=>date('Y-m-d H:i:s')]);
+            $this->saveLog($cacheKey . 'qrcode:error', ['page' => $page, 'scene' => $scene, 'error' => $this->error, 'trace' => $e->getTrace(), 'date' => date('Y-m-d H:i:s')]);
             return false;
         }
     }
 
     /**
-     * 获取用户信息
+     * 获取授权信息
      * @param $code
      * @param $platform mp-小程序,wechat-公众号
      * @return array|false|mixed|string[]
      */
-    public function getUserinfo($code,$platform='mp')
+    public function getUserinfo($code, $platform = 'mp')
     {
         try {
-            if(empty($code)){
+            if (empty($code)) {
                 $this->error = '缺少授权参数';
                 return false;
             }
@@ -200,39 +201,64 @@ class MpService extends BaseService
             $appSecret = $this->mpAppSecret;
             $cacheKey = "caches:mpApp:{$platform}_{$appId}:";
             $data = '';
-            if ($platform == 'wechat'){
+            if ($platform == 'wechat') {
                 $appId = $this->wechatAppid;
                 $appSecret = $this->wechatAppSecret;
-                if(empty($this->wechatAppid) || empty($this->wechatAppSecret)){
+                if (empty($this->wechatAppid) || empty($this->wechatAppSecret)) {
                     $this->error = '公众号参数未配置';
                     return false;
                 }
-                $url = sprintf($this->apiUrls['getWechatAccessToken'], $appId,$appSecret,$code);
-            }else{
-                if(empty($this->mpAppid) || empty($this->mpAppSecret)){
+                $url = sprintf($this->apiUrls['getWechatAccessToken'], $appId, $appSecret, $code);
+            } else {
+                if (empty($this->mpAppid) || empty($this->mpAppSecret)) {
                     $this->error = '小程序参数未配置';
                     return false;
                 }
 
-                $data=[
+                $data = [
                     'appid' => $appId,
-                    'secret'=> $appSecret,
-                    'js_code'=>$code,
-                    'grant_type'=>'authorization_code'
+                    'secret' => $appSecret,
+                    'js_code' => $code,
+                    'grant_type' => 'authorization_code'
                 ];
                 $url = $this->apiUrls['getUserInfo'];
             }
 
-            $result = httpRequest($url, $data,'get','',5);
-            $this->saveLog($cacheKey.'userInfo:request', ['code'=>$code,'url'=>$url,'query'=>$data,'result'=>$result,'date'=>date('Y-m-d H:i:s')]);
-            if(empty($result)){
+            $result = httpRequest($url, $data, 'get', '', 5);
+            $this->saveLog($cacheKey . 'userInfo:request', ['code' => $code, 'url' => $url, 'query' => $data, 'result' => $result, 'date' => date('Y-m-d H:i:s')]);
+            if (empty($result)) {
                 $this->error = '获取用户信息失败';
                 return false;
             }
             return $result;
-        }catch (\Exception $e){
+        } catch (\Exception $e) {
             $this->error = $e->getMessage();
-            $this->saveLog($cacheKey.'userInfo:error', ['code'=>$code,'error'=>$this->error,'trace'=>$e->getTrace(),'date'=>date('Y-m-d H:i:s')]);
+            $this->saveLog($cacheKey . 'userInfo:error', ['code' => $code, 'error' => $this->error, 'trace' => $e->getTrace(), 'date' => date('Y-m-d H:i:s')]);
+            return false;
+        }
+    }
+
+    /**
+     * 公众号用户信息
+     * @param $accessToken
+     * @param $openid
+     * @return array|false|mixed|string[]
+     */
+    public function getWechatUserInfo($accessToken, $openid)
+    {
+        try {
+            $cacheKey = "caches:mpApp:wechat_{$openid}:";
+            $url = sprintf($this->apiUrls['getWechatAccessToken'], $accessToken, $openid);
+            $result = httpRequest($url, '', 'get', '', 5);
+            $this->saveLog($cacheKey . 'wechatUserInfo:request', ['openid' => $openid, 'access_token' => $accessToken, 'url' => $url, 'result' => $result, 'date' => date('Y-m-d H:i:s')]);
+            if (empty($result)) {
+                $this->error = '获取用户信息失败';
+                return false;
+            }
+            return $result;
+        } catch (\Exception $e) {
+            $this->error = $e->getMessage();
+            $this->saveLog($cacheKey . 'userInfo:error', ['openid' => $openid, 'access_token' => $accessToken, 'error' => $this->error, 'trace' => $e->getTrace(), 'date' => date('Y-m-d H:i:s')]);
             return false;
         }
     }
@@ -245,34 +271,33 @@ class MpService extends BaseService
     public function getPhoneNumber($code)
     {
         try {
-            if(empty($code)){
+            if (empty($code)) {
                 $this->error = '缺少授权参数';
                 return false;
             }
 
-            if(empty($this->mpAppid) || empty($this->mpAppSecret)){
+            if (empty($this->mpAppid) || empty($this->mpAppSecret)) {
                 $this->error = '小程序参数未配置';
                 return false;
             }
 
-            if(!$token = $this->getAccessToken())
-            {
+            if (!$token = $this->getAccessToken()) {
                 $this->error = '获取token失败';
                 return false;
             }
 
             $cacheKey = "caches:mpApp:mp_{$this->mpAppid}:";
             $url = sprintf($this->apiUrls['getPhoneNumber'], $token);
-            $result = httpRequest($url, json_encode(['code'=>$code],256),'post','',5);
-            $this->saveLog($cacheKey.'phone:request', ['code'=>$code,'url'=>$url,'result'=>$result,'date'=>date('Y-m-d H:i:s')]);
-            if(empty($result)){
+            $result = httpRequest($url, json_encode(['code' => $code], 256), 'post', '', 5);
+            $this->saveLog($cacheKey . 'phone:request', ['code' => $code, 'url' => $url, 'result' => $result, 'date' => date('Y-m-d H:i:s')]);
+            if (empty($result)) {
                 $this->error = '获取用户手机号失败';
                 return false;
             }
             return $result;
-        }catch (\Exception $e){
+        } catch (\Exception $e) {
             $this->error = $e->getMessage();
-            $this->saveLog($cacheKey.'phone:error', ['code'=>$code,'error'=>$this->error,'trace'=>$e->getTrace(),'date'=>date('Y-m-d H:i:s')]);
+            $this->saveLog($cacheKey . 'phone:error', ['code' => $code, 'error' => $this->error, 'trace' => $e->getTrace(), 'date' => date('Y-m-d H:i:s')]);
             return false;
         }
     }
@@ -292,24 +317,22 @@ class MpService extends BaseService
             return false;
         }
 
-        $aesKey=base64_decode($sessionKey);
+        $aesKey = base64_decode($sessionKey);
         if (strlen($iv) != 24) {
             $this->error = -41002;
             return false;
         }
-        $aesIV=base64_decode($iv);
+        $aesIV = base64_decode($iv);
 
-        $aesCipher=base64_decode($encryptedData);
+        $aesCipher = base64_decode($encryptedData);
 
-        $result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
-        $dataObj=json_decode( $result);
-        if( $dataObj  == NULL )
-        {
+        $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
+        $dataObj = json_decode($result);
+        if ($dataObj == NULL) {
             $this->error = -41003;
             return false;
         }
-        if( $dataObj->watermark->appid !=  $this->mpAppid)
-        {
+        if ($dataObj->watermark->appid != $this->mpAppid) {
             $this->error = -41003;
             return false;
         }
@@ -325,10 +348,10 @@ class MpService extends BaseService
      * @param $data
      * @param $time
      */
-    public function saveLog($cackekey, $data, $time=0)
+    public function saveLog($cackekey, $data, $time = 0)
     {
-        if($this->debug){
-            RedisService::set($cackekey, $data, $time?$time : $this->expireTime);
+        if ($this->debug) {
+            RedisService::set($cackekey, $data, $time ? $time : $this->expireTime);
         }
     }