Skip to content

Commit 87a0104

Browse files
feat: recaptcha samples for site key operations (GoogleCloudPlatform#1500)
1 parent b96b7df commit 87a0104

File tree

9 files changed

+586
-0
lines changed

9 files changed

+586
-0
lines changed

recaptcha/README.md

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
2+
# Google reCAPTCHA Enterprise PHP Sample Application
3+
4+
[![Open in Cloud Shell][shell_img]][shell_link]
5+
6+
[shell_img]: http://gstatic.com/cloudssh/images/open-btn.svg
7+
[shell_link]: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googlecloudplatform/php-docs-samples&page=editor&working_dir=recaptcha
8+
9+
## Description
10+
11+
This simple command-line application demonstrates how to invoke
12+
[Google reCAPTCHA Enterprise][recaptcha-enterprise] from PHP.
13+
14+
## Build and Run
15+
16+
1. **Enable APIs** - [Enable the reCAPTCHA Enterprise
17+
API](https://console.cloud.google.com/flows/enableapi?apiid=recaptchaenterprise.googleapis.com)
18+
and create a new project or select an existing project.
19+
20+
1. **Download The Credentials** - Click "Go to credentials" after enabling the
21+
APIs. Click "New Credentials" and select "Service Account Key". Create a new
22+
service account, use the JSON key type, and select "Create". Once
23+
downloaded, set the environment variable `GOOGLE_APPLICATION_CREDENTIALS` to
24+
the path of the JSON key that was downloaded.
25+
26+
1. **Clone the repo** and cd into this directory
27+
28+
```text
29+
$ git clone https://github.com/GoogleCloudPlatform/php-docs-samples
30+
$ cd php-docs-samples/recaptcha
31+
```
32+
33+
1. **Install dependencies** via [Composer][install-composer]. If composer is
34+
installed locally:
35+
36+
```text
37+
$ php composer.phar install
38+
```
39+
40+
If composer is installed globally:
41+
42+
```text
43+
$ composer install
44+
```
45+
46+
1. Execute the snippets in the [src/](src/) directory by running:
47+
48+
```text
49+
$ php src/SNIPPET_NAME.php
50+
```
51+
52+
The usage will print for each if no arguments are provided.
53+
54+
See the [reCAPTCHA Enterprise Documentation](https://cloud.google.com/recaptcha-enterprise/docs) for more information.
55+
56+
## Contributing changes
57+
58+
* See [CONTRIBUTING.md](../CONTRIBUTING.md)
59+
60+
## Licensing
61+
62+
* See [LICENSE](../LICENSE)
63+
64+
[install-composer]: http://getcomposer.org/doc/00-intro.md
65+
[recaptcha-enterprise]: https://cloud.google.com/recaptcha-enterprise

recaptcha/composer.json

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"require": {
3+
"google/cloud-recaptcha-enterprise": "^1.0"
4+
}
5+
}

recaptcha/phpunit.xml.dist

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<!--
3+
Copyright 2020 Google LLC.
4+
5+
Licensed under the Apache License, Version 2.0 (the "License");
6+
you may not use this file except in compliance with the License.
7+
You may obtain a copy of the License at
8+
9+
http://www.apache.org/licenses/LICENSE-2.0
10+
11+
Unless required by applicable law or agreed to in writing, software
12+
distributed under the License is distributed on an "AS IS" BASIS,
13+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
See the License for the specific language governing permissions and
15+
limitations under the License.
16+
-->
17+
<phpunit bootstrap="../testing/bootstrap.php">
18+
<testsuites>
19+
<testsuite name="PHP reCAPTCHA test">
20+
<directory>test</directory>
21+
</testsuite>
22+
</testsuites>
23+
<logging>
24+
<log type="coverage-clover" target="build/logs/clover.xml"/>
25+
</logging>
26+
<filter>
27+
<whitelist>
28+
<directory suffix=".php">./src</directory>
29+
<exclude>
30+
<directory>./vendor</directory>
31+
</exclude>
32+
</whitelist>
33+
</filter>
34+
<php>
35+
<env name="PHPUNIT_TESTS" value="1"/>
36+
</php>
37+
</phpunit>

recaptcha/src/create_key.php

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
<?php
2+
/*
3+
* Copyright 2021 Google LLC.
4+
*
5+
* Licensed under the Apache License, Version 2.0 (the "License");
6+
* you may not use this file except in compliance with the License.
7+
* You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
/**
19+
* For instructions on how to run the full sample:
20+
*
21+
* @see https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/recaptcha/README.md
22+
*/
23+
24+
namespace Google\Cloud\Samples\Recaptcha;
25+
26+
// [START recaptcha_enterprise_create_site_key]
27+
use Google\Cloud\RecaptchaEnterprise\V1\RecaptchaEnterpriseServiceClient;
28+
use Google\Cloud\RecaptchaEnterprise\V1\Key;
29+
use Google\Cloud\RecaptchaEnterprise\V1\WebKeySettings;
30+
use Google\Cloud\RecaptchaEnterprise\V1\WebKeySettings\IntegrationType;
31+
use Google\ApiCore\ApiException;
32+
33+
/**
34+
* Create a site key for reCAPTCHA
35+
*
36+
* @param string $projectId Your Google Cloud project ID
37+
* @param string $keyName The name of the key you wish to create
38+
*/
39+
function create_key(string $projectId, string $keyName): void
40+
{
41+
$client = new RecaptchaEnterpriseServiceClient();
42+
$formattedProject = $client->projectName($projectId);
43+
44+
// Create the settings for the key.
45+
// In order to create other keys we'll use AndroidKeySettings or IOSKeySettings
46+
$settings = new WebKeySettings();
47+
48+
// Allow the key to work for all domains(Not recommended)
49+
$settings->setAllowAllDomains(true);
50+
// ...or explicitly set the allowed domains for the key as an array of strings
51+
// $settings->setAllowedDomains(['']);
52+
53+
// Specify the type of the key
54+
// - score based key -> IntegrationType::SCORE
55+
// - checkbox based key -> IntegrationType::CHECKBOX
56+
// Read https://cloud.google.com/recaptcha-enterprise/docs/choose-key-type
57+
$settings->setIntegrationType(IntegrationType::CHECKBOX);
58+
59+
$key = new Key();
60+
$key->setDisplayName($keyName);
61+
$key->setWebSettings($settings);
62+
63+
try {
64+
$createdKey = $client->createKey($formattedProject, $key);
65+
printf('The key: %s is created.' . PHP_EOL, $createdKey->getName());
66+
} catch (ApiException $e) {
67+
print('createKey() call failed with the following error: ');
68+
print($e);
69+
}
70+
}
71+
// [END recaptcha_enterprise_create_site_key]
72+
73+
// The following 2 lines are only needed to run the samples
74+
require_once __DIR__ . '/../../testing/sample_helpers.php';
75+
\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv);

recaptcha/src/delete_key.php

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
<?php
2+
/*
3+
* Copyright 2021 Google LLC.
4+
*
5+
* Licensed under the Apache License, Version 2.0 (the "License");
6+
* you may not use this file except in compliance with the License.
7+
* You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
/**
19+
* For instructions on how to run the full sample:
20+
*
21+
* @see https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/recaptcha/README.md
22+
*/
23+
24+
namespace Google\Cloud\Samples\Recaptcha;
25+
26+
// [START recaptcha_enterprise_delete_site_key]
27+
use Google\ApiCore\ApiException;
28+
use Google\Cloud\RecaptchaEnterprise\V1\RecaptchaEnterpriseServiceClient;
29+
30+
/**
31+
* Delete an existing reCAPTCHA key from your Google Cloud project
32+
*
33+
* @param string $projectId Your Google Cloud project ID
34+
* @param string $keyId The 40 char long key ID you wish to delete
35+
*/
36+
function delete_key(string $projectId, string $keyId): void
37+
{
38+
$client = new RecaptchaEnterpriseServiceClient();
39+
$formattedKeyName = $client->keyName($projectId, $keyId);
40+
41+
try {
42+
$client->deleteKey($formattedKeyName);
43+
printf('The key: %s is deleted.' . PHP_EOL, $keyId);
44+
} catch (ApiException $e) {
45+
if ($e->getStatus() === 'NOT_FOUND') {
46+
printf('The key with Key ID: %s doesn\'t exist.' . PHP_EOL, $keyId);
47+
} else {
48+
print('deleteKey() call failed with the following error: ');
49+
print($e->getBasicMessage() . PHP_EOL);
50+
}
51+
}
52+
}
53+
// [END recaptcha_enterprise_delete_site_key]
54+
55+
// The following 2 lines are only needed to run the samples
56+
require_once __DIR__ . '/../../testing/sample_helpers.php';
57+
\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv);

recaptcha/src/get_key.php

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
<?php
2+
/*
3+
* Copyright 2021 Google LLC.
4+
*
5+
* Licensed under the Apache License, Version 2.0 (the "License");
6+
* you may not use this file except in compliance with the License.
7+
* You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
/**
19+
* For instructions on how to run the full sample:
20+
*
21+
* @see https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/recaptcha/README.md
22+
*/
23+
24+
namespace Google\Cloud\Samples\Recaptcha;
25+
26+
// [START recaptcha_enterprise_get_site_key]
27+
use Google\Cloud\RecaptchaEnterprise\V1\RecaptchaEnterpriseServiceClient;
28+
use Google\Cloud\RecaptchaEnterprise\V1\WebKeySettings\IntegrationType;
29+
use Google\ApiCore\ApiException;
30+
31+
/**
32+
* Get a reCAPTCHA key from a google cloud project
33+
*
34+
* @param string $projectId Your Google Cloud project ID
35+
* @param string $keyId The 40 char long key ID you wish to fetch
36+
*/
37+
function get_key(string $projectId, string $keyId): void
38+
{
39+
$client = new RecaptchaEnterpriseServiceClient();
40+
$formattedKeyName = $client->keyName($projectId, $keyId);
41+
42+
try {
43+
// Returns a 'Google\Cloud\RecaptchaEnterprise\V1\Key' object
44+
$key = $client->getKey($formattedKeyName);
45+
$webSettings = $key->getWebSettings();
46+
47+
print('Key fetched' . PHP_EOL);
48+
printf('Display name: %s' . PHP_EOL, $key->getDisplayName());
49+
// $key->getCreateTime() returns a Google\Protobuf\Timestamp object
50+
printf('Create time: %d' . PHP_EOL, $key->getCreateTime()->getSeconds());
51+
printf('Web platform settings: %s' . PHP_EOL, $key->hasWebSettings() ? 'Yes' : 'No');
52+
printf('Allowed all domains: %s' . PHP_EOL, $key->hasWebSettings() && $webSettings->getAllowAllDomains() ? 'Yes' : 'No');
53+
printf('Integration Type: %s' . PHP_EOL, $key->hasWebSettings() ? IntegrationType::name($webSettings->getIntegrationType()) : 'N/A');
54+
} catch (ApiException $e) {
55+
if ($e->getStatus() === 'NOT_FOUND') {
56+
printf('The key with Key ID: %s doesn\'t exist.' . PHP_EOL, $keyId);
57+
} else {
58+
print('getKey() call failed with the following error: ');
59+
print($e);
60+
}
61+
}
62+
}
63+
// [END recaptcha_enterprise_get_site_key]
64+
65+
// The following 2 lines are only needed to run the samples
66+
require_once __DIR__ . '/../../testing/sample_helpers.php';
67+
\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv);

recaptcha/src/list_keys.php

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
<?php
2+
/*
3+
* Copyright 2021 Google LLC.
4+
*
5+
* Licensed under the Apache License, Version 2.0 (the "License");
6+
* you may not use this file except in compliance with the License.
7+
* You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
/**
19+
* For instructions on how to run the full sample:
20+
*
21+
* @see https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/recaptcha/README.md
22+
*/
23+
24+
namespace Google\Cloud\Samples\Recaptcha;
25+
26+
// [START recaptcha_enterprise_list_site_keys]
27+
use Google\Cloud\RecaptchaEnterprise\V1\RecaptchaEnterpriseServiceClient;
28+
use Google\ApiCore\ApiException;
29+
30+
/**
31+
* List all the reCAPTCHA keys associate to a Google Cloud project
32+
*
33+
* @param string $projectId Your Google Cloud project ID
34+
*/
35+
function list_keys(string $projectId): void
36+
{
37+
$client = new RecaptchaEnterpriseServiceClient();
38+
$formattedProject = $client->projectName($projectId);
39+
40+
try {
41+
$response = $client->listKeys($formattedProject, [
42+
'pageSize' => 2
43+
]);
44+
45+
print('Keys fetched' . PHP_EOL);
46+
47+
// Either iterate over all the keys and let the library handle the paging
48+
foreach ($response->iterateAllElements() as $key) {
49+
print($key->getDisplayName() . PHP_EOL);
50+
}
51+
52+
// Or fetch each page and process the keys as needed
53+
// foreach ($response->iteratePages() as $page) {
54+
// foreach ($page as $key) {
55+
// print($key->getDisplayName() . PHP_EOL);
56+
// }
57+
// }
58+
} catch (ApiException $e) {
59+
print('listKeys() call failed with the following error: ');
60+
print($e);
61+
}
62+
}
63+
// [END recaptcha_enterprise_list_site_keys]
64+
65+
// The following 2 lines are only needed to run the samples
66+
require_once __DIR__ . '/../../testing/sample_helpers.php';
67+
\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv);

0 commit comments

Comments
 (0)