Skip to content

Commit 6d936d6

Browse files
authored
Merge pull request #8 from FriendlyCaptcha/risk-intelligence
Add support for Risk Intelligence
2 parents 3744139 + 68d6e69 commit 6d936d6

12 files changed

Lines changed: 1351 additions & 118 deletions

File tree

README.md

Lines changed: 46 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# friendly-captcha-php
22

3-
A PHP client for the [Friendly Captcha](https://friendlycaptcha.com) service. This client allows for easy integration and verification of captcha responses with the Friendly Captcha API.
3+
A PHP client for the [Friendly Captcha](https://friendlycaptcha.com) service. This client makes it easy to connect to the Friendly Captcha API for captcha verification or [Risk Intelligence](https://developer.friendlycaptcha.com/docs/v2/risk-intelligence/) retrieval.
44

55
> Note, this is for [Friendly Captcha v2](https://developer.friendlycaptcha.com) only.
66
@@ -16,7 +16,11 @@ composer require friendlycaptcha/sdk
1616

1717
## Usage
1818

19-
First configure and create a SDK client
19+
Below are some basic examples that demonstrate how to use this SDK.
20+
21+
For complete examples, take a look at the [examples](./examples/) directory.
22+
23+
### Initialization
2024

2125
```php
2226
use FriendlyCaptcha\SDK\{Client, ClientConfig}
@@ -25,12 +29,12 @@ $config = new ClientConfig();
2529
$config->setAPIKey("<YOUR API KEY>")->setSitekey("<YOUR SITEKEY (optional)>");
2630

2731
// You can also specify which endpoint to use, for example `"global"` or `"eu"`.
28-
// $config->setEndpoint("eu")
32+
// $config->setApiEndpoint("eu")
2933

3034
$captchaClient = new Client($config)
3135
```
3236

33-
Then use it in the endpoint you want to protect
37+
### Verifying a Captcha Response
3438

3539
```php
3640
function handleLoginRequest() {
@@ -61,6 +65,38 @@ function handleLoginRequest() {
6165
}
6266
```
6367

68+
### Retrieving Risk Intelligence
69+
70+
You can retrieve [Risk Intelligence](https://developer.friendlycaptcha.com/docs/v2/risk-intelligence/) data using a token. This data provides detailed information about the risk profile of a request, including network data, geolocation, browser details, and risk scores.
71+
72+
```php
73+
function getRiskIntelligence() {
74+
global $frcClient;
75+
76+
$token = isset($_POST["frc-risk-intelligence-token"]) ? $_POST["frc-risk-intelligence-token"] : null;
77+
$result = $frcClient->retrieveRiskIntelligence($token);
78+
79+
if ($result->wasAbleToRetrieve()) {
80+
// Risk Intelligence token is valid and data was retrieved successfully.
81+
if ($result->isValid()) {
82+
// Token was invalid or expired.
83+
$response = $result->getResponse();
84+
echo "Risk Intelligence data", $response->data;
85+
} else {
86+
$error = $result->getResponseError();
87+
error_log("Error:", $error);
88+
}
89+
} else {
90+
// Network issue or configuration problem.
91+
if ($result->isClientError()) {
92+
error_log("Configuration error - check your API key");
93+
} else {
94+
error_log("Network issue or service temporarily unavailable");
95+
}
96+
}
97+
}
98+
```
99+
64100
## Development
65101

66102
Make sure you have PHP installed (e.g. with `brew install php` on a Macbook).
@@ -111,17 +147,15 @@ OK (28 tests, 110 assertions)
111147

112148
### Optional
113149

114-
Install an old version of PHP (to be sure it works in that version). The oldest PHP version this SDK supports is 7.1.
115-
116-
```php
117-
brew install shivammathur/php/php@7.1
118-
echo 'export PATH="/opt/homebrew/opt/php@7.1/bin:$PATH"' >> ~/.zshrc
119-
echo 'export PATH="/opt/homebrew/opt/php@7.1/sbin:$PATH"' >> ~/.zshrc
150+
To make sure that the SDK is backwards compatible, make sure the tests pass in PHP 7.1. We recommend using Docker.
120151

121-
# open a new terminal and check the new version
122-
php --version
152+
```console
153+
$ docker run --rm -it --network host -v $PWD:/php -w /php php:7.1-alpine /bin/sh
154+
/php # apk update && apk add git
123155
```
124156

157+
Then follow the steps above starting with [**Install Composer**](#install-composer). You can run `./friendly-captcha-sdk-testserver serve` outside the Docker container.
158+
125159
### Some features you can't use to be compatible with PHP 7.1
126160

127161
- Typings of class member variables.

examples/form/README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# form
22

3-
Example of using the Friendly Captcha SDK for PHP.
3+
Example of using the Friendly Captcha SDK for PHP. It displays a form with a captcha and verifies the captcha response on the back-end. If the application has [**Risk Intelligence**](https://developer.friendlycaptcha.com/docs/v2/risk-intelligence/) enabled, it will also generate a token and use it to retrieve the Risk Intelligence data.
44

55
## Running the example
66

@@ -11,7 +11,7 @@ FRC_APIKEY=YOUR_API_KEY FRC_SITEKEY=YOUR_SITEKEY php -S localhost:8000
1111
Alternatively, you can also specify custom endpoints:
1212

1313
```shell
14-
FRC_SITEKEY=YOUR_API_KEY FRC_APIKEY=YOUR_SITEKEY FRC_SITEVERIFY_ENDPOINT=https://eu-dev.frcapi.com/api/v2/captcha/siteverify FRC_WIDGET_ENDPOINT=https://eu-dev.frcapi.com/api/v2/captcha php -S localhost:8000
14+
FRC_SITEKEY=YOUR_API_KEY FRC_APIKEY=YOUR_SITEKEY FRC_API_ENDPOINT=https://eu-dev.frcapi.com FRC_WIDGET_ENDPOINT=https://eu-dev.frcapi.com php -S localhost:8000
1515
```
1616

1717
Now open your browser and navigate to [http://localhost:8000](http://localhost:8000).

examples/form/index.php

Lines changed: 40 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -10,17 +10,17 @@
1010
$apikey = getenv('FRC_APIKEY');
1111

1212
// Optionally we can pass in custom endpoints to be used, such as "eu".
13-
$siteverifyEndpoint = getenv('FRC_SITEVERIFY_ENDPOINT');
13+
$apiEndpoint = getenv('FRC_API_ENDPOINT');
1414
$widgetEndpoint = getenv('FRC_WIDGET_ENDPOINT');
1515

16-
const MODULE_SCRIPT_URL = "https://cdn.jsdelivr.net/npm/@friendlycaptcha/sdk@0.1.8/site.min.js";
17-
const NOMODULE_SCRIPT_URL = "https://cdn.jsdelivr.net/npm/@friendlycaptcha/sdk@0.1.8/site.compat.min.js";; // Compatibility fallback for old browsers.
16+
const MODULE_SCRIPT_URL = "https://cdn.jsdelivr.net/npm/@friendlycaptcha/sdk@0.2.0/site.min.js";
17+
const NOMODULE_SCRIPT_URL = "https://cdn.jsdelivr.net/npm/@friendlycaptcha/sdk@0.2.0/site.compat.min.js";; // Compatibility fallback for old browsers.
1818

1919
if (empty($sitekey) || empty($apikey)) {
2020
die("Please set the FRC_SITEKEY and FRC_APIKEY environment values before running this example.");
2121
}
2222

23-
function generateForm(bool $didSubmit, bool $captchaOK, string $sitekey)
23+
function generateForm(bool $didSubmit, bool $captchaOK, string $sitekey, string $riskIntelligence)
2424
{
2525
global $widgetEndpoint;
2626
$html = '';
@@ -31,20 +31,21 @@ function generateForm(bool $didSubmit, bool $captchaOK, string $sitekey)
3131
} else {
3232
$html .= '<p style="color:#ba1f1f">❌ Anti-robot check failed, please try again.<br>See console output for details.</p>';
3333
}
34+
if (!empty($riskIntelligence)) {
35+
$html .= $riskIntelligence;
36+
}
3437
$html .= '<a href=".">Back to form</a>';
35-
}
36-
37-
if (!$didSubmit) {
38+
} else {
39+
$dataEndpoint = empty($widgetEndpoint) ? "" : (' data-api-endpoint="' . $widgetEndpoint . '"');
3840
$html .= '
3941
<form method="POST">
4042
<div class="form-group">
4143
<label>Your Name:</label><br />
4244
<input type="text" name="name" value="Jane Doe"><br />
4345
<label>Message:</label><br />
4446
<textarea name="message"></textarea><br />
45-
<div class="frc-captcha"
46-
data-sitekey="' . $sitekey . '"' .
47-
(isset($widgetEndpoint) ? (' data-api-endpoint="' . $widgetEndpoint . '"') : '') . '></div>
47+
<div class="frc-captcha" data-sitekey="' . $sitekey . '"' . $dataEndpoint . '></div>
48+
<div class="frc-risk-intelligence" data-sitekey="' . $sitekey . '"' . $dataEndpoint . '></div>
4849
<input style="margin-top: 1em" type="submit" value="Submit">
4950
</div>
5051
</form>';
@@ -55,15 +56,17 @@ function generateForm(bool $didSubmit, bool $captchaOK, string $sitekey)
5556
$config = new \FriendlyCaptcha\SDK\ClientConfig();
5657
$config->setAPIKey($apikey);
5758
$config->setSitekey($sitekey);
58-
if (!empty($siteverifyEndpoint)) {
59-
$config->setSiteverifyEndpoint($siteverifyEndpoint); // Optional, it defaults to "global".
59+
if (!empty($apiEndpoint)) {
60+
$config->setApiEndpoint($apiEndpoint); // Optional, it defaults to "global".
6061
}
6162

6263
$frcClient = new \FriendlyCaptcha\SDK\Client($config);
6364

6465
$didSubmit = $_SERVER['REQUEST_METHOD'] === 'POST';
6566
$captchaOK = false;
6667

68+
$riskIntelligence = "";
69+
6770
if ($didSubmit) {
6871
$captchaResponse = isset($_POST["frc-captcha-response"]) ? $_POST["frc-captcha-response"] : null;
6972
$captchaResult = $frcClient->verifyCaptchaResponse($captchaResponse);
@@ -91,6 +94,30 @@ function generateForm(bool $didSubmit, bool $captchaOK, string $sitekey)
9194
// In this example we will simply print the message to the console using `error_log`.
9295
error_log("Message submitted by \"" . $name . "\": \"" . $message . "\"");
9396
}
97+
98+
$riskIntelligenceToken = isset($_POST["frc-risk-intelligence-token"]) ? $_POST["frc-risk-intelligence-token"] : null;
99+
$result = $frcClient->retrieveRiskIntelligence($riskIntelligenceToken);
100+
if ($result->wasAbleToRetrieve()) {
101+
if ($result->isValid()) {
102+
$data = $result->getResponse()->data->risk_intelligence;
103+
$riskIntelligence = '
104+
<h3>Risk Intelligence Data</h3>
105+
<dl>
106+
<dt>Location</dt>
107+
<dd>' . $data->network->geolocation->city . ', ' . $data->network->geolocation->country->name . '</dd>
108+
<dt>Device</dt>
109+
<dd><i>Make:</i> ' . $data->client->device->brand . '<br><i>Model:</i> ' . $data->client->device->model . '</dd>
110+
<dt>Overall Risk Score</dt>
111+
<dd>' . $data->risk_scores->overall . '</dd>
112+
</dl>
113+
';
114+
} else {
115+
$error = $result->getResponseError();
116+
error_log("Friendly Captcha API Error:", $error);
117+
}
118+
} else {
119+
error_log("Failed to make the request", $result->errorCode);
120+
}
94121
}
95122
?>
96123

@@ -112,7 +139,7 @@ function generateForm(bool $didSubmit, bool $captchaOK, string $sitekey)
112139
<body>
113140
<main>
114141
<h1>PHP Form Example</h1>
115-
<?php echo generateForm($didSubmit, $captchaOK, $sitekey); ?>
142+
<?php echo generateForm($didSubmit, $captchaOK, $sitekey, $riskIntelligence); ?>
116143
</main>
117144

118145
<script>

0 commit comments

Comments
 (0)