微信自定义菜单打开本地连接,并提示用户授权登录获取信息

微信自定义菜单打开本地连接,并提示用户授权登录获取信息,将微信用户与本地用户关系打通

网页端判断是否是微信浏览器浏览

<script>
    if(isWeixin()) {
       // alert('是微信浏览器');
        window.location.href = "{:url("/bindphone/getcode")}";
    }
function isWeixin () {
        var ua = window.navigator.userAgent.toLowerCase();
        if(ua.match(/MicroMessenger/i) == 'micromessenger' || ua.match(/_SQ_/i) == '_sq_'){
            return true;
        } else{
            return false;
        }
    }
</script>

  如果是微信客户端浏览网页则跳转到getcode方法中,进行提示用户授权操作,来获取用户openid 等信息

public function getcode()
    {
        $state = md5(uniqid(rand(), TRUE));
        $hdurl = urlencode("http://****.cn/bindphone/callback");
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . $this->appid . "&redirect_uri=" . $hdurl . "&response_type=code&scope=snsapi_userinfo&state=" . $state . "#wechat_redirect";
        $this->redirect($url); //此方法为跳转到页面方法,不是curl方法获取数据用
        die;
    }

上面拿到微信的code码,用户同意授权后,会跳转到红色 回调路径中去,

微信官方提示:

https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html

下图为scope等于snsapi_userinfo时的授权页面:

用户同意授权后

如果用户同意授权,页面将跳转至 redirect_uri/?code=CODE&state=STATE。

code说明 : code作为换取access_token的票据,每次用户授权带上的code将不一样,code只能使用一次,5分钟未被使用自动过期。

这样在callback方法中获取code码,然后在获取accetoken 即可

public function callback()
    {
        $param = request()->param();
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $this->appid . '&secret=' . $this->AppSecret . '&code=' . $param['code'] . '&grant_type=authorization_code';
        $arr = $this->http_curl($url);
        $openids = $arr['openid'];  这里就可以拿到用户openid 与accestoken等信息
        Cache::set($openids, $openids, 86400);
        //得到openid    后查询数据库看看是否有该纪录,如果有,直接登录,存好uid到session,如果没有,走绑定手机号步骤,进行完善或者注册
        $useinfo = Db::name('nqi_sys_user')->where('openid', $openids)->find();
        if (!empty($useinfo)) {
            $this->sees($useinfo['sys_user_id'],$useinfo['user_name']);//这里是登录操作,无关
            $this->redirect("/news.html?searchmodels=能源&filter=filter-ny&pageindex=2&pagesize=12");
        }
        //得到 access_token 与 openid
        $urls = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $arr['access_token'] . '&openid=' .$openids . '&lang=zh_CN';
        $wechatInfos = $this->http_curl($urls);   这里得到用户资料
        //得到 用户资料,将openid  unionid传给页面,跳转去走注册或者绑定流程页面
        $this->redirect("/bindphone.html?openid=".$wechatInfos['openid']."&nickname=".$wechatInfos['nickname']);
    }

public function http_curl($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_URL, $url);
$json = curl_exec($ch);
curl_close($ch);
return json_decode($json, 1);

}
 

经过上面步骤就可以拿到用户个人信息,头像用户名,openid等信息,想要拿到unionid需要到开放平台去授权公众平台才行

原文地址:https://www.cnblogs.com/yszr/p/15338911.html