Applet development skills (c) - Cloud Development refresh and timeliness of data storage (access_token etc.)

Applet cloud development refresh and timeliness of data storage (access_token etc.)

1. Problem Description

Applets often have the need for OCR recognition, or with an external api e.g. Baidu AI recognition interfaces, these interfaces require the token call request, i.e., a number of time-sensitive data. In this paper, a small program developed using Baidu Cloud API interface as an example, access_token regularly updated and request mechanism.

Here is some demand to call Baidu ID card identification is required pass parameters requires access_token.

Example request

HTTP methods:POST

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

URL parameters:

parameter value
access_token Acquired through the API Key and Secret Key access_token, reference " Access Token obtain "

access_token data is time sensitive, once the interface on each request to conduct a refresh request is clearly a waste of computer resources, and the impact of efficiency.

2. Problem Solution

2.1. Cloud Database Configuration

Create a new database called cloud setConfig . As the configuration type information storage database, the data can be similar to the access_token stored therein.

Access_token configuration of the following fields:

  1. _openid (your openid * Required)
  2. config_name (configuration name, fill access_token)
  3. value (the value of access_token, defaults to null)

id generated automatically configuring the following effect (this value is a value has been updated)

2.2 Timing cloud configuration function

Read the documentation access_token acquired shows that we need to address a request to get the value of the access_token.

Get Access_Token

Request URL data format

Authorized service address to https://aip.baidubce.com/oauth/2.0/tokensend requests (recommended POST), and bring the following parameters in the URL:

  • grant_type: mandatory parameters, fixed 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

Guess you like

Origin www.cnblogs.com/masterchd/p/12431426.html