快乐每一天

自己选择的路,跪着也要走下去...

标签 H5 下的文章

微信H5授权登录获取用户信息

看完代码后,一定要注意末尾的两个注意事项,白名单跟网页授权域名的新增


<?php
/**
 * Created by PhpStorm.
 * User: 项羽
 * Date: 2019/1/28
 * Time: 10:31
 * QQ群:310325131
 */

namespace app\api\controller;


class Wxgetuserinfo
{
    /**
     * 1、获取用户信息
     */
    public function index(){
        $appid = config('appid');
        $secret = config('secret');
//        $fetch='/cc';
        /*TODO 检测是否关注公众号 直接调用 $this->checkisgz()*/
        $ret=array();

        if(!session('?userinfo')){
            if (!isset($_GET['code'])){//没有code,去微信接口获取code码
                $request = request();
                $callback = $request->url(true);//微信服务器回调url,这里是本页url
                /* $this->get_code($callback);*/
                /* 这个地方还是直接拿当前的方法走,不然部分手机调不起来授权登录。处理方法如下:*/
                $redirect_uri=urlencode($callback);
                $url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.$redirect_uri.'&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect';
                header("location:$url");exit();


            } else {//获取code后跳转回来到这里了
                $code = $_GET['code'];
                $data = $this->get_access_token($code);//获取网页授权access_token和用户openid
                $data_all = $this->get_user_info($data['access_token'],$data['openid']);//获取微信用户信息
                session('userinfo',$data_all);
                return json($data_all);
            }
        }else{
            $ret=session('userinfo');
            return json($ret);             //返回的获取到的微信用户信息
        }

        /*TODO 明信片二维码:B@     防伪码:C@   不参与兑换的明信片防伪码:A@ */
        /*$this->assign('retdata',$retdata);
        $this->assign('uniquecode',$uniquecode);
        $this->assign('userinfo',session('userinfo')['nickname']);
        return $this->fetch($fetch);*/
    }

    /**
     * 2、用户授权并获取code  这一步作废,上面直接调用
     * @param string $callback 微信服务器回调链接url
     */
    private function get_code($callback){
        $appid = config('appid');
        $scope = 'snsapi_userinfo';
        $state = md5(uniqid(rand(), TRUE));//唯一ID标识符绝对不会重复
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $appid . '&redirect_uri=' . urlencode($callback) .  '&response_type=code&scope=' . $scope . '&state=' . $state . '#wechat_redirect';
        header("Location:$url");
    }

    /**
     * 3、使用code换取access_token
     * @param string 用于换取access_token的code,微信提供
     * @return array access_token和用户openid数组
     */
    private function get_access_token($code){
        $appid = config('appid');
        $appsecret = config('secret');
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $appsecret . '&code=' . $code . '&grant_type=authorization_code';
        $user = json_decode(file_get_contents($url));
        if (isset($user->errcode)) {
            echo 'error:' . $user->errcode.'<hr>msg  :' . $user->errmsg;exit;
        }
        $data = json_decode(json_encode($user),true);//返回的json数组转换成array数组
//        error_log(time().'测试old'.print_r($data,true),3,dirname(__FILE__).'/error_log.php');
        return $data;
    }

    /**
     * 4、使用access_token获取用户信息
     * @param string access_token
     * @param string 用户的openid
     * @return array 用户信息数组
     */
    private function get_user_info($access_token,$openid){
        $url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN';
        $user = json_decode(file_get_contents($url));
        if (isset($user->errcode)) {
//            echo 'error:' . $user->errcode.'<hr>msg  :' . $user->errmsg;exit;
        }
        $data = json_decode(json_encode($user),true);//返回的json数组转换成array数组

        return $data;
    }



/*↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓*/
    /*检测是否关注公众号*/
    /*subscribe    用户是否订阅该公众号标识,值为0时,代表此用户没有关注该公众号,拉取不到其余信息。*/
    /*https://www.cnblogs.com/mracale/p/9318349.html*/
    public function checkisgz(){
        $request = request();
        $callback = $request->url(true);//微信服务器回调url,这里是本页url

        $appid = config('appid');
        $secret = config('secret');

//微信网页授权获取openid
        $web_url=$callback;

        if (!isset($_GET['code'])) {
            $redirect_uri=urlencode($web_url);
            $url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.$redirect_uri.'&response_type=code&scope=snsapi_base&state=1#wechat_redirect';
            header("location:$url");exit();
        }
        $code=trim($_GET['code']);
        $url='https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$secret.'&code='.$code.'&grant_type=authorization_code';
        $access=file_get_contents($url);
        $data=json_decode($access,true);
        $access_token=$data['access_token'];
        $url='https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid=OPENID&lang=zh_CN';
        $user=file_get_contents($url);
        $arr=json_decode($user,true);
//获取用户的openid
        $openid=$arr['openid'];

        $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
        $access=file_get_contents($url);
        $access_arr=json_decode($access,true);
//非网页的access_token
        $access_token=$access_arr['access_token'];

        $url="https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";
        $res=file_get_contents($url);
//        var_dump($res);
        return $res['subscribe'];
    }




}
注意事项如下所示
  1. 公众号白名单需要新增
  2. 网页授权回调地址需要添加

TIM截图20190128172733.png
2.png

阅读全文