微信公衆號獲取用戶基本信息

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);
}

發佈了24 篇原創文章 · 獲贊 16 · 訪問量 5093
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章