微信小程序敏感词过滤

当你的小程序有用户提交(评论、文章、图片)时,如果你的代码没有过滤敏感词汇,将会审核不通过,幸好官方提供了API,方便了很多,废话不多说,干!

本文只有文字过滤

本文采用的是云函数方法

为了不浪费各位的时间特此说明

一、启动微信开发者工具

1、在项目中新建一个文件夹例如functions,

2、找到项目中的prject.config.json配置文件,加入cloudfunctionRoot:’文件夹名’,如下图:

微信小程序敏感词过滤

 "cloudfunctionRoot": "functions/",

3、右键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 }
  }
}

4、新建config.json

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

5、右键msgSC函数名=》上传并部署,不上传node-modules

6、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了

二、总结一下几个关键点

1、prject.config.json配置文件

2、config.json中的openapi的值

3、try和catch一定要加入判断

本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 1

封装filter

<?php


namespace App\lib;


class Filter
{
    /**
     * 内容审核
     */
    public function contentAudit($content)
    {
//        $content = $request->post('content');
        //ApiKey和SecretKey从自己在百度智能云上创建的应用信息里获取
        $token = $this->getAccessToken('', '');

        $url = 'https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined?access_token=' . $token;

        $bodys = array(
            'text' => $content
        );

        $res = $this->curlPost($url, $bodys);

        //结果转成数组
        $res = json_decode($res, true);

        //根据自己的业务逻辑进行处理

        return $res;
    }

    /**
     * 图片审核
     */
    public function imageAudit()
    {

        $fileTmp = $request->file('image')->getPathname();
        $token = $this->getAccessToken('ApiKey ', 'SecretKey ');
        $url = 'https://aip.baidubce.com/rest/2.0/solution/v1/img_censor/v2/user_defined?access_token=' . $token;
        $img = file_get_contents($fileTmp);//本地路径
        $img = base64_encode($img);
        $bodys = array(
            'image' => $img
        );
        $res = $this->curlPost($url, $bodys);
        //结果转成数组
        $res = json_decode($res, true);
        //根据自己的业务逻辑进行处理
        return $res;
    }

    /**
     * CURL的Post请求方法
     * @param string $url
     * @param string $param
     * @return bool|string
     */
    function curlPost($url = '', $param = '')
    {
        if (empty($url) || empty($param)) {
            return false;
        }

        $postUrl = $url;
        $curlPost = $param;
        // 初始化curl
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $postUrl);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        // 要求结果为字符串且输出到屏幕上
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        // post提交方式
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
        // 运行curl
        $data = curl_exec($curl);
        curl_close($curl);

        return $data;
    }

    /**
     * 获取百度开放平台的票据
     * 参考链接:https://ai.baidu.com/ai-doc/REFERENCE/Ck3dwjhhu
     */
    public function getAccessToken($ApiKey = '', $SecretKey = '', $grantType = 'client_credentials')
    {

        $url = 'https://aip.baidubce.com/oauth/2.0/token';
        $post_data['grant_type'] = $grantType;
        $post_data['client_id'] = $ApiKey;
        $post_data['client_secret'] = $SecretKey;
        $o = "";
        foreach ($post_data as $k => $v) {
            $o .= "$k=" . urlencode($v) . "&";
        }
        $post_data = substr($o, 0, -1);

        $res = $this->curlPost($url, $post_data);
        //进行把返回结果转成数组
        $res = json_decode($res, true);
        if (isset($res['error'])) {
            exit('API Key或者Secret Key不正确');
        }
        $accessToken = $res['access_token'];
        return $accessToken;
    }


}
    public function commentAdd(Request $request)
    {
        $res = $request->post();
        $text = $res['content'];
//过滤content
        $filter = new Filter();
        $filterName = $filter->contentAudit($text);
        if ($filterName['conclusion'] == '合规') {
            $data = Comment::commentAdd($res);
            $id = $data->id;
            $result = $data->toArray();
            $es = new Es();
            $arr = $es->add_doc($id, $result, '123', 'fang');
            if (!$arr) {
                return response(['code' => 400]);
            }
            return response(['code' => 200]);
        }
        return response(['code' => 500, 'msg' => '敏感词汇']);
    }
2年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!