1. 前言
推薦使用 EasyWechat: https://www.easywechat.com/docs/4.x/basic-services/content_security
下載 TP6.0 最新正式版
composer create-project topthink/think=6.0.* tp6
進(jìn)入框架根目錄,安裝 easywechat 4.x 版本擴(kuò)展包
easywechat 4.x 要求PHP7.2+,tp6.0 要求PHP7.2.5+, 這個(gè)版本最適合在TP6.0中使用
cd tp6 && composer require overtrue/wechat:~4.0
2. 文本內(nèi)容安全檢測(cè)
使用示例
$content = '習(xí)近平';
$bool = \app\logic\WeChat::checkText($content);
$bool === false && fault('系統(tǒng)檢測(cè)到文本內(nèi)容中包含非法內(nèi)容');
halt('文本內(nèi)容合法');
拋出錯(cuò)誤
{
"code": 201,
"msg": "系統(tǒng)檢測(cè)到文本內(nèi)容中包含非法內(nèi)容"
}
3. 圖片內(nèi)容安全檢測(cè)
測(cè)試表單
<form action="{:url('upload')}" method="post" enctype="multipart/form-data">
<input type="file" name="img">
<button>提交</button>
</form>
上傳接口
$name = 'img'; // 文件上傳字段域名稱(chēng)
try {
$file = request()->file($name);
if (!$file) throw new \Exception('沒(méi)有文件上傳');
// 敏感圖檢測(cè)
// checkImage() 參數(shù)要求必須是絕對(duì)路徑地址的圖片,可以使用圖片的臨時(shí)存放路徑
$bool = \app\logic\WeChat::checkImage($file->getRealPath());
$bool === false && fault('系統(tǒng)檢測(cè)到圖片中包含非法內(nèi)容');
// 上傳操作 ...
} catch (\Exception $e) {
fault($e->getMessage());
}
4. 代碼示例(基礎(chǔ)類(lèi)庫(kù)層、邏輯層、函數(shù))
基礎(chǔ)類(lèi)庫(kù)層
<?php
namespace app\lib;
use EasyWeChat\Factory;
/**
* 小程序
*/
class MiniProgram
{
private $app;
/**
* 初始化配置
*/
public function __construct()
{
$config = [
'app_id' => 'wx4837bd88b6xxxxx',
'secret' => 'c8fe4278064b22d722682xxxxx',
// 下面為可選項(xiàng)
// 指定 API 調(diào)用返回結(jié)果的類(lèi)型:array(default)/collection/object/raw/自定義類(lèi)名
'response_type' => 'array',
];
$this->app = Factory::miniProgram($config);
}
/**
* 文本安全內(nèi)容檢測(cè)(敏感詞檢測(cè))
*
* @param string $content 文本內(nèi)容
*/
public function checkText(string $content)
{
$result = $this->app->content_security->checkText($content);
if (isset($result['errcode']) && $result['errcode'] == 87014) {
return false;//含有非法內(nèi)容
} else {
return true;// 內(nèi)容安全
}
}
/**
* 圖片內(nèi)容安全檢測(cè)(敏感圖檢測(cè))
*
* @param string $image 絕對(duì)路徑圖片地址
*/
public function checkImage(string $image)
{
$result = $this->app->content_security->checkImage($image);
if (isset($result['errcode']) && $result['errcode'] == 87014) {
return false;//含有非法內(nèi)容
} else {
return true;// 內(nèi)容安全
}
}
}
邏輯層
<?php
namespace app\logic;
use app\lib\MiniProgram;
class WeChat
{
// +------------------------------------------------------------
// | 小程序
// +------------------------------------------------------------
/**
* 敏感詞檢測(cè)
*
* @param string $content
* @return boolean true 內(nèi)容安全
*/
public static function checkText(string $content)
{
return app(MiniProgram::class)->checkText($content);
}
/**
* 敏感圖檢測(cè)
*
* @param string $image
*/
public static function checkImage(string $image)
{
return app(MiniProgram::class)->checkImage($image);
}
}
自定義函數(shù)
/**
* 拋出異常
*
* @param string $msg
* @param integer $code
*/
function fault(string $msg = "", int $code = 201)
{
throw new \Exception($msg, $code);
}