微信公众号开发(四)--微信网页授权,获取用户信息

自定义菜单

参考资料

  1. 微信公众平台
  2. 微信公众号开发文档

网页授权

下面代码用THINK_PHP 5.0编写
  1. 网页点击 微信登录请求该接口,返回相应参数
$appId = '';

//successUrl用来传递用户授权成功后的跳转地址
$successUrl = urlencode($this->request->post('successUrl'));

//用户点击同意,跳转的地址,在该地址进行获取用户的信息及相应逻辑处理
$redirectUrl = 'http://xxxxxx/index/wx/wxInfo.html?successUrl='.$successUrl;

//snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且,即使在未关注的情况下,只要用户授权,也能获取其信息)
$scope = 'snsapi_userinfo';
$url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appId
    .'&redirect_uri='.urlencode($redirectUrl)
    .'&response_type=code'
    .'&scope='.$scope
    .'&state=xx'
    .'#wechat_redirect';

//返回微信授权链接  返回的json结构 {code:1,msg:'微信登录',data:{url:$url}}
return $this->jsonSuccess('微信登录', ['url'=>$url]);
  1. 用户同意 http://xxxxxx/index/wx/wxInfo.html 获取用户信息
$code = $this->request->get('code');
$successUrl = $this->request->get('successUrl');
//如果用户已经登录 重定向到成功后跳转的页面
if(Session::get('USER_ID')>0){
    $response = new Redirect(urldecode($successUrl));
    throw new HttpResponseException($response);
}

// 获取openID, accessToken
$appId = '';
$appSecret = '';
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appId 
    ."&secret=".$appSecret
    ."&code=".$code
    ."&grant_type=authorization_code";
try {
    $resStr = file_get_contents($url);
    $res = json_decode($resStr , true);
}catch(\Exception $e){
    return $this->fail('登陆失败');
}
if(!isset($res['access_token'])){
    return $this->fail('登陆失败');
}

$accessToken = $res['access_token'];
$openId = $res['openid'];
// 获取用户信息
$url2 = "https://api.weixin.qq.com/sns/userinfo?access_token=".$accessToken."&openid=".$openId."&lang=zh_CN";
try {
    $result2 = file_get_contents($url2);
    $wxUserInfo = json_decode($result2, true);
}catch(\Exception $e){
    return $this->fail('登陆失败');
}
if(!isset($wxUserInfo['nickname'])){
    return $this->fail('登陆失败');
}
$data = [
    'nick_name' => $wxUserInfo['nickname'],
    'sex' => $wxUserInfo['sex'],
    'poster' => $wxUserInfo['headimgurl'],
    'open_id'=>$wxUserInfo['openid'],
    'unionid'=>isset($wxUserInfo['unionid']) ? $wxUserInfo['unionid'] : '',
    'language'=>$wxUserInfo['language'],
    'city'=>$wxUserInfo['city'],
    'country'=>$wxUserInfo['country'],
    'province'=>$wxUserInfo['province'],
];
//数据保存 省略一部分代码
$userId = '';
Session::set('USER_ID', $userId);
//跳转到成功页面,几秒后跳转到successUrl
return $this->success('登录成功', $successUrl);
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值