Skip to content

Commit

Permalink
feat:新增小程序内容安全检测接口
Browse files Browse the repository at this point in the history
  • Loading branch information
XueSiLf authored and Player626 committed Dec 15, 2021
1 parent df90950 commit bdbaacf
Show file tree
Hide file tree
Showing 8 changed files with 294 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/MiniProgram/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
* @property Auth\Client $auth
* @property Base\Client $base
* @property Broadcast\Client $broadcast
* @property ContentSecurity\Client $contentSecurity
* @property CustomerService\Client $customerService
* @property DataCube\Client $dataCube
* @property Express\Client $express
Expand Down Expand Up @@ -49,6 +50,7 @@ class Application extends ServiceContainer
const Auth = 'auth';
const Base = 'base';
const Broadcast = 'broadcast';
const ContentSecurity = 'contentSecurity';
const CustomerService = 'customerService';
const DataCube = "dataCube";
const Express = "express";
Expand Down
127 changes: 127 additions & 0 deletions src/MiniProgram/ContentSecurity/Client.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
<?php

namespace EasySwoole\WeChat\MiniProgram\ContentSecurity;

use EasySwoole\WeChat\Kernel\Exceptions\InvalidArgumentException;
use EasySwoole\WeChat\Kernel\ServiceProviders;
use EasySwoole\WeChat\MiniProgram\BaseClient;

/**
* Class Client
* @package EasySwoole\WeChat\MiniProgram\ContentSecurity
* @author: XueSi
* @email: <[email protected]>
* doc link: https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/sec-check/security.imgSecCheck.html
* desc 内容安全相关接口
*
*/
class Client extends BaseClient
{
/**
* imgSecurityCheck
* 校验一张图片是否含有违法违规内容
* doc link: https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/sec-check/security.imgSecCheck.html
*
* @param string $path
* @return mixed
* @throws InvalidArgumentException
* @throws \EasySwoole\WeChat\Kernel\Exceptions\HttpException
*/
public function checkImg(string $path)
{
if (!file_exists($path) || !is_readable($path)) {
throw new InvalidArgumentException(sprintf("File does not exist, or the file is unreadable: '%s'", $path));
}

$client = $this->getClient()
->setMethod('POST')
->addFile($path, 'media');

$response = $client->send($this->buildUrl(
'/wxa/img_sec_check',
[
'access_token' => $this->app[ServiceProviders::AccessToken]->getToken(),
]
));

$this->checkResponse($response, $parseData);

return $parseData;
}

/**
* mediaCheckAsync
* 异步校验图片/音频是否含有违法违规内容。
* doc link: https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/sec-check/security.mediaCheckAsync.html
*
* @param string $mediaUrl
* @param int $mediaType
* @param string $openId
* @param int $scene
* @param int $version
* @return mixed
* @throws InvalidArgumentException
* @throws \EasySwoole\WeChat\Kernel\Exceptions\HttpException
*/
public function checkMediaAsync(string $mediaUrl, int $mediaType, string $openId, int $scene, int $version = 2)
{
if (!in_array($mediaType, [1, 2], true)) {
throw new InvalidArgumentException("The value of parameter mediaType is illegal!");
}

if (!in_array($scene, [1, 2, 3, 4], true)) {
throw new InvalidArgumentException("The value of parameter scene is illegal!");
}

$params = [
'media_url' => $mediaUrl,
'media_type' => $mediaType,
'version' => $version,
'openid' => $openId,
'scene' => $scene
];

$response = $this->getClient()
->setMethod('POST')
->setBody($this->jsonDataToStream($params))
->send($this->buildUrl(
'/wxa/media_check_async',
['access_token' => $this->app[ServiceProviders::AccessToken]->getToken()])
);

$this->checkResponse($response, $parseData);

return $parseData;
}

/**
* msgSecurityCheck
* 检查一段文本是否含有违法违规内容。
* doc link: https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/sec-check/security.msgSecCheck.html
*
* @param array $params
* @return mixed
* @throws InvalidArgumentException
* @throws \EasySwoole\WeChat\Kernel\Exceptions\HttpException
*/
public function checkMsg(array $params)
{
if (!isset($params['scene']) || !in_array($params['scene'], [1, 2, 3, 4], true)) {
throw new InvalidArgumentException("The value of parameter scene is illegal!");
}

$params['version'] = 2;

$response = $this->getClient()
->setMethod('POST')
->setBody($this->jsonDataToStream($params))
->send($this->buildUrl(
'/wxa/msg_sec_check',
['access_token' => $this->app[ServiceProviders::AccessToken]->getToken()])
);

$this->checkResponse($response, $parseData);

return $parseData;
}
}
17 changes: 17 additions & 0 deletions src/MiniProgram/ContentSecurity/ServiceProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

namespace EasySwoole\WeChat\MiniProgram\ContentSecurity;

use EasySwoole\WeChat\MiniProgram\Application;
use Pimple\Container;
use Pimple\ServiceProviderInterface;

class ServiceProvider implements ServiceProviderInterface
{
public function register(Container $app)
{
$app[Application::ContentSecurity] = function ($app) {
return new Client($app);
};
}
}
105 changes: 105 additions & 0 deletions tests/MiniProgram/ContentSecurity/ClientTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
<?php
/**
* Created by PhpStorm.
* User: XueSi
* Email: <[email protected]>
* Date: 2021/12/01
* Time: 20:13
*/

namespace EasySwoole\WeChat\Tests\MiniProgram\ContentSecurity;

use EasySwoole\WeChat\Kernel\ServiceContainer;
use EasySwoole\WeChat\MiniProgram\ContentSecurity\Client;
use EasySwoole\WeChat\Tests\Mock\Message\Status;
use EasySwoole\WeChat\Tests\TestCase;
use Psr\Http\Message\ServerRequestInterface;

class ClientTest extends TestCase
{
public function testCheckImg()
{
$response = $this->buildResponse(Status::CODE_OK, $this->readMockResponseJson('checkImg.json'));

$app = $this->mockAccessToken(new ServiceContainer([
'appId' => 'mock_appid',
'appSecret' => 'mock_secret'
]));

$app = $this->mockHttpClient(function (ServerRequestInterface $request) {
$this->assertEquals('POST', $request->getMethod());
$this->assertEquals('/wxa/img_sec_check', $request->getUri()->getPath());
$this->assertEquals('access_token=mock_access_token', $request->getUri()->getQuery());
}, $response, $app);

$client = new Client($app);

$ret = $client->checkImg(__DIR__ . '/mock_data/mock_image.jpg');

$this->assertIsArray($ret);

$this->assertSame(json_decode($this->readMockResponseJson('checkImg.json'), true), $ret);
}

public function testCheckMediaAsync()
{
$response = $this->buildResponse(Status::CODE_OK, $this->readMockResponseJson('checkMediaAsync.json'));

$app = $this->mockAccessToken(new ServiceContainer([
'appId' => 'mock_appid',
'appSecret' => 'mock_secret'
]));

$app = $this->mockHttpClient(function (ServerRequestInterface $request) {
$this->assertEquals('POST', $request->getMethod());
$this->assertEquals('/wxa/media_check_async', $request->getUri()->getPath());
$this->assertEquals('access_token=mock_access_token', $request->getUri()->getQuery());
}, $response, $app);

$client = new Client($app);

$mediaUrl = 'https://developers.weixin.qq.com/miniprogram/assets/images/[email protected]';
$mediaType = 2;
$openId = 'OPENID';
$scene = 1;

$ret = $client->checkMediaAsync($mediaUrl, $mediaType, $openId, $scene);

$this->assertIsArray($ret);

$this->assertSame(json_decode($this->readMockResponseJson('checkMediaAsync.json'), true), $ret);
}

public function testCheckMsg()
{
$response = $this->buildResponse(Status::CODE_OK, $this->readMockResponseJson('checkMsg.json'));

$app = $this->mockAccessToken(new ServiceContainer([
'appId' => 'mock_appid',
'appSecret' => 'mock_secret'
]));

$app = $this->mockHttpClient(function (ServerRequestInterface $request) {
$this->assertEquals('POST', $request->getMethod());
$this->assertEquals('/wxa/msg_sec_check', $request->getUri()->getPath());
$this->assertEquals('access_token=mock_access_token', $request->getUri()->getQuery());
}, $response, $app);

$client = new Client($app);

$ret = $client->checkMsg([
'openid' => 'OPENID',
'scene' => 1,
'content' => 'hello world!'
]);

$this->assertIsArray($ret);

$this->assertSame(json_decode($this->readMockResponseJson('checkMsg.json'), true), $ret);
}

private function readMockResponseJson($filename)
{
return file_get_contents(__DIR__ . '/mock_data/' . $filename);
}
}
4 changes: 4 additions & 0 deletions tests/MiniProgram/ContentSecurity/mock_data/checkImg.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"errcode": 0,
"errmsg": "ok"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"errcode": 0,
"errmsg": "ok",
"trace_id": "967e945cd8a3e458f3c74dcb886068e9"
}
34 changes: 34 additions & 0 deletions tests/MiniProgram/ContentSecurity/mock_data/checkMsg.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"errcode": 0,
"errmsg": "ok",
"result": {
"suggest": "risky",
"label": 20001
},
"detail": [
{
"strategy": "content_model",
"errcode": 0,
"suggest": "risky",
"label": 20006,
"prob": 90
},
{
"strategy": "keyword",
"errcode": 0,
"suggest": "pass",
"label": 20006,
"level": 20,
"keyword": "命中的关键词1"
},
{
"strategy": "keyword",
"errcode": 0,
"suggest": "risky",
"label": 20006,
"level": 90,
"keyword": "命中的关键词2"
}
],
"trace_id": "60ae120f-371d5872-7941a05b"
}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit bdbaacf

Please sign in to comment.