URL risk detection integration

更新时间:
复制 MD 格式

You can call the URL Risk Detection service using an SDK or native HTTPS requests. We recommend using an SDK to simplify the integration process, as it handles details like signature verification and request body construction. This topic describes how to integrate the URL Risk Detection service.

Step 1: Activate the service

Go to the Activate Service page to activate Content Moderation Enhanced Edition.

After you activate Content Moderation Enhanced Edition, the default billing method is pay-as-you-go. You are billed daily for your actual usage. If you do not call the service, no fees are incurred. After you integrate and use the API, the system automatically generates bills based on your usage. For more information, see Billing Details. You can also purchase a resource package, which offers tiered discounts and is ideal for users with predictable or high usage.

Step 2: Create and authorize a RAM user

Before you integrate the SDK, create an identity for making API calls, obtain its access credentials, and grant it permissions to access cloud resources. This guide uses a RAM user as the identity, an AccessKey as the credential, and grants the user permission to call the URL Risk Detection service. For more information, see Integrate SDK.

  1. Log in to the RAM console with your Alibaba Cloud account (root account) or a RAM user that has administrative permissions.

  2. Create a RAM user, select OpenAPI Call Access, and record the AccessKey generated for the RAM user. For more information, see Create a RAM user.

  3. Grant the AliyunYundunGreenWebFullAccess system policy to the RAM user. For more information, see Manage RAM user permissions.

Step 3: Install and integrate URL risk detection

This topic provides SDKs for asynchronous URL detection. For SDKs that support synchronous URL detection, see SDK integration guide for Content Moderation 2.0. The supported regions are:

Region

Public endpoint

Internal endpoint

Supported services

China (Shanghai)

green-cip.cn-shanghai.aliyuncs.com

green-cip-vpc.cn-shanghai.aliyuncs.com

url_detection, url_detection_pro

China (Hangzhou)

green-cip.cn-hangzhou.aliyuncs.com

green-cip-vpc.cn-hangzhou.aliyuncs.com

China (Beijing)

green-cip.cn-beijing.aliyuncs.com

green-cip-vpc.cn-beijing.aliyuncs.com

url_detection

China (Hangzhou)

green-cip.cn-hangzhou.aliyuncs.com

green-cip-vpc.cn-hangzhou.aliyuncs.com

China (Shenzhen)

green-cip.cn-shenzhen.aliyuncs.com

green-cip-vpc.cn-shenzhen.aliyuncs.com

China (Chengdu)

green-cip.cn-chengdu.aliyuncs.com

Not available

Note

If you need SDK sample code for other languages, you can use the debugging tools in OpenAPI Developer Portal. The portal automatically generates SDK sample code for the API you are debugging. You can debug the following APIs online:

Alibaba Cloud SDKs create default credentials by reading the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables. When you call an API operation, the program reads your AccessKey from these variables and automatically completes authentication. Before you use SDK sample code, you must configure the environment variables. For more information, see Configure authentication credentials.

The following SDKs are for asynchronous URL detection. For SDKs that support synchronous URL detection, see SDK integration guide for Content Moderation 2.0.

Java SDK

Add the following dependency to your pom.xml file to use the SDK in your Maven project.

  1. In dependencies, add the following dependencies:

    <dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>green20220302</artifactId>
      <version>3.3.3</version>
    </dependency>
  2. Integrate the Java SDK.

    • Sample code for submitting a URL risk detection task

      import com.alibaba.fastjson.JSON;
      import com.aliyun.green20220302.Client;
      import com.aliyun.green20220302.models.UrlAsyncModerationRequest;
      import com.aliyun.green20220302.models.UrlAsyncModerationResponse;
      import com.aliyun.green20220302.models.UrlAsyncModerationResponseBody;
      import com.aliyun.teaopenapi.models.Config;
      import com.aliyun.teautil.models.RuntimeOptions;
      
      import java.util.HashMap;
      import java.util.Map;
      import java.util.UUID;
      
      public class UrlAsyncModerationDemo {
      
          /**
           * Create a client.
           *
           * @param accessKeyId
           * @param accessKeySecret
           * @param endpoint
           * @return
           * @throws Exception
           */
          public static Client createClient(String accessKeyId, String accessKeySecret, String endpoint) throws Exception {
              Config config = new Config();
              config.setAccessKeyId(accessKeyId);
              config.setAccessKeySecret(accessKeySecret);
              // Configure an HTTP proxy.
              // config.setHttpProxy("http://10.10.xx.xx:xxxx");
              // Configure an HTTPS proxy.
              // config.setHttpsProxy("https://10.10.xx.xx:xxxx");
              // Modify the region and endpoint based on your business requirements.
              config.setEndpoint(endpoint);
              return new Client(config);
          }
      
          public static UrlAsyncModerationResponse invokeFunction(String accessKeyId, String accessKeySecret, String endpoint) throws Exception {
              // We recommend that you reuse the client instance to improve performance by avoiding repeated connection establishment.
              Client client = createClient(accessKeyId, accessKeySecret, endpoint);
      
              // Create a RuntimeOptions instance and configure runtime parameters.
              RuntimeOptions runtime = new RuntimeOptions();
      
              // Construct the detection parameters.
              Map<String, String> serviceParameters = new HashMap<>();
              // The publicly accessible URL to be detected.
              serviceParameters.put("url", "https://www.aliyun.com/");
              // A unique identifier for the data to be detected.
              serviceParameters.put("dataId", UUID.randomUUID().toString());
              // The callback URL that receives the detection result.
              serviceParameters.put("callback", "http://www.aliyun.com");
              // A random string used to sign callback notification requests.
              serviceParameters.put("seed", "seedCode");
              // The algorithm used to sign callback notifications when a callback URL is used.
              serviceParameters.put("cryptType", "SM3");
      
              UrlAsyncModerationRequest request = new UrlAsyncModerationRequest();
              // The service for URL detection. Example: url_detection_pro.
              request.setService("url_detection_pro");
              request.setServiceParameters(JSON.toJSONString(serviceParameters));
      
              UrlAsyncModerationResponse response = null;
              try {
                  response = client.urlAsyncModerationWithOptions(request, runtime);
              } catch (Exception e) {
                  e.printStackTrace();
              }
              return response;
          }
      
          public static void main(String[] args) throws Exception {
              /**
               * An AccessKey of an Alibaba Cloud account has full permissions on all APIs. We recommend that you use a RAM user to make API calls or perform routine O&M.
               * We strongly recommend that you do not hard-code your AccessKey ID and AccessKey Secret in your project code. Otherwise, your AccessKeys may be leaked, which poses a threat to the security of your resources.
               * Common methods for retrieving environment variables:
               * Method 1:
               *     Get the AccessKey ID of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Get the AccessKey secret of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               * Method 2:
               *     Get the AccessKey ID of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Get the AccessKey secret of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               */
              String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
              String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
              UrlAsyncModerationResponse response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.cn-shanghai.aliyuncs.com");
      
              // Print the detection result.
              if (response != null) {
                  if (response.getStatusCode() == 200) {
                      // The response contains a reqId field. Use this field to query the result of the asynchronous detection task.
                      UrlAsyncModerationResponseBody body = response.getBody();
                      if (body.getCode() == 200) {
                          System.out.println(JSON.toJSONString(body));
                      } else {
                          System.out.println("url moderation not success. code:" + body.getCode());
                      }
                  } else {
                      System.out.println("response not success. status:" + response.getStatusCode());
                  }
              }
          }
      }
    • Sample code for querying the result of a URL risk detection task

      package com.example.demo.cip.image;
      
      import com.alibaba.fastjson.JSON;
      import com.aliyun.green20220302.Client;
      import com.aliyun.green20220302.models.DescribeUrlModerationResultRequest;
      import com.aliyun.green20220302.models.DescribeUrlModerationResultResponse;
      import com.aliyun.teaopenapi.models.Config;
      import com.aliyun.teautil.models.RuntimeOptions;
      
      public class DescribeUrlModerationResultDemo {
          /**
           * Create a client.
           *
           * @param accessKeyId
           * @param accessKeySecret
           * @param endpoint
           * @return
           * @throws Exception
           */
          public static Client createClient(String accessKeyId, String accessKeySecret, String endpoint) throws Exception {
              Config config = new Config();
              config.setAccessKeyId(accessKeyId);
              config.setAccessKeySecret(accessKeySecret);
              // Configure an HTTP proxy.
              // config.setHttpProxy("http://10.10.xx.xx:xxxx");
              // Configure an HTTPS proxy.
              // config.setHttpsProxy("https://10.10.xx.xx:xxxx");
              // Modify the region and endpoint based on your business requirements.
              config.setEndpoint(endpoint);
              return new Client(config);
          }
      
          public static DescribeUrlModerationResultResponse invokeFunction(String accessKeyId, String accessKeySecret, String endpoint) throws Exception {
              // We recommend that you reuse the client instance to improve performance by avoiding repeated connection establishment.
              Client client = createClient(accessKeyId, accessKeySecret, endpoint);
      
              // Create a RuntimeOptions instance and configure runtime parameters.
              RuntimeOptions runtime = new RuntimeOptions();
      
              // Construct the request parameters.
              DescribeUrlModerationResultRequest request = new DescribeUrlModerationResultRequest();
              // The reqId returned from submitting the asynchronous detection task. Example: DFEXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXX44
              request.setReqId("DFEXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXX44");
      
              DescribeUrlModerationResultResponse response = null;
              try {
                  response = client.describeUrlModerationResultWithOptions(request, runtime);
              } catch (Exception e) {
                  e.printStackTrace();
              }
              return response;
          }
      
          public static void main(String[] args) throws Exception {
              /**
               * An AccessKey of an Alibaba Cloud account has full permissions on all APIs. We recommend that you use a RAM user to make API calls or perform routine O&M.
               * We strongly recommend that you do not hard-code your AccessKey ID and AccessKey Secret in your project code. Otherwise, your AccessKeys may be leaked, which poses a threat to the security of your resources.
               * Common methods for retrieving environment variables:
               * Method 1:
               *     Get the AccessKey ID of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Get the AccessKey secret of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               * Method 2:
               *     Get the AccessKey ID of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Get the AccessKey secret of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               */
              String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
              String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
              DescribeUrlModerationResultResponse response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.cn-shanghai.aliyuncs.com");
      
              // Print the detection result.
              if (response != null) {
                  if (response.getStatusCode() == 200) {
                      System.out.println(JSON.toJSONString(response.getBody()));
                  } else {
                      System.out.println("response not success. status:" + response.getStatusCode());
                  }
              }
      
          }
      }

Python SDK

Python 3.6 or later is required.

  1. Run the following command to install the SDK:

    pip install alibabacloud_green20220302==3.2.4
  2. Integrate the Python SDK.

    • Sample code for submitting a URL risk detection task

      from alibabacloud_green20220302.client import Client
      from alibabacloud_green20220302 import models
      from alibabacloud_tea_openapi.models import Config
      from alibabacloud_tea_util import models as util_models
      import json
      import os
      import uuid
      
      
      # Create a client.
      def create_client(access_key_id, access_key_secret, endpoint):
          config = Config(
              access_key_id=access_key_id,
              access_key_secret=access_key_secret,
              # Configure an HTTP proxy.
              # http_proxy='http://10.10.xx.xx:xxxx',
              # Configure an HTTPS proxy.
              # https_proxy='https://10.10.xx.xx:xxxx',
              # Modify the region and endpoint based on your business requirements.
              endpoint=endpoint
          )
          return Client(config)
      
      
      def invoke_function(access_key_id, access_key_secret, endpoint):
          # We recommend that you reuse the client instance to improve performance by avoiding repeated connection establishment.
          client = create_client(access_key_id, access_key_secret, endpoint)
          # Create a RuntimeOptions instance and configure runtime parameters.
          runtime = util_models.RuntimeOptions()
      
          # Construct the detection parameters.
          service_parameters = {
              # The publicly accessible URL to be detected.
              'url': 'https://www.aliyun.com/',
              # A unique identifier for the data to be detected.
              'dataId': str(uuid.uuid1()),
              # The callback URL that receives the detection result.
              'callback': 'http://www.aliyun.com',
              # A random string used to sign callback notification requests.
              'seed': 'seedCode',
              # The algorithm used to sign callback notifications when a callback URL is used.
              'cryptType': 'SM3'
          }
      
          url_image_moderation_request = models.UrlAsyncModerationRequest(
              # The service for URL detection. Example: url_detection_pro.
              service='url_detection_pro',
              service_parameters=json.dumps(service_parameters)
          )
      
          try:
              return client.url_async_moderation_with_options(url_image_moderation_request, runtime),
          except Exception as err:
              print(err)
      
      
      if __name__ == '__main__':
          # An AccessKey of an Alibaba Cloud account has full permissions on all APIs. We recommend that you use a RAM user to make API calls or perform routine O&M.
          # We strongly recommend that you do not hard-code your AccessKey ID and AccessKey Secret in your project code. Otherwise, your AccessKeys may be leaked, which poses a threat to the security of your resources.
          # We recommend that you retrieve the AccessKey ID and AccessKey secret from environment variables.
          access_key_id = os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
          access_key_secret = os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
          # Modify the region and endpoint based on your business requirements.
          response = invoke_function(access_key_id, access_key_secret, 'green-cip.cn-shanghai.aliyuncs.com')
          # Print the result.
          if len(response) >= 1:
              if response[0].status_code == 200:
                  # The call was successful.
                  # Get the result ReqId.
                  result = response[0].body
                  print('response success. result:{}'.format(result))
                  if result.code == 200:
                      result_data = result.data
                      print('result: {}'.format(result_data))
              else:
                  print('response not success. status:{} ,result:{}'.format(response.status_code, response))
    • Sample code for querying the result of a URL risk detection task

      from alibabacloud_green20220302.client import Client
      from alibabacloud_green20220302 import models
      from alibabacloud_tea_openapi.models import Config
      from alibabacloud_tea_util import models as util_models
      import os
      
      
      # Create a client.
      def create_client(access_key_id, access_key_secret, endpoint):
          config = Config(
              access_key_id=access_key_id,
              access_key_secret=access_key_secret,
              # Configure an HTTP proxy.
              # http_proxy='http://10.10.xx.xx:xxxx',
              # Configure an HTTPS proxy.
              # https_proxy='https://10.10.xx.xx:xxxx',
              # Modify the region and endpoint based on your business requirements.
              endpoint=endpoint
          )
          return Client(config)
      
      
      def invoke_function(access_key_id, access_key_secret, endpoint):
          # We recommend that you reuse the client instance to improve performance by avoiding repeated connection establishment.
          client = create_client(access_key_id, access_key_secret, endpoint)
          # Create a RuntimeOptions instance and configure runtime parameters.
          runtime = util_models.RuntimeOptions()
      
          # Construct the request parameters.
          describe_result_request = models.DescribeUrlModerationResultRequest(
              # The reqId returned from submitting the asynchronous detection task. Example: DFEXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXX44
              req_id='DFEXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXX44',
          )
      
          try:
              return client.describe_url_moderation_result_with_options(describe_result_request, runtime)
          except Exception as err:
              print(err)
      
      
      if __name__ == '__main__':
          # An AccessKey of an Alibaba Cloud account has full permissions on all APIs. We recommend that you use a RAM user to make API calls or perform routine O&M.
          # We strongly recommend that you do not hard-code your AccessKey ID and AccessKey Secret in your project code. Otherwise, your AccessKeys may be leaked, which poses a threat to the security of your resources.
          # We recommend that you retrieve the AccessKey ID and AccessKey secret from environment variables.
          access_key_id = os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
          access_key_secret = os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
          # Modify the region and endpoint based on your business requirements.
          response = invoke_function(access_key_id, access_key_secret, 'green-cip.cn-shanghai.aliyuncs.com')
          # Print the result.
          if response is not None:
              if response.status_code == 200:
                  # The call was successful.
                  # Get the detection result.
                  result = response.body
                  print('response success. result:{}'.format(result))
                  if result.code == 200:
                      result_data = result.data
                      print('result: {}'.format(result_data))
              else:
                  print('response not success. status:{} ,result:{}'.format(response.status_code, response))

PHP SDK

PHP 5.6 or later is required.

  1. Run the following command to install the dependencies:

    composer require alibabacloud/green-20220302 3.2.4
  2. Integrate the PHP SDK.

    • Sample code for submitting a URL risk detection task

      <?php
      require('../../../vendor/autoload.php');
      
      use AlibabaCloud\SDK\Green\V20220302\Models\UrlAsyncModerationResponse;
      use Darabonba\OpenApi\Models\Config;
      use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
      use AlibabaCloud\SDK\Green\V20220302\Green;
      use AlibabaCloud\SDK\Green\V20220302\Models\UrlAsyncModerationRequest;
      
      /**
       * Create a client.
       * @param $accessKeyId
       * @param $accessKeySecret
       * @param $endpoint
       * @return Green
       */
      function create_client($accessKeyId, $accessKeySecret, $endpoint): Green
      {
          $config = new Config([
              "accessKeyId" => $accessKeyId,
              "accessKeySecret" => $accessKeySecret,
              // Configure an HTTP proxy.
              // "httpProxy" => "http://10.10.xx.xx:xxxx",
              // Configure an HTTPS proxy.
              // "httpsProxy" => "https://10.10.xx.xx:xxxx",
              "endpoint" => $endpoint,
          ]);
          return new Green($config);
      }
      
      /**
       * Submit a detection task.
       * @param $accessKeyId
       * @param $accessKeySecret
       * @param $endpoint
       * @return UrlAsyncModerationResponse
       */
      function invoke($accessKeyId, $accessKeySecret, $endpoint): UrlAsyncModerationResponse
      {
          // We recommend that you reuse the client instance to improve performance by avoiding repeated connection establishment.
          $client = create_client($accessKeyId, $accessKeySecret, $endpoint);
          // Create a RuntimeOptions instance and configure runtime parameters.
          $runtime = new RuntimeOptions([]);
          // Construct the detection parameters.
          $request = new UrlAsyncModerationRequest();
          $serviceParameters = array(
              // The publicly accessible URL to be detected.
              'url' => 'https://aliyun.com',
              // A unique identifier for the data to be detected.
              'dataId' => uniqid(),
              // The callback URL that receives the detection result.
              'callback' => 'http://www.aliyun.com',
              // A random string used to sign callback notification requests.
              'seed' => 'seedCode',
              // The algorithm used to sign callback notifications when a callback URL is used.
              'cryptType' => 'SM3'
          );
          // The service for URL detection. Example: url_detection_pro.
          $request->service = "url_detection_pro";
          $request->serviceParameters = json_encode($serviceParameters);
          // Submit the detection task.
          return $client->urlAsyncModerationWithOptions($request, $runtime);
      }
      
      // An AccessKey of an Alibaba Cloud account has full permissions on all APIs. We recommend that you use a RAM user to make API calls or perform routine O&M.
      // We strongly recommend that you do not hard-code your AccessKey ID and AccessKey Secret in your project code. Otherwise, your AccessKeys may be leaked, which poses a threat to the security of your resources.
      // We recommend that you retrieve the AccessKey ID and AccessKey secret from environment variables.
      $accessKeyId = getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
      $accessKeySecret = getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
      // Modify the endpoint based on your business requirements.
      $endpoint = "green-cip.cn-shanghai.aliyuncs.com";
      
      try {
          $response = invoke($accessKeyId, $accessKeySecret, $endpoint);
          // The response contains a reqId field. Use this field to query the result of the asynchronous detection task.
          print_r(json_encode($response->body, JSON_UNESCAPED_UNICODE));
      } catch (Exception $e) {
          var_dump($e->getMessage());
          var_dump($e->getErrorInfo());
          var_dump($e->getLastException());
          var_dump($e->getLastRequest());
      }
    • Sample code for querying the result of a URL risk detection task

      <?php
      require('../../../vendor/autoload.php');
      
      use AlibabaCloud\SDK\Green\V20220302\Models\DescribeUrlModerationResultResponse;
      use Darabonba\OpenApi\Models\Config;
      use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
      use AlibabaCloud\SDK\Green\V20220302\Green;
      use AlibabaCloud\SDK\Green\V20220302\Models\DescribeUrlModerationResultRequest;
      
      /**
       * Create a client.
       * @param $accessKeyId
       * @param $accessKeySecret
       * @param $endpoint
       * @return Green
       */
      function create_client($accessKeyId, $accessKeySecret, $endpoint): Green
      {
          $config = new Config([
              "accessKeyId" => $accessKeyId,
              "accessKeySecret" => $accessKeySecret,
              "endpoint" => $endpoint,
          ]);
          return new Green($config);
      }
      
      /**
       * Submit a detection task.
       * @param $accessKeyId
       * @param $accessKeySecret
       * @param $endpoint
       * @return DescribeUrlModerationResultResponse
       */
      function invoke($accessKeyId, $accessKeySecret, $endpoint): DescribeUrlModerationResultResponse
      {
          // We recommend that you reuse the client instance to improve performance by avoiding repeated connection establishment.
          $client = create_client($accessKeyId, $accessKeySecret, $endpoint);
          // Create a RuntimeOptions instance and configure runtime parameters.
          $runtime = new RuntimeOptions([]);
          // Construct the request parameters.
          $request = new DescribeUrlModerationResultRequest();
          // The reqId returned from submitting the asynchronous detection task. Example: DFEXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXX44
          $request->reqId = "DFEXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXX44";
          // Submit the detection task.
          return $client->describeUrlModerationResultWithOptions($request, $runtime);
      }
      
      // An AccessKey of an Alibaba Cloud account has full permissions on all APIs. We recommend that you use a RAM user to make API calls or perform routine O&M.
      // We strongly recommend that you do not hard-code your AccessKey ID and AccessKey Secret in your project code. Otherwise, your AccessKeys may be leaked, which poses a threat to the security of your resources.
      // We recommend that you retrieve the AccessKey ID and AccessKey secret from environment variables.
      $accessKeyId = getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
      $accessKeySecret = getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
      // Modify the endpoint based on your business requirements.
      $endpoint = "green-cip.cn-shanghai.aliyuncs.com";
      
      try {
          $response = invoke($accessKeyId, $accessKeySecret, $endpoint);
          print_r(json_encode($response->body, JSON_UNESCAPED_UNICODE));
      } catch (Exception $e) {
          var_dump($e->getMessage());
          var_dump($e->getErrorInfo());
          var_dump($e->getLastException());
          var_dump($e->getLastRequest());
      }

Go SDK

  1. Run the following command to install the dependency:

    go get github.com/alibabacloud-go/green-20220302/v3
  2. Integrate the Go SDK.

    • Sample code for submitting a URL risk detection task

      package main
      
      import (
      	"encoding/json"
      	"fmt"
      	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
      	green20220302 "github.com/alibabacloud-go/green-20220302/v3/client"
      	util "github.com/alibabacloud-go/tea-utils/v2/service"
      	"github.com/alibabacloud-go/tea/tea"
      	"github.com/google/uuid"
      	"net/http"
      	"os"
      )
      
      // Create a client.
      func createClient(accessKeyId *string, accessKeySecret *string, endpoint *string) (*green20220302.Client, error) {
      	config := &openapi.Config{
      		/**
      		 * An AccessKey of an Alibaba Cloud account has full permissions on all APIs. We recommend that you use a RAM user to make API calls or perform routine O&M.
      		 * We strongly recommend that you do not hard-code your AccessKey ID and AccessKey Secret in your project code. Otherwise, your AccessKeys may be leaked, which poses a threat to the security of your resources.
      		 * We recommend that you retrieve the AccessKey ID and AccessKey secret from environment variables.
      		 * Get the AccessKey ID of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
      		 * Get the AccessKey secret of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
      		 */
      		AccessKeyId:     accessKeyId,
      		AccessKeySecret: accessKeySecret,
      		// Configure an HTTP proxy.
      		// HttpProxy: tea.String("http://10.10.xx.xx:xxxx"),
      		// Configure an HTTPS proxy.
      		// HttpsProxy: tea.String("https://username:password@xxx.xxx.xxx.xxx:9999"),
      		Endpoint: endpoint,
      	}
      	// We recommend that you reuse the client instance to improve performance by avoiding repeated connection establishment.
      	return green20220302.NewClient(config)
      }
      
      func invoke(accessKeyId *string, accessKeySecret *string, endpoint *string) (_result *green20220302.UrlAsyncModerationResponse, _err error) {
      	// We recommend that you reuse the client instance to improve performance by avoiding repeated connection establishment.
      	client, _err := createClient(accessKeyId, accessKeySecret, endpoint)
      	if _err != nil {
      		return nil, _err
      	}
      	// Create a RuntimeOptions instance and configure runtime parameters. These settings are valid only for requests that use this instance.
      	runtime := &util.RuntimeOptions{}
      
      	// Construct the URL detection request.
      	serviceParameters, _ := json.Marshal(
      		map[string]interface{}{
      			// The publicly accessible URL to be detected.
      			"url": "https://www.aliyun.com",
      			// A unique identifier for the data to be detected.
      			"dataId": uuid.New(),
      			// The callback URL that receives the detection result.
      			"callback": "http://www.aliyun.com",
      			// A random string used to sign callback notification requests.
      			"seed": "seedCode",
      			// The algorithm used to sign callback notifications when a callback URL is used.
      			"cryptType": "SM3",
      		},
      	)
      	imageModerationRequest := &green20220302.UrlAsyncModerationRequest{
      		// The service for URL detection. Example: url_detection_pro.
      		Service:           tea.String("url_detection_pro"),
      		ServiceParameters: tea.String(string(serviceParameters)),
      	}
      
      	return client.UrlAsyncModerationWithOptions(imageModerationRequest, runtime)
      
      }
      
      func main() {
      	/**
      	 * An AccessKey of an Alibaba Cloud account has full permissions on all APIs. We recommend that you use a RAM user to make API calls or perform routine O&M.
      	 * We strongly recommend that you do not hard-code your AccessKey ID and AccessKey Secret in your project code. Otherwise, your AccessKeys may be leaked, which poses a threat to the security of your resources.
      	 * We recommend that you retrieve the AccessKey ID and AccessKey secret from environment variables.
      	 * Get the AccessKey ID of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
      	 * Get the AccessKey secret of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
      	 */
      	var accessKeyId = tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
      	var accessKeySecret = tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
      	// Modify the region and endpoint based on your business requirements.
      	var endpoint = tea.String("green-cip.cn-shanghai.aliyuncs.com")
      	response, _err := invoke(accessKeyId, accessKeySecret, endpoint)
      
      	if response != nil {
      		statusCode := tea.IntValue(tea.ToInt(response.StatusCode))
      		body := response.Body
      		imageModerationResponseData := body.Data
      		if statusCode == http.StatusOK {
      			fmt.Println("response success. response:" + body.String())
      			if tea.IntValue(tea.ToInt(body.Code)) == 200 {
      				// The response contains a ReqId field. Use this field to query the result of the asynchronous detection task.
      				fmt.Println("response ReqId:" + tea.StringValue(imageModerationResponseData.ReqId))
      			} else {
      				fmt.Println("url moderation not success. status" + tea.ToString(body.Code))
      			}
      		} else {
      			fmt.Print("response not success. status:" + tea.ToString(statusCode))
      			fmt.Println("Error:", _err)
      		}
      	}
      }
    • Sample code for querying the result of a URL risk detection task

      package main
      
      import (
      	"fmt"
      	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
      	green20220302 "github.com/alibabacloud-go/green-20220302/v3/client"
      	util "github.com/alibabacloud-go/tea-utils/v2/service"
      	"github.com/alibabacloud-go/tea/tea"
      	"net/http"
      	"os"
      )
      
      // Create a client.
      func createClient(accessKeyId *string, accessKeySecret *string, endpoint *string) (*green20220302.Client, error) {
      	config := &openapi.Config{
      		/**
      		 * An AccessKey of an Alibaba Cloud account has full permissions on all APIs. We recommend that you use a RAM user to make API calls or perform routine O&M.
      		 * We strongly recommend that you do not hard-code your AccessKey ID and AccessKey Secret in your project code. Otherwise, your AccessKeys may be leaked, which poses a threat to the security of your resources.
      		 * We recommend that you retrieve the AccessKey ID and AccessKey secret from environment variables.
      		 * Get the AccessKey ID of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
      		 * Get the AccessKey secret of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
      		 */
      		AccessKeyId:     accessKeyId,
      		AccessKeySecret: accessKeySecret,
      		// Configure an HTTP proxy.
      		// HttpProxy: tea.String("http://10.10.xx.xx:xxxx"),
      		// Configure an HTTPS proxy.
      		// HttpsProxy: tea.String("https://username:password@xxx.xxx.xxx.xxx:9999"),
      		Endpoint: endpoint,
      	}
      	// We recommend that you reuse the client instance to improve performance by avoiding repeated connection establishment.
      	return green20220302.NewClient(config)
      }
      
      func invoke(accessKeyId *string, accessKeySecret *string, endpoint *string) (_result *green20220302.DescribeUrlModerationResultResponse, _err error) {
      	// We recommend that you reuse the client instance to improve performance by avoiding repeated connection establishment.
      	client, _err := createClient(accessKeyId, accessKeySecret, endpoint)
      	if _err != nil {
      		return nil, _err
      	}
      	// Create a RuntimeOptions instance and configure runtime parameters. These settings are valid only for requests that use this instance.
      	runtime := &util.RuntimeOptions{}
      
      	// Construct the request.
      	imageModerationRequest := &green20220302.DescribeUrlModerationResultRequest{
      		// The reqId returned from submitting the asynchronous detection task. Example: DFEXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXX44
      		ReqId:           tea.String("DFEXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXX44"),
      	}
      
      	return client.DescribeUrlModerationResultWithOptions(imageModerationRequest, runtime)
      
      }
      
      func main() {
      	/**
      	 * An AccessKey of an Alibaba Cloud account has full permissions on all APIs. We recommend that you use a RAM user to make API calls or perform routine O&M.
      	 * We strongly recommend that you do not hard-code your AccessKey ID and AccessKey Secret in your project code. Otherwise, your AccessKeys may be leaked, which poses a threat to the security of your resources.
      	 * We recommend that you retrieve the AccessKey ID and AccessKey secret from environment variables.
      	 * Get the AccessKey ID of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
      	 * Get the AccessKey secret of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
      	 */
      	var accessKeyId = tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
      	var accessKeySecret = tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
      	// Modify the region and endpoint based on your business requirements.
      	var endpoint = tea.String("green-cip.cn-shanghai.aliyuncs.com")
      	response, _err := invoke(accessKeyId, accessKeySecret, endpoint)
      
      	if response != nil {
      		statusCode := tea.IntValue(tea.ToInt(response.StatusCode))
      		body := response.Body
      		imageModerationResponseData := body.Data
      		fmt.Println("requestId:" + tea.StringValue(body.RequestId))
      		if statusCode == http.StatusOK {
      			fmt.Println("response success. response:" + imageModerationResponseData.String())
      		} else {
      			fmt.Print("response not success. status:" + tea.ToString(statusCode))
      			fmt.Println("Error:", _err)
      		}
      	}
      }

Node.js SDK

  1. Run the following command to install the dependency:

    npm install @alicloud/green20220302@3.2.4
  2. Integrate the Node.js SDK.

    • Sample code for submitting a URL risk detection task

      const RPCClient = require("@alicloud/pop-core");
      const { v4: uuidv4 } = require('uuid');
      
      async function main() {
          // We recommend that you reuse the client instance to improve performance by avoiding repeated connection establishment.
          var client = new RPCClient({
              // An AccessKey of an Alibaba Cloud account has full permissions on all APIs. We recommend that you use a RAM user to make API calls or perform routine O&M.
              // We strongly recommend that you do not hard-code your AccessKey ID and AccessKey Secret in your project code. Otherwise, your AccessKeys may be leaked, which poses a threat to the security of your resources.
              accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
              accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
              // Modify the region and endpoint based on your business requirements.
              endpoint: "https://green-cip.cn-shanghai.aliyuncs.com",
              apiVersion: '2022-03-02',
              // Configure an HTTP proxy.
              // httpProxy: "http://xx.xx.xx.xx:xxxx",
              // Configure an HTTPS proxy.
              // httpsProxy: "https://username:password@xxx.xxx.xxx.xxx:9999",
          });
          // Create an API request and configure the parameters.
          var params = {
              // The service for URL detection. Example: url_detection_pro.
              "Service": "url_detection_pro",
              "ServiceParameters": JSON.stringify({
                  // A unique identifier for the data to be detected.
                  "dataId": uuidv4(),
                  // The publicly accessible URL to be detected.
                  "url": "https://www.aliyun.com",
                  // The callback URL that receives the detection result.
                  "callback": "http://www.aliyun.com",
                  // A random string used to sign callback notification requests.
                  "seed": "seedCode",
                  // The algorithm used to sign callback notifications when a callback URL is used.
                  "cryptType": "SM3"
              })
          }
      
          var requestOption = {
              method: 'POST',
              formatParams: false,
          };
      
          try {
              // Call the API to get the result.
              var response = await client.request('UrlAsyncModeration', params, requestOption)
          } catch (err) {
              console.log(err);
          }
          return response;
      }
      
      main().then(function (response) {
          // The response contains a ReqId field. Use this field to query the result of the asynchronous detection task.
          console.log(JSON.stringify(response))
      });
    • Sample code for querying the result of a URL risk detection task

      const RPCClient = require("@alicloud/pop-core");
      const { v4: uuidv4 } = require('uuid');
      
      async function main() {
          // We recommend that you reuse the client instance to improve performance by avoiding repeated connection establishment.
          var client = new RPCClient({
              // An AccessKey of an Alibaba Cloud account has full permissions on all APIs. We recommend that you use a RAM user to make API calls or perform routine O&M.
              // We strongly recommend that you do not hard-code your AccessKey ID and AccessKey Secret in your project code. Otherwise, your AccessKeys may be leaked, which poses a threat to the security of your resources.
              accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
              accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
              // Modify the region and endpoint based on your business requirements.
              endpoint: "https://green-cip.cn-shanghai.aliyuncs.com",
              apiVersion: '2022-03-02',
              // Configure an HTTP proxy.
              // httpProxy: "http://xx.xx.xx.xx:xxxx",
              // Configure an HTTPS proxy.
              // httpsProxy: "https://username:password@xxx.xxx.xxx.xxx:9999",
          });
          // Create an API request and configure the parameters.
          var params = {
              // The reqId returned from submitting the asynchronous detection task. Example: DFEXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXX44
              "ReqId": "DFEXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXX44",
          }
      
          var requestOption = {
              method: 'POST',
              formatParams: false,
          };
      
          try {
              // Call the API to get the detection result.
              var response = await client.request('DescribeUrlModerationResult', params, requestOption)
          } catch (err) {
              console.log(err);
          }
      
          return response;
      }
      
      main().then(function (response) {
          console.log(JSON.stringify(response))
      });

C# SDK

  1. Run the following command to install the dependency:

    dotnet add package AlibabaCloud.SDK.Green20220302 --version 3.2.4
  2. Integrate the C# SDK.

    • Sample code for submitting a URL risk detection task

      using Newtonsoft.Json;
      
      namespace AlibabaCloud.SDK.Green20220302
      {
          public class ImageModerationAutoRoute
          {
              public static void Main(string[] args)
              {
                  /**
                  * An AccessKey of an Alibaba Cloud account has full permissions on all APIs. We recommend that you use a RAM user to make API calls or perform routine O&M.
                  * We strongly recommend that you do not hard-code your AccessKey ID and AccessKey Secret in your project code. Otherwise, your AccessKeys may be leaked, which poses a threat to the security of your resources.
                  * We recommend that you retrieve the AccessKey ID and AccessKey secret from environment variables.
                  * Get the AccessKey ID of the RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID")
                  * Get the AccessKey secret of the RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
                  */
                  String accessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID");
                  String accessKeySecret = Environment.GetEnvironmentVariable(
                      "ALIBABA_CLOUD_ACCESS_KEY_SECRET"
                  );
                  // Modify the region and endpoint based on your business requirements.
                  String endpoint = "green-cip.cn-shanghai.aliyuncs.com";
                  // We recommend that you reuse the client instance to improve performance by avoiding repeated connection establishment.
                  Client client = createClient(accessKeyId, accessKeySecret, endpoint);
      
                  // Configure runtime parameters. These settings are valid only for requests that use this runtime parameter instance.
                  AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions =
                      new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
      
                  // Construct the URL detection request.
                  Models.UrlAsyncModerationRequest imageModerationRequest =
                      new Models.UrlAsyncModerationRequest();
                  // The service for URL detection. Example: url_detection_pro.
                  imageModerationRequest.Service = "url_detection_pro";
                  Dictionary<string, object> task = new Dictionary<string, object>();
                  // The publicly accessible URL to be detected.
                  task.Add(
                      "url",
                      "https://www.aliyun.com"
                  );
                  // A unique identifier for the data to be detected.
                  task.Add("dataId", Guid.NewGuid().ToString());
                  // The callback URL that receives the detection result.
                  task.Add("callback", "http://www.aliyun.com");
                  // A random string used to sign callback notification requests.
                  task.Add("seed", "seedCode");
                  // The algorithm used to sign callback notifications when a callback URL is used.
                  task.Add("cryptType", "SM3");
                  imageModerationRequest.ServiceParameters = JsonConvert.SerializeObject(task);
      
                  try
                  {
                      // Call the API to get the detection result.
                      Models.UrlAsyncModerationResponse response =
                          client.UrlAsyncModerationWithOptions(imageModerationRequest, runtimeOptions);
                      // The response contains a ReqId field. Use this field to query the result of the asynchronous detection task.
                      Console.WriteLine(response.Body.RequestId);
                      Console.WriteLine(JsonConvert.SerializeObject(response.Body));
                  }
                  catch (Exception _err)
                  {
                      Console.WriteLine(_err);
                  }
              }
      
              // Create a client.
              public static Client createClient(
                  String accessKeyId,
                  String accessKeySecret,
                  String endpoint
              )
              {
                  AlibabaCloud.OpenApiClient.Models.Config config =
                      new AlibabaCloud.OpenApiClient.Models.Config
                      {
                          AccessKeyId = accessKeyId,
                          AccessKeySecret = accessKeySecret,
                          // Configure an HTTP proxy.
                          //HttpProxy = "http://10.10.xx.xx:xxxx",
                          // Configure an HTTPS proxy.
                          //HttpsProxy = "https://username:password@xxx.xxx.xxx.xxx:9999",
                          // The endpoint to access.
                          Endpoint = endpoint,
                      };
                  return new Client(config);
              }
          }
      }
    • Sample code for querying the result of a URL risk detection task

      using Newtonsoft.Json;
      
      namespace AlibabaCloud.SDK.Green20220302
      {
          public class ImageModerationAutoRoute
          {
              public static void Main(string[] args)
              {
                  /**
                  * An AccessKey of an Alibaba Cloud account has full permissions on all APIs. We recommend that you use a RAM user to make API calls or perform routine O&M.
                  * We strongly recommend that you do not hard-code your AccessKey ID and AccessKey Secret in your project code. Otherwise, your AccessKeys may be leaked, which poses a threat to the security of your resources.
                  * We recommend that you retrieve the AccessKey ID and AccessKey secret from environment variables.
                  * Get the AccessKey ID of the RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID")
                  * Get the AccessKey secret of the RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
                  */
                  String accessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID");
                  String accessKeySecret = Environment.GetEnvironmentVariable(
                      "ALIBABA_CLOUD_ACCESS_KEY_SECRET"
                  );
                  // Modify the region and endpoint based on your business requirements.
                  String endpoint = "green-cip.cn-shanghai.aliyuncs.com";
                  // We recommend that you reuse the client instance to improve performance by avoiding repeated connection establishment.
                  Client client = createClient(accessKeyId, accessKeySecret, endpoint);
      
                  // Configure runtime parameters. These settings are valid only for requests that use this runtime parameter instance.
                  AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions =
                      new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
      
                  // Construct the URL detection request.
                  Models.DescribeUrlModerationResultRequest imageModerationRequest =
                      new Models.DescribeUrlModerationResultRequest();
                  // The reqId returned from submitting the asynchronous detection task. Example: DFEXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXX44
                  imageModerationRequest.ReqId = "DFEXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXX44";
      
                  try
                  {
                      // Call the API to get the detection result.
                      Models.DescribeUrlModerationResultResponse response = client.DescribeUrlModerationResultWithOptions(
                          imageModerationRequest,
                          runtimeOptions
                      );
      
                      Console.WriteLine(response.Body.RequestId);
                      Console.WriteLine(JsonConvert.SerializeObject(response.Body));
                  }
                  catch (Exception _err)
                  {
                      Console.WriteLine(_err);
                  }
              }
      
              // Create a client.
              public static Client createClient(
                  String accessKeyId,
                  String accessKeySecret,
                  String endpoint
              )
              {
                  AlibabaCloud.OpenApiClient.Models.Config config =
                      new AlibabaCloud.OpenApiClient.Models.Config
                      {
                          AccessKeyId = accessKeyId,
                          AccessKeySecret = accessKeySecret,
                          // Configure an HTTP proxy.
                          //HttpProxy = "http://10.10.xx.xx:xxxx",
                          // Configure an HTTPS proxy.
                          //HttpsProxy = "https://username:password@xxx.xxx.xxx.xxx:9999",
                          // The endpoint to access.
                          Endpoint = endpoint,
                      };
                  return new Client(config);
              }
          }
      }

If you encounter any issues, join the DingTalk group (ID: 35573806) for support from our product and technical experts.