mosparo/php-api-client
PHP API client for mosparo spam protection. Connect to a mosparo instance, send verification requests for form submissions, handle validation results, and integrate bot protection into your PHP/Laravel apps with a simple, lightweight client.
Installation
composer require mosparo/php-api-client
Ensure your project meets PHP 8.0+ requirements.
First API Call
Initialize the client with your API key (replace YOUR_API_KEY):
use Mosparo\ApiClient\Client;
$client = new Client('YOUR_API_KEY');
Basic Request
Fetch a simple endpoint (e.g., /v1/health):
$response = $client->get('/v1/health');
$data = json_decode($response->getBody(), true);
Key Files
src/Client.php: Core client logic.src/Exception/ApiException.php: Error handling.src/Request.php: Request builder.Authenticated Requests Use the client instance for all requests (automatically includes auth headers):
$response = $client->post('/v1/campaigns', ['name' => 'Test']);
Pagination
Handle paginated responses with getNextPage():
$response = $client->get('/v1/campaigns');
$campaigns = json_decode($response->getBody(), true);
while ($nextPage = $client->getNextPage($response)) {
$campaigns = array_merge($campaigns, json_decode($nextPage->getBody(), true));
}
Webhook Verification Verify incoming webhooks (e.g., from Mosparo):
$verifier = $client->getWebhookVerifier($_SERVER['HTTP_SIGNATURE']);
if ($verifier->isValid()) {
// Process webhook
}
Rate Limiting Check rate limits before making requests:
$limits = $client->getRateLimit();
if ($limits['remaining'] <= 0) {
sleep($limits['reset'] - time());
}
Laravel Service Provider Bind the client to the container for dependency injection:
$this->app->singleton(Client::class, function ($app) {
return new Client(config('services.mosparo.key'));
});
API Resource Classes
Extend Mosparo\ApiClient\Resource to model API responses:
class Campaign extends Resource {
public function getName() { return $this->name; }
}
Async Requests Use Guzzle’s async features for batch operations:
$promises = [];
foreach ($campaigns as $campaign) {
$promises[] = $client->postAsync('/v1/campaigns/send', ['id' => $campaign['id']]);
}
GuzzleHttp\Promise\Utils::settle($promises)->wait();
API Key Exposure
.env or a secrets manager.config('services.mosparo.key') in Laravel.Rate Limit Headers
X-RateLimit-Remaining.Webhook Signatures
HTTP_SIGNATURE matches the header name.$signature = $_SERVER['HTTP_X_MOSPARO_SIGNATURE'] ?? '';
Deprecated Endpoints
Client::setBaseUrl() to override endpoints during testing.Enable Guzzle Debugging Attach a middleware to log requests:
$client->getClient()->getEmitter()->attach(
new \GuzzleHttp\Middleware::tap(function ($request) {
error_log($request->getUri());
})
);
Handle Exceptions
Catch Mosparo\ApiClient\Exception\ApiException for HTTP errors:
try {
$response = $client->get('/v1/invalid');
} catch (ApiException $e) {
logger()->error($e->getMessage(), ['status' => $e->getCode()]);
}
Custom Headers Add headers globally:
$client->getClient()->getConfig()->set('headers', [
'X-Custom-Header' => 'value',
]);
Middleware Inject middleware (e.g., for logging or auth):
$client->getClient()->getMiddleware()->unshift(
new \GuzzleHttp\Middleware()
);
Response Transformers Override response handling:
$client->setResponseTransformer(function ($response) {
return json_decode($response->getBody(), true)['data'];
});
Testing Mock the client in PHPUnit:
$mock = $this->getMockBuilder(Client::class)
->disableOriginalConstructor()
->onlyMethods(['get'])
->getMock();
$mock->method('get')->willReturn(new \GuzzleHttp\Psr7\Response(200, [], '{}'));
How can I help you explore Laravel packages today?