作者:手机用户2702936044 | 来源:互联网 | 2020-09-29 13:52
index.php如下:
//scope=snsapi_base 实例
$appid='你的AppId';
$redirect_uri = urlencode ( 'http://你的域名/getUserInfo.php' );
$url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_base&state=1#wechat_redirect";
header("Location:".$url);
getUserInfo.php如下:
$appid = "你的AppId";
$secret = "你的AppSecret";
$code = $_GET["code"];
//第一步:取全局access_token
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
$token = getJson($url);
//第二步:取得openid
$oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
$oauth2 = getJson($oauth2Url);
//第三步:根据全局access_token和openid查询用户信息
$access_token = $token["access_token"];
$openid = $oauth2['openid'];
$get_user_info_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN";
$userinfo = getJson($get_user_info_url);
//打印用户信息
print_r($userinfo);
function getJson($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);
}
scope为snsapi_userinfo 用户不用关注公众号,也能取到信息,但是会有一个界面让用户去点击确认!相当于一个登录授权吧!
代码实例
index.php如下:
//scope=snsapi_userinfo实例
$appid='你的AppId';
$redirect_uri = urlencode ( 'http://你的域名/getUserInfo.php' );
$url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
header("Location:".$url);
getUserInfo.php如下:
$appid = "你的AppId";
$secret = "你的AppSecret";
$code = $_GET["code"];
//第一步:取得openid
$oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
$oauth2 = getJson($oauth2Url);
//第二步:根据全局access_token和openid查询用户信息
$access_token = $oauth2["access_token"];
$openid = $oauth2['openid'];
$get_user_info_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN";
$userinfo = getJson($get_user_info_url);
//打印用户信息
print_r($userinfo);
function getJson($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);
}
测试步骤:
创建index.php和getUserInfo.php两个文件后
先测试:scope为snsapi_base
1)先关注公众账号
2)将网址: http://你的域名/index.php 生成一个二维码!
3)用微信扫一扫
再测试:scope为snsapi_userinfo
1)替换代码
2)取消关注当前公众号.
3)然后用微信扫一扫,刚刚你生成的二维码.
相关学习推荐:php编程(视频)
以上就是基于PHP微信网页获取用户信息的实例分析的详细内容,更多请关注 第一PHP社区 其它相关文章!