基于Vue的單頁應用的微信網頁授權登錄解決思路

微信公眾號的微信授權登錄,為我們快速導入用戶流量提供了極大的便利,我們會選擇在發布在微信端的頁面中,優先使用微信授權登錄,在這次的項目過程中,我們是這樣解決微信的網頁授權的——

解決思路

代碼

  • main.js 配置路由前置操作
router.beforeEach((to, from, next) => {
  if (to.path === '/author' && store.state.userInfo.userId) {
    next('/near');
    return false
  }
  if (!(store.state.userInfo.userId) && to.path !== '/author') {
    store.state.toUrl = to.fullPath;
    next('/author');
  }
  if (store.state.userInfo.userId) {
    next();
    return false
  }
  next();
});
  • author.vue 授權中間件
mounted(){
 if (this.$store.state.toUrl){
          cooike.set('toUrl',this.$store.state.toUrl)
        }
        if (cooike.get('openid') === null){
            if (this.$route.query.openid){
              this.openid = this.$route.query.openid;
              cooike.set('openid',this.openid,5);
              console.log(this.openid);
            }else{
             window.location.href = '********************';//去后端授權頁面
            }
        } else{
          this.openid = cooike.get('openid');
        }
this.$ajax({
          method:'POST',
          url:getToken,
          data:qs.stringify({
            openid:this.openid
          }),
        }).then((resp)=>{
          if (resp.data.errcode==='200'){
              console.log(resp.data.data);
            this.$vux.toast.show({
              text:'授權成功',
              time:1000,
            });
            console.log(resp.data.data.token);
            this.$store.state.token=resp.data.data.token;
            console.log(this.$store.state.token);
            this.$store.state.userInfo.userId=resp.data.data.userInfo.userId;
            this.$store.state.userInfo.nickName=resp.data.data.userInfo.nickName;
            this.$store.state.userInfo.headImg=resp.data.data.userInfo.headImg;
            this.$store.state.userInfo.growthValue=resp.data.data.userInfo.growthValue;
            this.$router.replace(cooike.get('toUrl'));
          }else{
            cooike.delete('openid');
            this.$vux.toast.show({
              text:'已經重置,請重新進入',
              time:2000,
              type:"text",
              position:"bottom"
            })

          }
        });
}
  • 后端授權方法
public function auth(){
        $url = $this->_getUrl();
        //echo $url;
        if(!$_GET['code']){
            \LaneWeChat\Core\WeChatOAuth::getCode($url,1,'snsapi_userinfo');
        }
        if($_GET['code']){
            $code = $_GET['code'];
            $arr = \LaneWeChat\Core\WeChatOAuth::getAccessTokenAndOpenId($code);
            $openid = $arr['openid'];
            $access_token = $arr['access_token'];
            $UserModel = M('User');
            $where['openId']=$openid;
            $has = $UserModel ->where($where) ->find();
            $oUtil = new \Base\Controller\UtilController();
            if ($has){
                $token = $oUtil->createToken($has['userid']);
            }else{
                $userInfo = \LaneWeChat\Core\WeChatOAuth::getUserInfo($access_token,$openid);
                $userId = $oUtil->newUserFromWechat($userInfo);
                if ($userId!= null){
                    $token = $oUtil->createToken($userId);
                }else{
                    echo "UnknowError";
                }
            }
            $url = "http://*********/#/author?openid=".$openid;
            header('Location: '.$url, true, 301);
        }
    }
    private function _getUrl() {
        $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
        $php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
        $path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
        $relate_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $php_self.(isset($_SERVER['QUERY_STRING']) ? '?'.$_SERVER['QUERY_STRING'] : $path_info);
        return $sys_protocal.(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '').$relate_url;
    }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,948評論 18 139
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,368評論 25 708
  • 今天是我跟心理咨詢師的第五次交流,一個多小時的談話后,我忍不住想要把所學所思記錄下來。在自我探尋的路上跌跌撞撞走了...
    清晰無言閱讀 572評論 1 0
  • 如果不用面對,或許就不用傷心。 我換了微信頁面,改了簽名。 換了指甲的顏色,腳后跟紋了一根羽毛。 我告訴自己,一切...
    會飛的千鳥閱讀 165評論 0 0
  • 射線:3D世界中一個點向一個方向發射的一天無終點的線,在發射軌跡中魚其他物體發生碰撞時,他將停止發射。注意:這條線...
    IT白鴿閱讀 465評論 0 0