1. 程式人生 > >PHP 微信授權登入獲取使用者資訊

PHP 微信授權登入獲取使用者資訊

//呼叫微信授權登入(微信公眾平臺)
        public function add_user(){
            //獲取微信公眾號的APPID
            $app_id  = '';

            //請求介面回撥地址
            $redirect_uri = urlencode("http://www.xxx.com/getUserInfo");
$url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$app_id."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
            header("location:".$url);
        }

        public function getUserInfo(){
            //通過code換取網頁授權access_token
            //獲取微信公眾號的APPID
            $app_id  = '';
            //獲取微信公眾號的祕鑰
            $app_secret = '';
            //獲取code
            $code = $_GET['code'];
            $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$app_id."&secret=".$app_secret."&code=".$code."&grant_type=authorization_code";
            // 3、如果需要,開發者可以重新整理網頁授權access_token,避免過期
            // 4、通過網頁授權access_token和openid獲取使用者基本資訊(支援UnionID機制)
            $res = file_get_contents($url);
            //將json轉為資料
            $res = json_decode($res,TRUE);

            //獲取TOKEN
            $token = $res['access_token'];
            //獲取使用者的openid
            $openid = $res['openid'];
            //拉取使用者的詳細資訊
            $url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$token."&openid=".$openid."&lang=zh_CN";

            $res = file_get_contents($url);
            //將json轉為資料
            $res = json_decode($res,TRUE);
        }

//微信登入(微信開發平臺)
        public function wechat_login(){
            //獲取微信公眾號的APPID
            $app_id  = '';
            $redirect_uri = urlencode("http://www.xxxxx.com/wechatGetUserInfo");
            $url = "https://open.weixin.qq.com/connect/qrconnect?appid=".$app_id."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_login&state=wechat_login"; 
            header("location:".$url);
        }

        //微信登入跳轉頁面
        public function wechatGetUserInfo(){
            //通過code換取網頁授權access_token
            //獲取微信公眾號的APPID
            $app_id  = '';


            //獲取微信公眾號的祕鑰
            $app_secret = '';

            //獲取code
            if(is_array($_GET) && count($_GET)>0){//先判斷是否通過get傳值了
                    if(isset($_GET["code"])){//是否存在"id"的引數
                        $code = $_GET["code"];//存在
                    }
            }else{
                echo "引數錯誤";
                die;
            }

            $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$app_id."&secret=".$app_secret."&code=".$code."&grant_type=authorization_code";
            // 3、如果需要,開發者可以重新整理網頁授權access_token,避免過期
            // 4、通過網頁授權access_token和openid獲取使用者基本資訊(支援UnionID機制)
            $res = file_get_contents($url);
            //將json轉為資料
            $res = json_decode($res,TRUE);

       }