玩转微信公号开发(七)——账号体系与oauth登录

默认情况下,如之前“接收消息”里所说,一个用户和微信公号发生交互是,开发者拿到的是用户的openId,每一个用户,对应每一个公号,都有唯一的一个openId,当用户使用微信内置webview访问我们的页面是,开发者可以调用oauth2.0协议,302到自定的url,获取访问者的openId

1
2
3
4
5
$redirect = 'http://xxxx.xxx.com/xxx';
$url = 'http://open.weixin.qq.com/connect/oauth2/authorize?appid=your-appid&redirect_uri='
   .$redirect.'&response_type=code&scope=snsapi_base&state=ubox#wechat_redirect';
$this->redirect($url);
exit;

其中,scope=snsapi_base是要获取的权限类型,snsapi_base获取的只是openId,snsapi_userinfo可以用户获取用的较详细的昵称、头像等内容,但是是需要用户授权
上面的$redirect,就是登陆后需要跳转回来的开发者服务器的地址,这个登录操作是自动的,不需要用户做操作
跳回以后,url后附加一个code参数,通过这个code,再调微信的对应接口,即可获得openId,或者userinfo

1
2
3
4
5
6
$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=your-appid&secret=your-appSecret&code='.
	$_GET['code'].'&grant_type=authorization_code';
$json = Http::httpsGet($url);
$wxInfo = json_decode($json, true);
$openId = $wxInfo['openid'];
//.....你的其他操作

取得json的接口如下:

1
2
3
4
5
6
7
{
  "access_token":"xxxxxxxxxxxxxxxxxxxxxxxx",
  "expires_in":7200,
  "refresh_token":"xxxxxxxxxxxxxxxxxxxxxxxx",
  "openid":"ogaN_jp4sLWa4ZXGu5L39SSKcXU8",
  "scope":"snsapi_base,"
}

如你所见,openid就在里面了,进一步的,有了access_token,scope值如果是snsapi_userinfo,那么你还可以调“/sns/userinfo”接口取用户昵称等信息
expires_in是token超时时间,refresh_token可以用来刷新access_token

————
转载请注明出处: http://www.jiangkl.com/2014/02/weixin_oauth_userinfo/

2 Comments

  • 2014 年 02 月 07 日 - 下午 1:45 | Permalink

    年后初访,表示支持

  • xxx
    2014 年 02 月 23 日 - 下午 11:12 | Permalink

    嘿嘿

  • 发表评论

    电子邮件地址不会被公开。 必填项已用 * 标注

    *

    *