11-03 6,270 views
前几天发了一份微信调用JS-SDK分享接口的教程和参考代码
在微信移动页面开发中,除了自定义分享内容外,获取用户基本信息也是经常用到的,这篇文章将介绍下如何通过网页授权获取用户基本信息:
1.设置授权回调域名:每个公众号可以设置一个,我要测试的页面放在wx.karlew.com上,如果要回调的域名不是二级域名,要加上www.,但不要加入http://等协议头。
2.获取code:code是获取用户信息首先要得到的参数,要注意的是,要让用户打开的链接为https://open.weixin.qq.com/connect/oauth2/authorize?appid=(替换为相应公众号的appid)&redirect_uri=(urlencode后的回调链接)&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
例如,若获取用户信息的页面为http://wx.karlew.com/oauth2_test/index.php,所用的公众号appid为wx9b4b97f6ce6647ef,则让用户打开的不能是此链接,而是https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx9b4b97f6ce6647ef&redirect_uri=http%3a%2f%2fwx.karlew.com%2foauth2_test%2findex.php&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
用户同意授权后,页面便可以获取code。
- $code = $_GET['code'];
3.通过code获取access_token和openid:代码如下:
- $appid = "wx9b4b97f6ce6647ef"; //替换为所用公众号的appid
- $appsecret = "b1be97744f78714a5de17f4ca2823211"; //替换为所用公众号的appsecret
- $tokenres = file_get_contents("https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$appsecret."&code=".$code."&grant_type=authorization_code");
- $tokenres = json_decode($tokenres);
- $token = $tokenres['access_token'];
- $openid = $tokenres['openid'];
4.通过access_token和openid获取用户基本信息:
- $infoRes = file_get_contents("https://api.weixin.qq.com/sns/userinfo?access_token=".$token."&openid=".$openid."&lang=zh_CN");
- $infoRes = json_decode($infoRes);
- $nickname = $infoRes['nickname'];
- $sex = $infoRes['sex'];
- $headimgurl = $infoRes['headimgurl'];
除了头像昵称性别外,能获取的信息可查阅微信公众平台开发文档。
获取用户信息完整代码:https://github.com/karlew/wechat/blob/master/oauth2/userinfo.php
另附一份静默授权获取用户openid代码:https://github.com/karlew/wechat/blob/master/oauth2/base.php