微信小程序使用云函数通过security.msgSecCheck校验文本信息安全(过滤敏感词)

作者 : admin 本文共2542个字,预计阅读时间需要7分钟 发布时间: 2022-10-30 共821人阅读

微信官方提供了两种方法

一、HTTPS 调用

请求地址

POST https://api.weixin.qq.com/wxa/msg_sec_check?access_token=ACCESS_TOKEN

此方式需要在服务端用appid和secret换取ACCESS_TOKEN 比较麻烦,有需要的去看官方文档,https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/sec-check/security.msgSecCheck.html#method-http

这里记录的是第二种方法。

二、云调用

云调用使用云函数开发,需要你安装node.js,这里就不赘述了。

下面开始。

创建云函数
1.在根目录中创建云函数文件夹cloudfunctions

马赛克部分为云开发环境名称(云空间名称)

 

2.配置云函数路径

在项目最下面的项目配置文件(project.config.json)中加上刚才生成的根目录
“cloudfunctionRoot”: “cloudfunction/”,

然后ctrl+s保存就会发现刚才的文件夹上面出现一朵云了。

 

3.创建Node.js云函数

右击刚才创建的文件夹cloudfunctions,选择“新建Node.js云函数”,创建你的云函数的函数名称,自定义,这里我的是checkMsg

配置security.msgSecCheck方法
1.在刚才生成的云函数文件config.json中添加security.msgSecCheck方法

2.在app.json中加上security.msgSecCheck方法
“permission”: {
“openapi”:[
“security.msgSecCheck”
]
}

3.编写云函数方法

在云函数文件中index.js中,我这里使用的是文本检测2.0接口,1.0会有一直返回ok的问题,官方建议使用2.0

// 云函数入口文件
const cloud = require(‘wx-server-sdk’)
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  try {
    const result = await cloud.openapi.security.msgSecCheck({
        “openid”:wxContext.OPENID,
        “scene”: 1,
        “version”: 2,
        “content”: event.msg
    })
    return result
  } catch (err) {
    return err
  }
}

方法调用,逻辑部分替换成你自己的

wx.cloud.callFunction({
          name:”checkMsg”,
          data:{
            msg:e
          }
        })
        .then(res=>{
          if(res.result.errCode==0){
            if(res.result.result.suggest==’pass’){
                console.log(res,”检查通过”);
                wx.hideLoading();
                t.setData({
                    defaultInputValue: t.data.inputValue || “”,
                    showInput: !1,
                    displayText: t.data.inputValue
                }), t.data.inputValue, t.onChangeScroll()
            }else{
              console.log(“检查未通过”);
              wx.hideLoading();
              t.setData({
                  defaultInputValue: “”,
                  displayText: “”,
                  inputValue: “”
              }), wx.showToast({
                  title: “请注意言论,您输入的内容包含敏感词”,
                  icon: “none”
              })
            }
          }else{
            wx.showToast({
              title: “参数错误!”,
                icon: “none”
            })
          }
        })

这里有个地方需要注意一下,如果只是这样执行的话会报错没有初始化,
需要在app.js中对此进行初始化

env是云环境的ID

最后,上传云函数

在上传之前需要安装两个依赖,

安装wx-server-sdk依赖
在云函数上右键,最后选项打开终端
npm install –save wx-server-sdk@latest

安装got依赖
在云函数上右键,打开终端
npm install got -save

安装依赖完成之后在云函数中会出现package-lock.json这个文件
然后在package.json中会出现对应依赖的版本号

最后在云函数右键点击“上传并部署:云端安装依赖(不上传node_modules)”

结束!

 

嘟咪云,提供最优质的的资源集合
嘟咪云 » 微信小程序使用云函数通过security.msgSecCheck校验文本信息安全(过滤敏感词)

常见问题FAQ