编程爱好者之家
第一:在微信开放平台申请允许第三方用用后,获取到AppID以及AppSecrect信息
第二:进行登录,请求code
说明如下:
| 参数 | 是否必须 | 说明 |
|---|---|---|
| appid | 是 | 应用唯一标识 |
| redirect_uri | 是 | 请使用urlEncode对链接进行处理 |
| response_type | 是 | 填code |
| scope | 是 | 应用授权作用域,拥有多个作用域用逗号(,)分隔,网页应用目前仅填写snsapi_login即 |
| state | 否 | 用于保持请求和回调的状态,授权请求后原样带回给第三方。该参数可用于防止csrf攻击(跨站请求伪造攻击),建议第三方带上该参数,可设置为简单的随机数加session进行校验 |
在浏览器中输入地址会出现下图

第三:返回接口实现
第二步骤中的redirect_uri 就是微信获取信息后返回的接口
代码实现如下
<?php
$code = $_GET['code'];
$state = $_GET['state'];
//换成自己的接口信息
$appid = 'wxtd3rf1bee60e8e';
$appsecret = 'ba0960ag30a53gce9eg2c2afg2';
if (empty($code)) print_R('授权失败');
$token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';
$token = json_decode(file_get_contents($token_url));
if (isset($token->errcode)) {
echo '<h1>错误:</h1>'.$token->errcode;
echo '<br/><h2>错误信息:</h2>'.$token->errmsg;
exit;
}
$access_token_url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid='.$appid.'&grant_type=refresh_token&refresh_token='.$token->refresh_token;
//转成对象
$access_token = json_decode(file_get_contents($access_token_url));
if (isset($access_token->errcode)) {
echo '<h1>错误:</h1>'.$access_token->errcode;
echo '<br/><h2>错误信息:</h2>'.$access_token->errmsg;
exit;
}
$user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token->access_token.'&openid='.$access_token->openid.'&lang=zh_CN';
//转成对象
$user_info = json_decode(file_get_contents($user_info_url));
if (isset($user_info->errcode)) {
echo '<h1>错误:</h1>'.$user_info->errcode;
echo '<br/><h2>错误信息:</h2>'.$user_info->errmsg;
exit;
}
$result = json_decode(json_encode($user_info),true);//返回的json数组转换成array数组
//打印用户信息echo '<pre>';
print_r($result );echo '</pre>';打印信息如下:
Array ( [openid] => o-ukg1dHhZfHpP599dEkdWw-rC6k [nickname] => 测试昵称 [sex] => 1 [language] => zh_CN [city] => 闵行 [province] => 上海 [country] => 中国 [headimgurl] => http://thirdwx.qlogo.cn/mmopen/vi_32/6QKOCrTPbTwOrGL1xoyS0MS4P3HYyfXCOvfOyunzUujibwOoicvrpHLl7SHVRy2KZMHnHB1pN6lSicFKYZSQ/132 [privilege] => Array ( ) [unionid] => o4BJJ94i_138Tvt2bt1psNribCXU )
最后就可以进行后续的操作了