页面获取微信用户信息

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_38343894/article/details/79036844

获取用户基本信息需要以下三步:

  1. 获取code

    使用以下地址请求code:

    https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect
  2. 以上地址需要的参数解释:

    appid: 你的公众开发平台的appid

    redirect_uri: 你的回调地址, 获得code后会把code作为参数传入此地址中

    response_type: 直接填写code就行了

    scope: 如果获取用户信息的code就用snsapi_userinfo就行了

    state: (非必须)用于保持请求和回调的状态,授权请求后原样带回给第三方。该参数可用于防止csrf攻击(跨站请求伪造攻击),建议第三方带上该参数,可设置为简单的随机数加session进行校验

  3.  
  4. 通过code获取access_tokenopenid

    如果第一步没有问题的话, 在第一步中的redirect_uri参数地址中会接收到code信息;

    使用以下地址请求access_token和openid:

    https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code

    以上地址需要的参数解释:

    appid: 你的公众开发平台的appid

    secret: 你的公众开发平台的AppSecret

    code: 第一步传过来的code

    grant_type: 填写authorization_code就OK

  5.  
  6. 通过access_tokenopenid获取用户基本信息:

    使用以下地址请求用户基本信息:

    https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN';

    以上地址需要的参数解释:

    access_token: 通过第二步获取的access_token

    openid: 通过第二步获取的openid

    lang: 填写zh_CN就ok

  7.  

通过以上3步就能获取用户信息, 下面附上php代码的实现: 

// 入口函数
function main() {
$appid = "wxf445027deded67b7";
$redirect_uri=urlencode("http://XXXXXX/redirect); // 这里的回调地址为下面的函数
$url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
header('location:'.$url);
}
// 回调地址
function redirect() {
$info = $_REQUEST;
// 获取access_token和openid
$appid="wxf445027deded789"; // 公众平台的appid
$secret = "2e3a89b8de95d123213213"; // 公众平台的secret
$code = $info['code'];
$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$secret.'&code='.$code.'&grant_type=authorization_code';
$data = getCurl($url);
// 获取用户信息
$access_token = $data->access_token;
$openid = $data->openid;
$url1 = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
$data1 = getCurl($url1);
echo json_encode($data1);
}
// curl请求数据函数
function getCurl($url) {
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT,10);
$data = json_decode(curl_exec($ch));
curl_close($ch);
return $data;
}

猜你喜欢

转载自blog.csdn.net/weixin_38343894/article/details/79036844