ContentGreen.php 2.7 KB

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