Crea una chiave di sito reCAPTCHA

Crea una chiave di sito reCAPTCHA che associa un nome di dominio a una chiave univoca.

Esempio di codice

Java

Per eseguire l'autenticazione a reCAPTCHA, configura le credenziali predefinite dell'applicazione. Per ulteriori informazioni, vedi Configura l'autenticazione per un ambiente di sviluppo locale.


import com.google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseServiceClient;
import com.google.recaptchaenterprise.v1.CreateKeyRequest;
import com.google.recaptchaenterprise.v1.Key;
import com.google.recaptchaenterprise.v1.ProjectName;
import com.google.recaptchaenterprise.v1.WebKeySettings;
import com.google.recaptchaenterprise.v1.WebKeySettings.IntegrationType;
import java.io.IOException;

public class CreateSiteKey {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectID = "your-project-id";
    String domainName = "domain-name";

    createSiteKey(projectID, domainName);
  }

  /**
   * Create reCAPTCHA Site key which binds a domain name to a unique key.
   *
   * @param projectID : GCloud Project ID.
   * @param domainName : Specify the domain name in which the reCAPTCHA should be activated.
   */
  public static String createSiteKey(String projectID, String domainName) throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the `client.close()` method on the client to safely
    // clean up any remaining background resources.
    try (RecaptchaEnterpriseServiceClient client = RecaptchaEnterpriseServiceClient.create()) {

      // Set the type of reCAPTCHA to be displayed.
      // For different types, see: https://cloud.google.com/recaptcha-enterprise/docs/keys
      Key scoreKey =
          Key.newBuilder()
              .setDisplayName("any_descriptive_name_for_the_key")
              .setWebSettings(
                  WebKeySettings.newBuilder()
                      .addAllowedDomains(domainName)
                      .setAllowAmpTraffic(false)
                      .setIntegrationType(IntegrationType.SCORE)
                      .build())
              .build();

      CreateKeyRequest createKeyRequest =
          CreateKeyRequest.newBuilder()
              .setParent(ProjectName.of(projectID).toString())
              .setKey(scoreKey)
              .build();

      // Get the name of the created reCAPTCHA site key.
      Key response = client.createKey(createKeyRequest);
      String keyName = response.getName();
      String recaptchaSiteKey = keyName.substring(keyName.lastIndexOf("/") + 1);
      System.out.println("reCAPTCHA Site key created successfully. Site Key: " + recaptchaSiteKey);
      return recaptchaSiteKey;
    }
  }
}

PHP

Per eseguire l'autenticazione in reCAPTCHA, configura le Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

use Google\ApiCore\ApiException;
use Google\Cloud\RecaptchaEnterprise\V1\Client\RecaptchaEnterpriseServiceClient;
use Google\Cloud\RecaptchaEnterprise\V1\CreateKeyRequest;
use Google\Cloud\RecaptchaEnterprise\V1\Key;
use Google\Cloud\RecaptchaEnterprise\V1\WebKeySettings;
use Google\Cloud\RecaptchaEnterprise\V1\WebKeySettings\IntegrationType;

/**
 * Create a site key for reCAPTCHA
 *
 * @param string $projectId Your Google Cloud project ID
 * @param string $keyName The name of the key you wish to create
 */
function create_key(string $projectId, string $keyName): void
{
    $client = new RecaptchaEnterpriseServiceClient();
    $formattedProject = $client->projectName($projectId);

    // Create the settings for the key.
    // In order to create other keys we'll use AndroidKeySettings or IOSKeySettings
    $settings = new WebKeySettings();

    // Allow the key to work for all domains(Not recommended)
    $settings->setAllowAllDomains(true);
    // ...or explicitly set the allowed domains for the key as an array of strings
    // $settings->setAllowedDomains(['']);

    // Specify the type of the key
    // - score based key -> IntegrationType::SCORE
    // - checkbox based key -> IntegrationType::CHECKBOX
    // Read https://cloud.google.com/recaptcha-enterprise/docs/choose-key-type
    $settings->setIntegrationType(IntegrationType::CHECKBOX);

    $key = new Key();
    $key->setDisplayName($keyName);
    $key->setWebSettings($settings);

    try {
        $createKeyRequest = (new CreateKeyRequest())
            ->setParent($formattedProject)
            ->setKey($key);
        $createdKey = $client->createKey($createKeyRequest);
        printf('The key: %s is created.' . PHP_EOL, $createdKey->getName());
    } catch (ApiException $e) {
        print('createKey() call failed with the following error: ');
        print($e);
    }
}

Python

Per eseguire l'autenticazione a reCAPTCHA, configura le credenziali predefinite dell'applicazione. Per ulteriori informazioni, vedi Configura l'autenticazione per un ambiente di sviluppo locale.

from google.cloud import recaptchaenterprise_v1


def create_site_key(project_id: str, domain_name: str) -> str:
    """Create reCAPTCHA Site key which binds a domain name to a unique key.
    Args:
    project_id : GCloud Project ID.
    domain_name: Specify the domain name in which the reCAPTCHA should be activated.
    """
    client = recaptchaenterprise_v1.RecaptchaEnterpriseServiceClient()

    # Set the type of the reCAPTCHA to be displayed.
    # For different types, see: https://cloud.google.com/recaptcha-enterprise/docs/keys
    web_settings = recaptchaenterprise_v1.WebKeySettings()
    web_settings.allowed_domains.append(domain_name)
    web_settings.allow_amp_traffic = False
    web_settings.integration_type = web_settings.IntegrationType.SCORE

    key = recaptchaenterprise_v1.Key()
    key.display_name = "any descriptive name for the key"
    key.web_settings = web_settings

    # Create the request.
    request = recaptchaenterprise_v1.CreateKeyRequest()
    request.parent = f"projects/{project_id}"
    request.key = key

    # Get the name of the created reCAPTCHA site key.
    response = client.create_key(request)
    recaptcha_site_key = response.name.rsplit("/", maxsplit=1)[1]
    print("reCAPTCHA Site key created successfully. Site Key: " + recaptcha_site_key)
    return recaptcha_site_key

Ruby

Per eseguire l'autenticazione in reCAPTCHA, configura le Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

require "google/cloud/recaptcha_enterprise"

# Create a site key by registering a domain/app to use recaptcha services.
#
# @param project_id [String] GCloud Project ID.
# @param domain [String] Domain to register for recaptcha services.
# @return [void]
def create_site_key project_id:, domain:
  # Create the reCAPTCHA client.
  client = ::Google::Cloud::RecaptchaEnterprise.recaptcha_enterprise_service

  request = {
    parent: "projects/#{project_id}",
    key: {
      display_name: "any descriptive name for the key",
      web_settings: {
        allowed_domains: [domain],
        allow_amp_traffic: false,
        integration_type: 1
      }
    }
  }

  # Get the name of the created reCAPTCHA site key.
  response = client.create_key request
  recaptcha_site_key = response.name.split("/").last
  puts "reCAPTCHA Site key created successfully. Site Key: #{recaptcha_site_key}"
end

Passaggi successivi

Per cercare e filtrare esempi di codice per altri prodotti Google Cloud, consulta Browser di esempio Google Cloud.