小程序开发技巧(三)– 云开发时效数据刷新和存储 (access_token等)

小程序云开发时效数据刷新和存储 (access_token等)

1.问题描述

小程序中经常有需要进行OCR识别,或者使用外部api例如百度AI识别等接口,请求调用这些接口需要令牌,即一些具有时效性的数据。本文以小程序云开发使用百度API接口为例,介绍access_token定时刷新和请求机制。

下面是百度调用身份证识别的一段需求,需要传的参数需要有access_token。

请求示例

HTTP 方法:POST

请求URL: https://aip.baidubce.com/rest/2.0/ocr/v1/idcard

URL参数:

参数
access_token 通过API Key和Secret Key获取的access_token,参考“Access Token获取

access_token 是具有时效性的数据,每次请求一次接口就进行一次请求刷新,显然是对计算机资源的极大浪费,且影响效率。

2.问题解决方案

2.1.云数据库配置

新建一个云数据库名为setconfig。作为配置型信息存储数据库,类似access_token的数据都可以向其中存储。

对access_token配置下列字段:

  1. _openid (你的openid* 必填)
  2. config_name (配置名,填access_token)
  3. value (access_token的值,默认为null)

id会自动生成,配置完效果如下(这个value是已经更新后的值)

2.2 定时云函数配置

阅读access_token获取的文档,可知,我们需要请求一个地址来获取access_token的值。

获取Access_Token

请求URL数据格式

向授权服务地址https://aip.baidubce.com/oauth/2.0/token发送请求(推荐使用POST),并在URL中带上以下参数:

  • grant_type: 必须参数,固定为client_credentials
  • client_id: 必须参数,应用的API Key
  • client_secret: 必须参数,应用的Secret Key

例如:

https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=Va5yQRHlA4Fq5eR3LT0vuXV4&client_secret=0rDSjzQ20XUj5itV6WRtznPQSzr5pVw2&

实现

我们需要在云函数中模拟请求,并根据返回结果刷新云数据库中的access_token值。

想要运行通过该程序,需要开发者自己去百度创建账号并创建应用。

云函数index.js

// 云函数入口文件 index.js  const cloud = require('wx-server-sdk')    cloud.init({    env: cloud.DYNAMIC_CURRENT_ENV  })  const db = cloud.database()  var request = require('request')  // 定时器  exports.main = async(event, context) => {    const appkey = '填写你的百度AppKey';    const appsecret = '填写你的百度AppSecret';    var url = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + appkey + '&client_secret=' + appsecret;    return new Promise((resolve, reject) => {      request({        url: url,        method: "POST",        json: true,        headers: {          "content-type": "application/json",        },      }, function(error, response, body) {          if (!error && response.statusCode == 200) {          console.log('通行证为' + body.access_token)          resolve(body.access_token)            //记得修改.doc('xxx') 中的内容          db.collection('setconfig').doc('aaaf5a56-1dd9-4e50-974b-34688fa47b20').update({            data: {              value: body.access_token            }            }).then(res => {            console.log('调用完成')            console.log(res)          })        }      })    })  }

docid是setconfig生成的,每个人不同注意修改

还有一种更新写法,不过更推荐使用上面的方法,效率更高,且稳定。

db.collection('setconfig').where({      config_name:'access_token'  }).update({   data: {        value: body.access_token      }  })

云函数config.json(定时触发器功能实现)

{    // triggers 字段是触发器数组,目前仅支持一个触发器,即数组只能填写一个,不可添加多个    "triggers": [      {        // name: 触发器的名字,规则见下方说明        "name": "myTrigger",        // type: 触发器类型,目前仅支持 timer (即 定时触发器)        "type": "timer",        // config: 触发器配置,在定时触发器下,config 格式为 cron 表达式,        //现在为每天凌晨两点触发        "config": "0 0 2 * * * *"      }    ]  }

云函数整体结构为:

然后上传并部署(云端安装依赖)。

2.3 小程序端获取Access_token

在小程序进入相应界面的时候,请求云数据库,获取access_token

onLoad: function (options) {      //页面初始化      var that = this;      db.collection('setconfig').where({        config_name:'access_token'      }).get({        success(res){          that.setData({            access_token:res.data[0].value          })          //console.log(res.data[0])        },        fail(res){          wx.showToast({            title: '请求失败,无法通过扫描填充数据',          })        }      })    },

3. 参考资料

[1]百度AI鉴权认证机制

[2]微信小程序云开发数据库update函数更新不了数据的问题

[3]小程序云开发定时触发器

小程序开发相关问题欢迎联系QQ 1025584691