ContentGreen.php 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. namespace App\Servers\Aliyun;
  3. use AlibabaCloud\SDK\Green\V20220302\Green;
  4. use \Exception;
  5. use AlibabaCloud\Tea\Exception\TeaError;
  6. use AlibabaCloud\Tea\Utils\Utils;
  7. use Darabonba\OpenApi\Models\Config;
  8. use AlibabaCloud\SDK\Green\V20220302\Models\TextModerationRequest;
  9. use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
  10. use App\Facades\Servers\Logs\Log;
  11. /**
  12. * 阿里内容安全
  13. * @author 唐远望
  14. * @version 1.0
  15. * @date 2025-12-22
  16. */
  17. class ContentGreen
  18. {
  19. function __construct() {}
  20. /**
  21. * 使用AK&SK初始化账号Client
  22. * @return Green Client
  23. */
  24. public static function createClient()
  25. {
  26. // 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考。
  27. // 建议使用更安全的 STS 方式,更多鉴权访问方式请参见:https://help.aliyun.com/document_detail/311677.html。
  28. $config = new Config([
  29. // 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
  30. "accessKeyId" => config('aliyun.accessKeyId', ''),
  31. // 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
  32. "accessKeySecret" => config('aliyun.accessKeySecret', '')
  33. ]);
  34. // Endpoint 请参考 https://api.aliyun.com/product/Green
  35. $config->endpoint = "green-cip.cn-shenzhen.aliyuncs.com";
  36. return new Green($config);
  37. }
  38. /**
  39. * @param string[] $args
  40. * @return void
  41. */
  42. public function main($content, $service = 'nickname_detection')
  43. {
  44. $client = self::createClient();
  45. $serviceParameters = [
  46. 'content' => $content
  47. ];
  48. $textModerationRequest = new TextModerationRequest([
  49. "service" => $service,
  50. "serviceParameters" => json_encode($serviceParameters),
  51. ]);
  52. try {
  53. // 复制代码运行请自行打印 API 的返回值
  54. $response = $client->textModerationWithOptions($textModerationRequest, new RuntimeOptions([]));
  55. if ($response->body->code == 200) {
  56. return $response->body->data->descriptions;
  57. }
  58. return false;
  59. } catch (Exception $error) {
  60. if (!($error instanceof TeaError)) {
  61. $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
  62. }
  63. // 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
  64. // 错误 message
  65. var_dump($error->message);
  66. // 诊断地址
  67. var_dump($error->data["Recommend"]);
  68. Utils::assertAsString($error->message);
  69. }
  70. }
  71. }