微信授权相关

已经写过挺多授权部分的了,这里做写记录,并且附上相关的链接,以便后续查阅

主要步骤

其实官网文档已经相当之详细了,这里特地记录下每一步骤实现所用的代码以及相关的工具函数

所以重点还是要看看官方文档

1.获取code

获取code方法如下

1
2
3
4
5
function wechatAuth (appId, redirectUri, responseType, scope, state) {
let url = 'https://open.weixin.qq.com/connect/oauth2/authorize'
let queryString = 'appid=' + appId + '&redirect_uri=' + encodeURIComponent(redirectUri) + '&response_type=' + responseType + '&scope=' + scope + '&state=' + state
location.href = url + '?' + queryString + '#wechat_redirect'
}

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

一般获取access_token 和 openid 都是由后台获取到,因为获取上面两个参数除了code外还需要传secret参数,出于安全考虑不会写在前端(参照文档)

3.刷新access_token (如果需要)

access_token scope为 snsapi_base 时,access_token似乎没啥用处

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

注意scope,这里针对scope为 snsapi_userinfo 的情景,即需要获取用户openid以外的更多信息

5.tips

获取url中code参数的方法

  1. 自写一个原生的
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    getUrlParams (query, _url) {
    const url = _url || window.location.href
    const paramsString = url.indexOf('?') > -1 ? url.substring(url.indexOf('?') + 1, url.length).split('&') : []
    let paramsObj = {}
    paramsString.forEach((item, index) => {
    paramsObj[item.substring(0, item.indexOf('='))] = item.substring(item.indexOf('=') + 1, item.length).split('#')[0]
    })
    if (Object.prototype.toString.call(query).slice(8, -1) === 'Array') {
    return paramsObj
    }
    const returnValue = paramsObj[query]

    if (typeof (returnValue) === 'undefined') {
    return ''
    } else {
    return returnValue
    }
    }
  2. vue 中的 router相关方法
    1
    this.$route.query.code

存储相关配置参数的位置

微信和支付宝授权啊支付啊什么的都需要传一些参数给支付宝或微信的后台,就前端来说,常见的如下

appid scope redirect_uri 等
那这些固定的常量都写在哪里呢?之前我会单新建一个config文件夹,然后分别创建微信和支付宝所需要用到的配置文件,不过有时候在测试的时候不想一遍遍的请求微信那边的授权(比如我只是想那个openid请求自己应用的接口),所以会额外加一些已知的openid userinfo 等,这些往往会再加多两个文件,而且还要加多一些有关开发和生产环境的判断等等

所以如果是在vue-cli的开发环境下,推荐使用环境变量和模式

相关链接

  1. 微信官方文档-网页授权
  2. vue-cli环境变量和模式