| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- <?php
- namespace App\Servers\Aliyun;
- use AlibabaCloud\SDK\Green\V20220302\Green;
- use \Exception;
- use AlibabaCloud\Tea\Exception\TeaError;
- use AlibabaCloud\Tea\Utils\Utils;
- use Darabonba\OpenApi\Models\Config;
- use AlibabaCloud\SDK\Green\V20220302\Models\TextModerationRequest;
- use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
- use App\Facades\Servers\Logs\Log;
- /**
- * 阿里内容安全
- * @author 唐远望
- * @version 1.0
- * @date 2025-12-22
- */
- class ContentGreen
- {
- function __construct() {}
- /**
- * 使用AK&SK初始化账号Client
- * @return Green Client
- */
- public static function createClient()
- {
- // 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考。
- // 建议使用更安全的 STS 方式,更多鉴权访问方式请参见:https://help.aliyun.com/document_detail/311677.html。
- $config = new Config([
- // 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
- "accessKeyId" => config('aliyun.accessKeyId', ''),
- // 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
- "accessKeySecret" => config('aliyun.accessKeySecret', '')
- ]);
- // Endpoint 请参考 https://api.aliyun.com/product/Green
- $config->endpoint = "green-cip.cn-shenzhen.aliyuncs.com";
- return new Green($config);
- }
- /**
- * @param string[] $args
- * @return void
- */
- public function main($content, $service = 'nickname_detection')
- {
- $client = self::createClient();
- $serviceParameters = [
- 'content' => $content
- ];
- $textModerationRequest = new TextModerationRequest([
- "service" => $service,
- "serviceParameters" => json_encode($serviceParameters),
- ]);
- try {
- // 复制代码运行请自行打印 API 的返回值
- $response = $client->textModerationWithOptions($textModerationRequest, new RuntimeOptions([]));
- if ($response->body->code == 200) {
- return $response->body->data->descriptions;
- }
- return false;
- } catch (Exception $error) {
- if (!($error instanceof TeaError)) {
- $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
- }
- // 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
- // 错误 message
- var_dump($error->message);
- // 诊断地址
- var_dump($error->data["Recommend"]);
- Utils::assertAsString($error->message);
- }
- }
- }
|