巧用云函数实现小程序全局 access_token 刷新

# 实现思路

利用云函数请求微信服务器获取小程序全局唯一后台接口调用凭据并存入云数据库,配合云函数的触发器来实现定期刷新。

# 云数据库配置

新建集合用于存放调用凭据

# 云函数代码

新建文件 package.json 输入以下内容

{
    "name": "sync_mp_access_token",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {},
    "author": "",
    "license": "ISC",
    "dependencies": {
        "request-promise": "^4.2.6",
        "@cloudbase/node-sdk": "latest"
    }
}

然后点击『保存并安装依赖』

修改 index.js 输入以下内容

'use strict';
const cloudbase = require("@cloudbase/node-sdk");
const rp = require('request-promise')
const app = cloudbase.init({
    env: '环境ID'
});
const db = app.database();
const appId = '自己的id'
const appSecrect = '自己的密钥'
const tokenForUrl =
    'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' + appId + '&secret=' + appSecrect
exports.main = async (event, context) => {
    let tokens = await db
        .collection('access_tokens')
        .get()

    if (tokens.data.length > 0) {
        let expires_time = tokens.data[0].expires_time
        console.log(parseInt(Date.now() / 1000) > expires_time + 3600)
        if (parseInt(Date.now() / 1000) > expires_time + 3600) {
            let tokenInfoNew = await rp({ url: tokenForUrl })
            tokenInfoNew = JSON.parse(tokenInfoNew)
            let expires_time = parseInt(Date.now() / 1000)
            await db
                .collection('access_tokens')
                .doc(tokens.data[0]._id)
                .update({
                    access_token: tokenInfoNew.access_token,
                    expires_time: expires_time
                })
            return tokenInfoNew
        } else {
            return tokens.data[0]
        }
    } else {
        let tokenInfoNew = await rp({ url: tokenForUrl })
        tokenInfoNew = JSON.parse(tokenInfoNew)
        let expires_time = parseInt(Date.now() / 1000)
        return await db.collection('access_tokens').add({
            access_token: tokenInfoNew.access_token,
            expires_time: expires_time
        })
    }

};

# 触发器设置

可以设置为每一小时触发一次。

{
    "triggers": [
        {
            "name": "sync_mp_access_token",
            "type": "timer",
            "config": "0 0 */1 * * * *"
        }
    ]
}

# HTTP访问

配合HTTP访问服务地址来随时取用

# 测试结果

# 参考资料

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐