首页 > 热点 > 微信 > 正文

微信公众号-获取用户信息(网页授权获取)实现步骤

2024-07-22 01:16:48
字体:
来源:转载
供稿:网友

根据微信公众号开发官方文档:

获取用户信息步骤如下:

1 第一步:用户同意授权,获取code
2 第二步:通过code换取网页授权access_token
3 第三步:刷新access_token(如果需要)
4 第四步:拉取用户信息(需scope为 snsapi_userinfo)

1 获取code

在确保微信公众账号拥有授权作用域(scope参数)的权限的前提下(服务号获得高级接口后,默认拥有scope参数中的snsapi_base和snsapi_userinfo),引导关注者打开如下页面:

https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect

若提示“该链接无法访问”,请检查参数是否填写错误,是否拥有scope参数对应的授权作用域权限。

尤其注意:由于授权操作安全等级较高,所以在发起授权请求时,微信会对授权链接做正则强匹配校验,如果链接的参数顺序不对,授权页面将无法正常访问

其中:

AppID - 公众号的唯一标识
REDIRECT_URI - 跳转url
SCOPE - 值为snsapi_base(不弹出授权页面,直接跳转,只能获取用户openid) 或snsapi_userinfo (弹 出授权页面,可通过openid拿到昵称、性别、所在地。并且,即使在未关注的情况下,只要用户授权,也能获取其信息)
STATE - 开发者可以自定义填写a-zA-Z0-9的参数值

2 通过code换取网页授权access_token

如果用户同意授权,页面将跳转至 redirect_uri/?code=CODE&state=STATE。
state就是上面的STATE参数原样传过来的

实现代码:

<code class="hljs php">$code = I('get.code');if (empty($code)) {   //todo 非微信访问   exit('</code>'); }else{ //授权后操作 }

在这里我们就可以得到code用作后续的获取access_token。

获取code后,请求以下链接获取access_token:

 https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code

appid - 公众号的唯一标识
secret - 密钥
code - 上述所返回的code
grant_type - 值为authorization_code

实现代码:

<code class="hljs bash">$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . C('wechat.AppID') . '&secret=' . C('wechat.AppSecret');$str = file_get_contents($url);$str = json_decode($str, true);$access_token = $str['access_token'];</code>

这里access_token可以做缓存处理,避免造成频繁获取
实现代码,以TP框架为例:

<code class="hljs php">$access_token = S('access_token');if (empty($access_token)) {  $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . C('wechat.AppID') . '&secret=' . C('wechat.AppSecret');  $str = file_get_contents($url);  $str = json_decode($str, true);  $access_token = $str['access_token'];  S('access_token', $access_token, 3600);}</code>            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表