PHP之路——微信公眾號授權獲取用戶信息


官方文檔鏈接:http://mp.weixin.qq.com/wiki/4/9ac2e7b1f1d22e9e57260f6553822520.html

 

  /**
     * 獲取code
     */
    public function actionGetCode()
    {
        $response_type = 'code';
        $scope = 'snsapi_userinfo';
        $conf = yii::$app->params['oauth_conf']['oauth_wx_in'];
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?';
        $url .= 'appid='.$conf['app_id'];
        $url .= '&redirect_uri=' . urlencode($conf['redirect_uri']);
        $url .= '&response_type=code';
    //這是微信公眾號內獲取
        $url .= '&scope=snsapi_userinfo';
    //這是微信開放平台獲取
//        $url .= '&scope=snsapi_login';
        $url .= '&#wechat_redirect';

        header('Location:'.$url);
        
    }


    /**
     * 獲取access_token
     */
    public function actionGettoken()
    {
        $conf = yii::$app->params['oauth_conf']['oauth_wx_in'];
        $code = $_GET['code'];
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?';
        $url .= 'appid='.$conf['app_id'];
        $url .= '&secret='.$conf['app_key'];
        $url .= '&code='.$code;
        $url .= '&grant_type=authorization_code';

        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_HEADER,0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $data = curl_exec($ch);
        $data = json_decode($data,true);
        curl_close($ch);

        $access_token = $data['access_token'];
        $openid = $data['openid'];
        $get_user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';

        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$get_user_info_url);
        curl_setopt($ch,CURLOPT_HEADER,0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $res = curl_exec($ch);
        curl_close($ch);
    //返回的是一個數組,里面存放用戶的信息
        $res = json_decode($res,true);

    }

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM