首先,要有一个百度云账号并获取到自己的API Key和Secret Key
上代码:在其中更改自己的API Key和Secret Key即可
最终在审核方法下方根据自己的需求进行逻辑处理
<?php
namespace app\api\controller;
use app\Request;
class Audit
{
public function contentAudit(Request $request)
{
$content = $request->post('content');
$token = $this->getAccessToken('ApiKey ', 'SecretKey ');
$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);
print_r($res);die;
}
public function imageAudit(Request $request)
{
$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);
print_r($res);
}
function curlPost($url = '', $param = '')
{
if (empty($url) || empty($param)) {
return false;
}
$postUrl = $url;
$curlPost = $param;
$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);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
$data = curl_exec($curl);
curl_close($curl);
return $data;
}
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;
}
}