腾讯云文本内容、图片内容安全校验接口
腾讯内容安全接口繁多,有些已经废弃,使用时一定注意查看官方文档。
由于内容安全引起的问题非常多,给运营者、商家、平台都造成了极大的风险,目前微信小程序发布新版本,平台已经强制要求接入内容安全校验接口,否则无法审核发布,一般都需要接入文本和图片内容检查,下面从这2个接口来分享。
一、文本
废话不多说,先来看代码
public static function msgSecCheck($content) { $content = substr($content, 0, 15000); //限制内容长度 try { $cred = new Credential(’你的SecretID‘,'你的SecretKey'); $httpProfile = new HttpProfile(); $httpProfile->setEndpoint("cms.tencentcloudapi.com"); $clientProfile = new ClientProfile(); $clientProfile->setHttpProfile($httpProfile); $client = new CmsClient($cred, "ap-guangzhou", $clientProfile); $req = new TextModerationRequest(); $params = array( "Content" => base64_encode($content), //需要base64编码 ); $req->fromJsonString(json_encode($params)); $resp = $client->TextModeration($req); //print_r($resp); //print_r($resp->toJsonString()); if ($resp->Data->EvilFlag != 0) { //TODO: log //msgSecCheck: failed, EvilType=".$resp->Data->EvilType.', Keywords='.var_export($resp->Data->Keywords, true) return false; } } catch(TencentCloudSDKException $e) { //TODO: log //msgSecCheck: exception, content=$content, exception msg=$e->getMessage() return false; } return true; }
代码比较简单,需要注意的地方已经添加注释信息,注意跟踪审核失败的日志排查问题。
二、图片
public static function imgSecCheck($imgs) { //图片需要使用http公网可访问链接,否则无法校验 foreach ($imgs as $img) { try { $cred = new Credential(’你的SecretID‘,'你的SecretKey'); $httpProfile = new HttpProfile(); $httpProfile->setEndpoint("cms.tencentcloudapi.com"); $clientProfile = new ClientProfile(); $clientProfile->setHttpProfile($httpProfile); $client = new CmsClient($cred, "ap-guangzhou", $clientProfile); $req = new ImageModerationRequest(); $params = array( 'FileUrl' => $img, ); $req->fromJsonString(json_encode($params)); $resp = $client->ImageModeration($req); //print_r($resp); //print_r($resp->toJsonString()); if ($resp->Data->EvilFlag != 0) { //TODO: log //imgSecCheck: failed, EvilType=$resp->Data->EvilType return false; } } catch(TencentCloudSDKException $e) { //TODO: log //imgSecCheck: exception, img=$img, exception msg=$e->getMessage() return false; } } return true; }
图片每次只能校验一张,如有多张图片需要循环调用,可自行修改此处循环逻辑,例子代码使用的是图片url链接,接口也支持base64方式,可根据文档修改。
注意:以上接口需要引入腾讯云SDK,以下是composer.json内容,因为整个代码库非常大,内容安全只需cms库即可,可以节省代码包大小。
{ "require": { "tencentcloud/cms": "^3.0" } }
目录效果截图
产品使用中效果图
本次分享结束,下次给大家分享珊瑚安全接口,价格相对更低,是微信官方在原内容安全接口的升级产品,官方强烈推荐。
本文是微擎百科入驻作者原创文章,如若转载请联系作者授权,发私信联系作者