基於TP5的微信登陸基本邏輯

    /**
     * 微信H5登陸
     */
    public function weixin_login()
    {

        $ua = $_SERVER['HTTP_USER_AGENT'];
        //MicroMessenger 是android/iphone版微信所帶的
        //Windows Phone 是winphone版微信帶的  (這個標識會誤傷winphone普通瀏覽器的訪問)
        if(strpos($ua, 'MicroMessenger') == false && strpos($ua, 'Windows Phone') == false){
            //普通瀏覽器
            echo "<script>alert('請用微信客戶端訪問');</script>";
            $this->redirect('login');
            exit;
        }
        if(empty(session('h5_uid'))){
            if(empty($_GET['code'])){
                $this->getCode();
                exit;
            }
            $code=$_GET['code'];
            $this->getAccessToken($code);
        }
        //如果該微信用戶未綁定基礎信息,就去綁定基礎信息
        $info=Db::name('user')->where('id',session('h5_uid'))->find();

        if(empty($info['name'])){
            $this->redirect('register');
        }
        if(!empty($info['mobile'])){
            session('mobile',$info['mobile']);
        }
         //如果是購買會員VIP頁面過來的,則微信登陸後返回企業自畫像
        if(cookie('is_vip')==1){
            $this->redirect('Vip/index');
        }
        //如果是企業自畫像過來,則微信登陸後返回企業自畫像
        if(cookie('is_business')==1){
            $this->redirect('Business/index');
        }
        $this->redirect('Mp/my');
        exit;
    }

    /**
     *獲取code值
     *TODO::從哪裏來就跳轉回哪裏
     */
    public function getCode()
    {

        $redirect_uri=urlencode("http://".$_SERVER['HTTP_HOST']."/home/index/weixin_login");
        $response_type='code';
        $scope='snsapi_userinfo';
        $url= "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".config('sys.appid')."&redirect_uri=".$redirect_uri."&response_type=code&scope=".$scope."&state=login#wechat_redirect";
        header("location:$url"); 
    }

    /**
     * 根據code值獲取access_token,openid, 將refresh_token寫入session裏,或者不寫
     */
    public function getAccessToken($code)
    {
         $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".config('sys.appid')."&secret=".config('sys.appsecret')."&code=".$code."&grant_type=authorization_code";
        $result = curl_get($url);
        $wxResult = json_decode($result, true);  //轉換爲數組
        if(empty($wxResult)) {
            echo json_encode(['code'=>0,'status'=>false,'msg'=>'獲取access_token及openID時異常,微信內部錯誤']);
            exit();
        } else {
            $loginFail = array_key_exists('errcode', $wxResult);
            if ($loginFail) {

                echo json_encode($wxResult);
                // echo $this->processLoginError($wxResult);
                exit();
            } else {
                return $this->grantToken($wxResult);

            }
        }
    }

    private function grantToken($wxResult){
        $openid=$wxResult['openid'];
        $user=Db::name("user")->where('openid',$openid)->find();
        if(!empty($user)){
            $uid = $user['id'];
        }else{
            $uid = $this->newUser($openid);
        }

        $userInfo= $this->saveUserInfo($wxResult,$uid);
        // $cachedValue=$this->prepareCachedValue($wxResult,$uid);
        // $token=$this->saveToCache($cachedValue);
        // cookie('mobile',$user['phone']);
        session('h5_uid',$uid);
        session('openid',$openid);
        return true;
        // return $this->redirect('Mp/my');
    }


        /**
     * 保存用戶信息
     * 背景:拿到access_token和openid之後,進一步保存用戶信息
     * @param array()  $wxResult  示例:
     * @return  bool  or false  
     */
    private function saveUserInfo($wxResult,$uid)
    {
        $url="https://api.weixin.qq.com/sns/userinfo?access_token=".$wxResult['access_token']."&openid=".$wxResult['openid']."&lang=zh_CN";
        $res=curl_get($url);
        $wxRes=json_decode($res,true);
        unset($wxRes['privilege']);

        if(empty($wxRes)){
            Log::error('保存用戶信息失敗,微信服務器返回的數據爲空');
        }else{
            $loginFail = array_key_exists('errcode', $wxRes);
            if ($loginFail) {
                Log::error('請求信息出錯,無法保存用戶信息:'.$wxRes);
            }else{
                unset($wxRes['language']);
                $user = Db::name('user')->where('id',$uid)->update($wxRes);
            }
        }
        return $uid;
    }
    /*
     * 如果不存在openid  就插入數據庫中
     * */
    private function newUser($openid)
    {
        $id=Db::name("user")->insertGetId(['openid'=>$openid,'add_time'=>time()]);
        return $id;
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章