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