为 Friendly Captcha API 提供的 Server-side SDK。
v0.1.0
2024-01-02 15:48 UTC
Requires
- php: >=7.1
Requires (Dev)
- phpunit/phpunit: >=7
README
一个用于 Friendly Captcha 服务的 PHP 客户端。此客户端允许轻松集成和验证 Friendly Captcha API 的 captcha 响应。
注意,此版本仅适用于 Friendly Captcha v2。此版本目前处于预览状态,有关当前版本,请参阅此处文档。
安装
需要 PHP 7.1 或更高版本。
使用 Composer 安装
composer require friendlycaptcha/sdk
用法
首先配置并创建 SDK 客户端
use FriendlyCaptcha\SDK\{Client, ClientConfig} $config = new ClientConfig(); $config->setAPIKey("<YOUR API KEY>")->setSitekey("<YOUR SITEKEY (optional)>"); // You can also specify which endpoint to use, for example `"global"` or `"eu"`. // $config->setEndpoint("eu") $captchaClient = new Client($config)
然后在您想要保护的端点上使用它
function handleLoginRequest() { global $captchaClient; $captchaResponse = isset($_POST["frc-captcha-response"]) ? $_POST["frc-captcha-response"] : null; $result = $captchaClient->verifyCaptchaResponse($captchaResponse); if (!$result->wasAbleToVerify()) { if ($result->isClientError()) { // ALERT: your website is NOT PROTECTED because of a configuration error. // Send an alert to yourself, check your API key (and sitekey). error_log("Failed to verify captcha response because of configuration problem: " . print_r($result->getResponseError())); } else { // Something else went wrong, maybe there is a connection problem or the API is down. error_log("Failed to verify captcha response: " . print_r($result->getErrorCode())); } } if ($result->shouldReject()) { // The captcha was not OK, show an error message to the user echo "Captcha anti-robot check failed, please try again."; return; } // The captcha is accepted, handle the request: loginUser($_POST["username"], $_POST["password"]); }
开发
请确保已安装 PHP(例如,在 Macbook 上使用 brew install php
)。
安装 Composer
mkdir -p bin php -r "copy('https://getcomposer.org.cn/installer', './bin/composer-setup.php');" # You can omit `--2.2 LTS` if you are using a more recent PHP version than 7.2 php bin/composer-setup.php --install-dir=bin --2.2 LTS
安装依赖项
bin/composer.phar install
运行测试
首先下载适用于您的操作系统的 friendly-captcha-sdk-testserver。
# Run the friendly-captcha-sdk-testserver
./friendly-captcha-sdk-testserver serve
然后在新的终端中运行以下命令
# Generate the autoload files
./bin/composer.phar dump
./vendor/bin/phpunit
然后您应该会看到以下输出
PHPUnit 7.0.0 by Sebastian Bergmann and contributors.
............................ 28 / 28 (100%)
Time: 36 ms, Memory: 4.00 MB
OK (28 tests, 110 assertions)
可选
安装旧版本的 PHP(以确保在该版本中工作)。此 SDK 支持的最旧 PHP 版本是 7.1。
brew install shivammathur/php/php@7.1 echo 'export PATH="/opt/homebrew/opt/php@7.1/bin:$PATH"' >> ~/.zshrc echo 'export PATH="/opt/homebrew/opt/php@7.1/sbin:$PATH"' >> ~/.zshrc # open a new terminal and check the new version php --version
一些功能您无法使用,以与 PHP 7.1 兼容
- 类成员变量的类型。
- 联合类型(不在注释之外)。
许可证
在 MIT 许可下开源。欢迎贡献力量!