微信公众号网页授权登录

发布时间:2019-03-25 19:08:22 浏览量:1244 标签: 公众号 微信

本节讲解一下微信公众号开发之-微信网页授权,此开发主要是针对于在微信公众号内打开链接,请求获取用户登录信息。在此之前开发者需要做token验证、有网页授权登录权限。


一、原理

用户微信客户端中访问第三方网页,公众号可以通过微信网页授权机制,来获取用户基本信息,进而实现业务逻辑。


二、过程

具体而言,网页授权流程分为四步:

1、引导用户进入授权页面同意授权,获取code

2、通过code换取网页授权access_token(与基础支持中的access_token不同)

3、如果需要,开发者可以刷新网页授权access_token,避免过期

4、通过网页授权access_token和openid获取用户基本信息(支持UnionID机制)

0046Zieizy6PrX4f0RWb8.jpg

三、代码

1、引导进入授权页面

/**
 * 网页授权
 */
public function webInfo()
{
    //获取code
    $appId       = $this->appId;
    $redirectUrl = urlencode($this->backUrl);
    $scope       = "snsapi_userinfo";
    $state       = rand(1000, 9999);
    $url         = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appId&redirect_uri=$redirectUrl&response_type=code&scope=$scope&state=$state#wechat_redirect";
    header('Location:' . $url);
}


2、获取access_token

/**
 * 授权回调地址
 * @return string
 */
public function wxback()
{
    header("Content-type:text/html;charset=utf-8");
    $code = input('get.code');
    if(!$code)
        $this->error("code获取失败");
    $appId  = $this->appId;
    $secket = $this->secket;
    $url    = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appId&secret=$secket&code=$code&grant_type=authorization_code";
    $result = file_get_contents($url);
    $result = json_decode($result, true);
    //token
    $access_token = $result['access_token'];
    //获取用户信息
    
}


3、通过token和appid获取用户信息

/**
 * 获取用户信息
 * @param $result
 * @return string
 */
public function info($result){
 //获取openid
 $openId = $result['openid'];
 //获取用户信息
 $post_url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openId&lang=zh_CN";
 $userInfo     = file_get_contents($post_url);
 $Info = json_decode($userInfo,true);
 session('openid', $Info['openid'], 'openid');
 session('nickname', $Info['nickname'], 'nickname');
 session('headimgurl', $Info['headimgurl'], 'headimgurl');
 return $userInfo;
}


四、请求结果


正确时返回的JSON数据包如下:

{   
    "openid":" OPENID",
    "nickname": NICKNAME,
    "sex":"1",
    "province":"PROVINCE"
    "city":"CITY",
    "country":"COUNTRY",
    "headimgurl":"http://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46",
    "privilege":[ "PRIVILEGE1" "PRIVILEGE2"],
    "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
}



评论
登录后才可以进行评论哦! QQ登录
验证码
评论内容