微信的测试公众号有很丰富的功能。
申请了测试公众号后,先配置接口信息后,还要设置网页授权
网页授权成功了后,你才能使用你的网页获取用户的信息。
通过接口调试工具,我们先设置自定义菜单,代码如下
{
"button": [
{
"type": "view",
"name": "测试",
"url": "https://open.weixin.qq.com/connect/oauth2/authorize?appid=公众号ID&redirect_uri=回调网页&response_type=code&scope=snsapi_base&state=1#wechat_redirect"
}
]
}
这里的回调网页需要注意格式,个人建议把回调页面URL使用UrlEncode编码,这样可以尽量避免出错。
举个例子:
假设我的网页授权域名设置的是:www.zyq_hh.com,
回调页面:http://www.zyq_hh.com/callback.php
把回调页面进行UrlEncode编码即可
回调页面代码如下:
<?php
$appid = "你的公众号ID";
$secret = '你的公众号secret';
$code = $_GET["code"];
$get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$secret.'&code='.$code.'&grant_type=authorization_code';
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$get_token_url);
curl_setopt($ch,CURLOPT_HEADER,0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
$res = curl_exec($ch);
curl_close($ch);
$json_obj = json_decode($res,true);
$access_token = $json_obj['access_token'];
$openid = $json_obj['openid'];
$get_user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$get_user_info_url);
curl_setopt($ch,CURLOPT_HEADER,0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
$res = curl_exec($ch);
curl_close($ch);
$user_obj = json_decode($res,true);
$openid = $user_obj['openid'];
echo $openid;
?>