美文网首页
微信小程序敏感词过滤

微信小程序敏感词过滤

作者: 生于乱世 | 来源:发表于2021-07-14 14:57 被阅读0次

当你的小程序有用户提交(评论、文章、图片)时,如果你的代码没有过滤敏感词汇,将会审核不通过,幸好官方提供了API,方便了很多
这里我只过滤文字 我采用的是云函数方法
第一步:在项目中新建一个文件夹例如functions
第二部:找到项目中的prject.config.json配置文件,加入cloudfunctionRoot:'文件夹名'

image.png

第三步:右键functions文件夹名,新建Node.js云函数,起名为:msgSC

// 云函数入口文件 index.js
const cloud = require('wx-server-sdk')
 
cloud.init()
 
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  try {
    const result = await cloud.openapi.security.msgSecCheck({
      content: event.text
    })
    
    if (result && result.errCode.toString() === '87014'){
      return { code: 500, msg: '内容含有违法违规内容', data: result }
    }else{
      return { code: 200, msg: 'ok', data: result }
    }
  } catch (err) {
    // 错误处理
    if (err.errCode.toString() === '87014') {
      return { code: 500, msg: '内容含有违法违规内容', data: err } 
    }
    return { code: 502, msg: '调用security接口异常', data: err }
  }
}

第四步:新建config.json


image.png
//config.json 这条注释请不要复制到代码中
{
  "permissions": {
    "openapi": [
      "security.msgSecCheck"
    ]
  }
}

第五步:右键msgSC函数名=》上传并部署,不上传node-modules
第六步:page中调用

  bindbt: function () {
    that = this;
    wx.cloud.init();
    wx.cloud.callFunction({
      name: 'msgSC',
      data: {
        text: "需要检测的内容"
      }
    }).then((res) => {
      if (res.result.code == "200") {
        //检测通过
 
      } else {
 
        //执行不通过
        wx.showToast({
          title: '包含敏感字哦。',
          icon: 'none',
          duration: 3000
        })
      }
    })
  }

以后哪个页面需要使用,直接把这个方法放里面就OK了

转载自:https://www.jianshu.com/p/97880eec839d

相关文章

网友评论

      本文标题:微信小程序敏感词过滤

      本文链接:https://www.haomeiwen.com/subject/diijpltx.html