阿里云绿网内容安全API


PHP版本:


define('AccessKeyId', 'AccessKeyId');
define('AccessKeySecret', 'AccessKeySecret');

/**
 *  获取签名
 */
function getSign($md5, $date, $rand)
{
    $data = array(
        "x-acs-version" => "2018-05-09",
        "x-acs-signature-nonce" => $rand,
        "x-acs-signature-version" => '1.0',
        "x-acs-signature-method" => "HMAC-SHA1",
    );
    ksort($data);
    $signUrl = '';
    foreach ($data as $k => $v) {
        $signUrl .= $k . ':' . $v . "\n";
    }
    $signUrl = sprintf("POST\napplication/json\n%s\napplication/json\n%s\n%s/green/text/scan", $md5, $date, $signUrl);
    $sign = base64_encode(hash_hmac('sha1', $signUrl, AccessKeySecret, true));
    return $sign;
}

/**
 *  发起 HTTP 请求
 */
function httpRequest($url, $body)
{
    $date = gmdate('D, d M Y H:i:s T');
    $md5 = base64_encode(md5($body, true));
    $rand = md5(rand(10000, 99999) . time());
    $sign = getSign($md5, $date, $rand);
    $header = array(
        'Accept: application/json',
        'Content-Type: application/json',
        'Content-MD5: ' . $md5,
        'Date: ' . $date,
        'x-acs-version: 2018-05-09',
        'x-acs-signature-nonce: ' . $rand,
        'x-acs-signature-version: 1.0',
        'x-acs-signature-method: HMAC-SHA1',
        'Authorization: acs ' . AccessKeyId . ':' . $sign,
    );

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
    $data = curl_exec($curl);
    $error = curl_error($curl);
    curl_close($curl);
    if ($error) {
        return $error;
    } else {
        return $data;
    }
}

/**
 *  内容检测
 */
function greenTextScan($content) {
    $api = 'https://green.cn-beijing.aliyuncs.com/green/text/scan';
    $body = [
        'scenes' => ['antispam'],
        'tasks' => []
    ];
    foreach($content as $k=>$v) {
        $body['tasks'][] = [
            'dataId' => $k,
            'content' => $v
        ];
    }
    return httpRequest($api, json_encode($body));
}

function main()
{
    echo greenTextScan(['需要检测的文本']);
}

main();