h5第三方登录—微信登录

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

1.用户同意授权,获取code

接口路径:

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

参数说明:

参数 说明
appid 公众号的唯一标识 , 后台获取
redirect_uri 授权后重定向的回调链接地址 ,可带参,但太多会被截掉
response_type 填code
scope 授权作用域,snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid),snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且, 即使在未关注的情况下,只要用户授权,也能获取其信息 )
state(可选) 重定向带state参数,a-zA-Z0-9,最多128字节
#wechat_redirect 无论直接打开还是做页面302重定向时候,必须带此参数

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

用户同意授权后:
页面将跳转至 redirect_uri/?code=CODE&state=STATE
(code说明 : code作为换取access_token的票据,每次用户授权带上的code将不一样,code只能使用一次,5分钟未被使用自动过期。)

2.通过code换取网页授权access_token

接口路径:

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

参数说明:

参数 说明
appid 公众号的唯一标识
secret 公众号的appsecret
code 填写第一步获取的code参数
grant_type 填写为authorization_code

返回JSON数据包

{
  //网页授权接口调用凭证
  "access_token":"ACCESS_TOKEN", 
  //access_token接口调用凭证超时时间
  "expires_in":7200,  
  //用户刷新access_token(步骤三需要,来更新access_token)
  "refresh_token":"REFRESH_TOKEN",
  //用户唯一标识
  "openid":"OPENID",
  //用户授权的作用域
  "scope":"SCOPE" 
}

4.拉取用户信息(需scope为 snsapi_userinfo)

接口

//http:GET(请使用https协议) 
https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN

参数说明

参数 说明
access_token 网页授权接口调用凭证
openid 用户的唯一标识
lang 返回国家地区语言版本,zh_CN 简体

返回结果

{   
  "openid":" OPENID",
  " nickname": NICKNAME,
  "sex":"1",
  "province":"PROVINCE"
  "city":"CITY",
  "country":"COUNTRY",
  "headimgurl":       "http://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46",
  "privilege":[ "PRIVILEGE1" "PRIVILEGE2"     ],
  "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
}

以上即可获得用户信息

至于步骤三和五详情跳转微信公众号开发文档
https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html#2

你可能感兴趣的:(微信小程序,第三方登录,微信登录,微信授权)