php 微信公众号获取用户信息

 

微信公众号获取用户id,要在公众平台设置code的回调域名,然后在用这个域名拼接链接即可。这个code不需要前端传输。虽然有$_GET['code'],但是code是微信直接返回的,代码如下:

//如果没有session 则获取
if(empty($this->session->get('openid'))){
// 微信授权
if(empty($_GET['code'])){
  $appid = $this->appid;
  $redirecturl = urlencode(\App_Const::Domain_INDEX);
  $url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.$redirecturl.'&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect';
header("Location:$url");//自动跳转到code界面获取code值。
}
// *应用授权作用域,snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid),snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且,即使在未关注的情况下,只要用户授权,也能获取其信息)
// *获取code openid
$appid = $this->appid;
$secret = $this->AppSecret;
$code = $_GET["code"];
$get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$secret.'&code='.$code.'&grant_type=authorization_code';
$res=send_post($get_token_url);
$json_obj = json_decode($res,true);
//根据openid和access_token查询用户信息
$access_token = $json_obj['access_token'];
$openid = $json_obj['openid'];
//$get_user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';

//$res=send_post($get_user_info_url);
//解析json
$wx_user = json_decode($res,true);
if(empty($openid)){
  $msg['msg'] = 'error';
  $msg['msg'] = '获取openid失败,请退出公众号重新进入';
  echo json_encode($msg);exit();
}
//微信信息存入session
$this->session->set('access_token',$access_token_user);
//保存openid
$this->session->set('openid',$openid);
}

转载于:https://www.cnblogs.com/ayanboke/p/9405865.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值