本文共 3006 字,大约阅读时间需要 10 分钟。
在确保微信公众账号具有授权作用域(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
注意事项:
snsapi_base
:不弹出授权页面,直接跳转。snsapi_userinfo
:弹出授权页面,可获取openid、昵称、性别、所在地等信息。用户同意授权后,页面跳转至redirect_uri/?code=CODE&state=STATE
。
这里获取的是特殊的网页授权access_token,与基础支持中的access_token不同。公众号可通过以下接口获取网页授权access_token:
https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID
特别注意:
说明:
snsapi_base
,只需获取openid,流程到此结束。snsapi_userinfo
,需进行后续步骤。由于access_token有效期较短,可以使用refresh_token刷新。refresh_token有效期为30天,如失效需用户重新授权。
在获取了access_token和openid后,可以通过以下接口拉取用户信息:
https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID
前端功能简要说明:
https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
业务需求:用户有自己的登录系统,若已在微信上登录,则直接跳转至内部页面,否则跳转至登录页。
登录逻辑:
export default { data() { return { appid: process.env.VUE_APP_WECHAT_APP_ID, openId: null }; }, mounted() { var that = this; const openIdStorage = storageDB.getItem('openId'); if (openIdStorage) { this.openId = openIdStorage; } else { this.getCode(); } }, methods: { getCode() { const scope = 'snsapi_base'; // 静默授权 const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${this.appid}&redirect_uri=${encodeURIComponent(window.location.href)}&response_type=code&scope=${scope}#wechat_redirect`; if (window.location.href.includes('?')) { window.location.href = url; } else { const theRequest = this.getUrlCode(); const state = theRequest['state']; if (!state) { window.location.href = url; } } }, getUrlCode() { const fullUrl = window.location.href; const theRequest = {}; if (fullUrl.includes('#')) { const hash = fullUrl.split('#')[1]; const param = hash.split('&')[0]; const key = param.split('=')[0]; const value = param.split('=')[1] || ''; theRequest[key] = value; } else if (fullUrl.includes('?')) { const query = fullUrl.split('?')[1]; const params = query.split('&'); for (let param of params) { const [key, value] = param.split('='); if (key) { theRequest[key] = value; } } } return theRequest; } }};
storageDB
需根据实际情况配置。ACCESS_TOKEN
、OPENID
需妥善处理。转载地址:http://thqwk.baihongyu.com/