码迷,mamicode.com
首页 > 微信 > 详细

PHP之路——微信公众号授权获取用户信息

时间:2016-08-28 09:48:28      阅读:347      评论:0      收藏:0      [点我收藏+]

标签:

官方文档链接: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);

    }

 

 

PHP之路——微信公众号授权获取用户信息

标签:

原文地址:http://www.cnblogs.com/xj76149095/p/5814366.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!