小程序开发笔记,七—加入内容安全检测

前两天在发布小程序版本的时候,审核被拒绝,原因是用户在发表内容的时候,没有对内容做安全检测,例如国家领导人姓名之类的。

后来了解到小程序官方文档上有提供相关检测接口,包括文本及图片检测,这里我只用到了文本检测

使用msgSecCheck接口检测文本

https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/sec-check/security.msgSecCheck.html

请求接口地址是 https://api.weixin.qq.com/wxa/msg_sec_check?access_token=ACCESS_TOKEN

,为POST请求,请求参数为:

  • access_token 接口调用凭证
  • content 要检测的文本内容,长度不超过 500KB
let content = params.content;
let access_token = await this.app.redis.get('access_token');
      let url = `https://api.weixin.qq.com/wxa/msg_sec_check?access_token=${access_token}`;
      let data = {
        content: content
      }
      let checkResult = await proxy(url, {
        headers: {
          'Content-Type': 'application/json'
        },
        method: 'POST',
        body: JSON.stringify(data)
      });
      checkResult = JSON.parse(checkResult);
if (checkResult.errcode == 87014) {
        // 内容含有违法违规内容
        response = this.ResultResponse.createByErrorMsg('内容含有违法违规内容');
      }

定时刷新access_token凭证

access_token是接口调用凭证,通过getAccessToken接口获取

https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/access-token/auth.getAccessToken.html

接口请求地址是 https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET,为GET请求,请求参数为:

  • grant_type 填写 client_credential
  • appid 小程序唯一凭证,即 AppID
  • secret 小程序唯一凭证密钥,即 AppSecret

接口返回数据除了access_token还有expires_in过期时间 ,这里有效期是7200s,也就是2小时候该凭证失效,所以我们需要通过定时器定时刷新获取access_token,然后存到redis里面

/////////get_access_token.js文件
const Subscription = require('egg').Subscription;
/**
 * 获取微信accessToken定时任务  90(5400s)分钟刷新一次
 */
class GetAceessToken extends Subscription {
  // 通过 schedule 属性来设置定时任务的执行间隔等配置
  static get schedule() {
    return {
      interval: '5400s', // 1 分钟间隔  隔单位 m 分 、  s 秒、  ms  毫秒 
      type: 'all', // all 指定所有的 worker 都需要执行   worker 每台机器上只有一个 worker 会执行这个定时任务
      immediate: true, //配置了该参数为 true 时,这个定时任务会在应用启动并 ready 后立刻执行一次这个定时任务。
      disable: false//配置该参数为 true 时,这个定时任务不会被启动。
    };
  }

  // subscribe 是真正定时任务执行时被运行的函数
  async subscribe() {
    let ctx = this.ctx;
    ctx.logger.info('-----getAccessToken start----');
    try {
      await ctx.service.userService.getAccessToken();
    } catch (error) {
      console.log('获取access token失败', error)
    }
    ctx.logger.info('-----getAccessToken end----');
  }
}

module.exports = GetAceessToken;

/////////userService.js文件
/**
  * 获取AccessToken,存储到redis里面,用于安全内容检查 每90分钟刷新一次
  */
  async getAccessToken() {
    let url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${config.key.appid}&secret=${config.key.secret}`;
    let result = await proxy(url, {
      method: 'GET'
    });
    result = JSON.parse(result);
    console.log('getAccessToken result', result)
    await this.app.redis.set('access_token', result.access_token);
    await this.app.redis.set('expires_in', result.expires_in);//目前有效期7200s 2小时
  }