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);

       }


 

猜你喜欢

转载自blog.csdn.net/Tingmmdh/article/details/81180782