微信公衆平臺實現受權登陸(不是微信開放平臺)

今天給你們補充一下微信受權登陸的實現方式。如標題,是公衆平臺的實現方式,官方推薦的是微信開放平臺,但因審覈問題,我只拿到了微信開放平臺的app_id和app_secret。因此作了這一版,僅供參考javascript

第一步:php

去微信公衆平臺開通一個微信服務號,地址 https://mp.weixin.qq.com/。審覈經過以後,默認就會有獲取的用戶信息的接口權限,這沒必要擔憂,總之拿到對應的app_id和app_secret就能夠。java

 

第二步:jquery

用戶點擊微信登陸的時候,跳轉到本身的一個靜態頁面,裏面有着一張登陸二維碼(本身經過php生成,不懂能夠百度),二維碼地址是:https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$app_id."&redirect_uri=".urlencode($my_url)."&response_type=code&scope=snsapi_userinfo&state=".$auth_code."#wechat_redirect。裏面的參數本身的便可。web

 

代碼以下:ajax

 

    $my_url = "http://".$_SERVER['HTTP_HOST']."/Home/User/wechatLogin?ip=".$_SERVER['REMOTE_ADDR']; //成功受權後的回調地址
    //
第一步:用戶贊成受權,獲取code $code = $_REQUEST["code"];//存放code $auth_code = md5(uniqid(rand(), TRUE)); //隨機生成字符串,防止csrf(目前並不生效) if(empty($code)){ $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$app_id."&redirect_uri=".urlencode($my_url)."&response_type=code&scope=snsapi_userinfo&state=".$auth_code."#wechat_redirect"; $src = qrcode($url, time().".png", "", "./logo.png", 3); //我調用的一個本身封裝的二維碼生成函數 $this->assign("src", substr($src, 1))->display();  //將他輸出到視圖,就是上圖     }

 

第三步:json

這個時候用戶掃碼,實際上是手機訪問了這個頁面(上一步中本身設置的$my_url),可是對於拿到數據與入庫並不影響。api

$url1="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$app_id."&secret=".$app_secret."&code=".$code."&grant_type=authorization_code";
            $res = file_get_contents($url1);//調用SDK方法獲取到res 從中能夠獲得openid
            $res = (json_decode($res, true));//轉換成array 方便調用openid

            //第三步:拉取用戶信息(需scope爲 snsapi_userinfo)
            if(isset($res['access_token'])){
                $url2 = "https://api.weixin.qq.com/sns/userinfo?access_token=".$res['access_token']."&openid=".$res['openid']."&lang=zh_CN";
                $row = file_get_contents($url2);
                $user_data = (json_decode($row, true));

                $m = M("Member");
                $data = array();
                $data['sex']              = $user_data['sex'];
                $data['province']      = $user_data['province'];
                $data['city']             = $user_data['city'];
                $data['person_name']   = $user_data['nickname'];
                $data['wx_number']     = $_REQUEST['ip'];
                $data['wx_openid']     = $user_data['openid'];
                $data['wx_name']       = $user_data['nickname'];
                $data['wx_img']        = $user_data['headimgurl'];
                $data['addtime']       = date("Y-m-d H:i:s", time());
                $data['person_img']       = $user_data['headimgurl'];
                $data['signtime']       = date("Y-m-d H:i:s", time());

                $user = $m->where(array("wx_openid"=> $user_data['openid']))->find();
                if($user){
                    $res = $m->where(array("wx_openid"=> $user_data['openid']))->setField(array("signtime"=> date("Y-m-d H:i:s", time()), "wx_number"=> $_REQUEST['ip']));
                    if($res){
                        $this->display("wechatWap");
                    }else{
                        $this->error("操做異常,拒絕訪問!", U('user/login'));
                    }
                }else{
                    $res=$m->add($data);

                    if($res){
                        $this->display("wechatWap");
                    }else{
                        $this->error("操做異常,拒絕訪問!", U('user/login'));
                    }
                }
            }

 

第四步:微信

這個時候數據已經在手機端的訪問中入庫,可是網頁端並不知道,這個時候須要網頁端作一個輪詢(若是想性能好,能夠用websokect來實現,這裏不作過多介紹)來判斷是否有新的數據入庫,若是有則取出數據,登陸成功!app

靜態頁面代碼以下:

<script src="__JS__/jquery-1.9.1.min.js" type="text/javascript"></script>
<body>
<style>
body{ background:#333;}
.headright{ position:relative; color:#fff;}
.headright a{ color:#fff;}
</style>
<include file="Public:menu_u"/>
<div class="wx_qrcode">
<dl>
<dt><img src="{$src}" /></dt>
<dd>微信掃描二維碼登陸<br>
「帝格珠寶」</dd>
</dl>
</div>
<!--<include file="Public:foot_u"/>-->
</body>

<script>
ajaxSearch();
function ajaxSearch(){
    $.post("{:U('/Home/User/wechatLogin')}", "", function(data){

        if(data.status==1){
            location.href='{:U("/Home/User/wxSucLogin/user_id/'+data.user_id+'")}';

        }else{
            setTimeout(function(){
                ajaxSearch();
            },5000)
        }
    })
}
</script>

php代碼以下:

//經過當前客戶端的ip地址發送ajax輪詢是否登陸成功
        if(IS_AJAX){
            $user = M("Member")->where(array("wx_number"=> $_SERVER['REMOTE_ADDR']))->select();
            if($user){
                foreach($user as $key=>$val){
                    $timer = time() - strtotime($val['signtime']);
                    if($timer < 10){

                        $this->ajaxReturn(array("info"=> "登陸成功!", "status"=> 1, "user_id"=> $val['id']));
                    }
                }

                $this->ajaxReturn(array("info"=> "暫無登陸信息!", "status"=> 0));
            }else{
                $this->ajaxReturn(array("info"=> "暫無登陸信息!", "status"=> 0));
            }
        }

這裏有一個問題,若是同時有多個用戶都在使用微信登陸,那怎麼判斷錄入進去的數據是那一個用戶掃碼登陸的呢?這裏能夠用客戶端ip來作標識區別開來。

在最開始第二步$my_url定義的時候加上客戶端ip做爲參數帶過去就能夠了。而後第三步獲取到ip錄入到數據中,這樣即可以區分開。

相關文章
相關標籤/搜索