微信公众号获取用户基本信息

1、需要在公众号内配置IP白名单和回调域名。
2、先根据 appid 获取code

public function wxLogin()
{
  $appid = '你的appid';
  // 你的授权回调地址
  $redirect_uri = urlencode("http://你的域名/index/getopenid/getuserinfo");
  $url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
  $this->redirect($url);
}

3、使用 appid 和 appsecret 以及获取到的 code 换取本次请求的 access_token
并且得到用户的基本信息

public function getUserInfo()
{
  $code = $_GET["code"];
  $appId = '你的appid';
  $appSecret = '你的appsecret';
  $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appId&secret=$appSecret&code=$code&grant_type=authorization_code";
  $res = $this->sendRequest($url);
  $access_token = $res["access_token"];
  $openId  = $res['openid'];
  $getUserInfo = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openId&lang=zh_CN";
  //得到用户信息
  $user_info = $this->sendRequest($getUserInfo);
  var_dump($user_info);
}
//发送请求
public function sendRequest($url)
{
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  $output = curl_exec($ch);
  curl_close($ch);
  return json_decode($output, true);
}

发布了22 篇原创文章 · 获赞 16 · 访问量 1543

猜你喜欢

转载自blog.csdn.net/ZhangJiWei_2019/article/details/103819054