微信公众号授权登陆

邱秋 • 2021年11月17日 • 阅读:262 • 微信 公众号

准备工作

注册公众号,登陆后台,在开发-基本配置找到 AppID,AppSecret,配置IP白名单 ,绑定开放平台账号

公众号授权

拉起授权,获取code

传参:

{
  redirect_uri:'授权成功后跳转地址',
  appid:'xxxx'
}

移动web端

url: https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect

PC web端(扫码登录)

url: https://open.weixin.qq.com/connect/qrconnect?appid={appid}&redirect_uri={redirect_uri}&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect

判断没有登陆,进行跳转拉取授权

if(!token){
  window.location.href = url
}

用户同意授权后

如果用户同意授权,页面将跳转至 redirect_uri/?code=CODE&state=STATE。

code说明 : code作为换取access_token的票据,每次用户授权带上的code将不一样,code只能使用一次,5分钟未被使用自动过期。

通过code换取网页授权access_token

次请求,必须服务器发起 传参:

{
  appid:'xxxx',
  secret:'xxx'
}

url: https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appid}&secret=${secret}&code=CODE&grant_type=authorization_code

正确时返回的JSON数据包如下:

{
  "access_token":"ACCESS_TOKEN",
  "expires_in":7200,
  "refresh_token":"REFRESH_TOKEN",
  "openid":"OPENID",
  "scope":"SCOPE" 
}

刷新access_token(如果需要)

由于access_token拥有较短的有效期,当access_token超时后,可以使用refresh_token进行刷新,refresh_token有效期为30天,当refresh_token失效之后,需要用户重新授权。 传参

{
  appid:'xxxx',
  refresh_token:'xxx'
}

url: https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=${appid}&grant_type=refresh_token&refresh_token=${refresh_token}

正确时返回的JSON数据包如下:

{ 
  "access_token":"ACCESS_TOKEN",
  "expires_in":7200,
  "refresh_token":"REFRESH_TOKEN",
  "openid":"OPENID",
  "scope":"SCOPE" 
}

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

传参

{
  access_token:'',
  openid:''
}

url: https://api.weixin.qq.com/sns/userinfo?access_token=${access_token}&openid=${openid}&lang=zh_CN

正确时返回的JSON数据包如下:

{   
  "openid": "OPENID", //用户的唯一标识
  "nickname": "NICKNAME", //用户昵称
  "sex": 1, //性别,1男性,2女性,0未知
  "province":"PROVINCE", //个人资料填写的省份
  "city":"CITY", //人资料填写的城市
  "country":"COUNTRY", //国家
  "headimgurl":"https://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46", //头像
  "privilege":[ "PRIVILEGE1" "PRIVILEGE2"     ],
  "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL" //只有在用户将公众号绑定到微信开放平台帐号后,才会出现该字段。
}

检验授权凭证(access_token)是否有效 传参

{
  access_token:'',
  openid:''
}

url: https://api.weixin.qq.com/sns/auth?access_token=${access_token}&openid=${openid}&lang=zh_CN

返回说明 正确的JSON返回结果:

{ 
  "errcode":0,
  "errmsg":"ok"
}

微信APP授权

微信APP授权登陆,支付等请参见安卓app和微信授权登录及分享完整对接

我,秦始皇,打钱!