获取 reCAPTCHA 网站密钥

获取指定项目 ID 的 reCAPTCHA 网站密钥。

代码示例

Java

如需向 reCAPTCHA Enterprise 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


import com.google.api.core.ApiFuture;
import com.google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseServiceClient;
import com.google.recaptchaenterprise.v1.GetKeyRequest;
import com.google.recaptchaenterprise.v1.Key;
import com.google.recaptchaenterprise.v1.KeyName;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class GetSiteKey {

  public static void main(String[] args)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    String projectID = "your-project-id";
    String recaptchaSiteKey = "recaptcha-site-key";

    getSiteKey(projectID, recaptchaSiteKey);
  }

  /**
   * Get the reCAPTCHA site key present under the project ID.
   *
   * @param projectID: GCloud Project ID.
   * @param recaptchaSiteKey: Specify the site key to get the details.
   */
  public static void getSiteKey(String projectID, String recaptchaSiteKey)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    // 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()) {

      // Construct the "GetSiteKey" request.
      GetKeyRequest getKeyRequest =
          GetKeyRequest.newBuilder()
              .setName(KeyName.of(projectID, recaptchaSiteKey).toString())
              .build();

      // Wait for the operation to complete.
      ApiFuture<Key> futureCall = client.getKeyCallable().futureCall(getKeyRequest);
      Key key = futureCall.get(5, TimeUnit.SECONDS);

      System.out.println("Successfully obtained the key !" + key.getName());
    }
  }
}

PHP

如需向 reCAPTCHA Enterprise 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

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

/**
 * Get a reCAPTCHA key from a google cloud project
 *
 * @param string $projectId Your Google Cloud project ID
 * @param string $keyId The 40 char long key ID you wish to fetch
 */
function get_key(string $projectId, string $keyId): void
{
    $client = new RecaptchaEnterpriseServiceClient();
    $formattedKeyName = $client->keyName($projectId, $keyId);

    try {
        // Returns a 'Google\Cloud\RecaptchaEnterprise\V1\Key' object
        $getKeyRequest = (new GetKeyRequest())
            ->setName($formattedKeyName);
        $key = $client->getKey($getKeyRequest);
        $webSettings = $key->getWebSettings();

        print('Key fetched' . PHP_EOL);
        printf('Display name: %s' . PHP_EOL, $key->getDisplayName());
        // $key->getCreateTime() returns a Google\Protobuf\Timestamp object
        printf('Create time: %d' . PHP_EOL, $key->getCreateTime()->getSeconds());
        printf('Web platform settings: %s' . PHP_EOL, $key->hasWebSettings() ? 'Yes' : 'No');
        printf('Allowed all domains: %s' . PHP_EOL, $key->hasWebSettings() && $webSettings->getAllowAllDomains() ? 'Yes' : 'No');
        printf('Integration Type: %s' . PHP_EOL, $key->hasWebSettings() ? IntegrationType::name($webSettings->getIntegrationType()) : 'N/A');
    } catch (ApiException $e) {
        if ($e->getStatus() === 'NOT_FOUND') {
            printf('The key with Key ID: %s doesn\'t exist.' . PHP_EOL, $keyId);
        } else {
            print('getKey() call failed with the following error: ');
            print($e);
        }
    }
}

Python

如需向 reCAPTCHA Enterprise 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

from google.cloud import recaptchaenterprise_v1

def get_site_key(project_id: str, recaptcha_site_key: str) -> None:
    """
    Get the reCAPTCHA site key present under the project ID.

    Args:
    project_id: GCloud Project ID.
    recaptcha_site_key: Specify the site key to get the details.
    """

    client = recaptchaenterprise_v1.RecaptchaEnterpriseServiceClient()

    # Construct the key details.
    key_name = f"projects/{project_id}/keys/{recaptcha_site_key}"

    request = recaptchaenterprise_v1.GetKeyRequest()
    request.name = key_name

    key = client.get_key(request)
    print("Successfully obtained the key !" + key.name)

Ruby

如需向 reCAPTCHA Enterprise 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

require "google/cloud/recaptcha_enterprise"

# Get details of site key registered to use recaptcha services.
#
# @param project_id [String] GCloud Project ID.
# @param site_key [String] Site key to be updated.
# @return [void]
def get_site_key project_id:, site_key:
  # Create the reCAPTCHA client.
  client = ::Google::Cloud::RecaptchaEnterprise.recaptcha_enterprise_service

  key = client.get_key name: "projects/#{project_id}/keys/#{site_key}"
  puts "Successfully obtained the key ! #{key.name}"
end

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器