AbuseZero PHP SDK
Use the AbuseZero PHP SDK, abusezero/abusezero-php, to evaluate claims, report outcomes and manage your workspace from your PHP server.
The AbuseZero PHP SDK, abusezero/abusezero-php, is the PHP client for the AbuseZero REST API. Every API operation for servers has a method. It checks your input against the API contract before it leaves your server, retries transient failures within a fixed request budget, and lets you set in advance what happens if AbuseZero can't be reached.
Install the PHP SDK
composer require abusezero/abusezero-phpThe PHP SDK supports PHP 8.3 to 8.6 and needs the cURL extension. Keep it, and your secret key, on your server.
Create a PHP SDK client
<?php
require __DIR__ . '/vendor/autoload.php';
$abusezero = new AbuseZero\Client([
'key' => getenv('ABUSEZERO_SECRET_KEY'),
'outage' => 'throw',
]);Create the client once and reuse it: once per request under PHP-FPM, or once per long-running worker. It keeps its connection to AbuseZero open between calls. Call close() when a long-running worker stops. Clients hold your credential, so they can't be serialized. In a queued job, create or resolve the client inside the job instead of passing it in.
Client options
| Option | Type | Required | Description |
|---|---|---|---|
key | string | One of key or accessToken | A secret key (sk_…) or restricted key (rk_…) from Developers → API & Webhooks → API keys. Publishable keys are rejected. |
accessToken | string | One of key or accessToken | An OAuth access token, from a person's sign-in or a machine client. Requires workspace. |
workspace | string | With accessToken | The 74999074913993548694 ID of the workspace this OAuth connection works in. |
outage | throw, allow or deny | No | What evaluate() does when AbuseZero can't be reached. The default is throw. See the outage option. |
transport | callable | No | Sends every request through your own code. See Use your own transport. |
baseUrl | string | No | The API origin. The default is https://api.abusezero.com. It must use HTTPS, except HTTP on a loopback address for local testing. |
Pass exactly one of key and accessToken. The constructor throws an AbuseZero\AbuseZeroError for a missing or invalid credential (see PHP SDK errors), and an InvalidArgumentException for other invalid options.
Evaluate a claim
Call evaluate() before you grant the benefit. It calls POST /v1/evaluations. Pass the claim's idempotency key as idempotencyKey.
$evaluation = $abusezero->evaluate([
'benefit' => 'pro_trial',
'claim_id' => $claimId,
'subject' => ['external_id' => (string) $user->id, 'email' => $user->email],
'context' => ['ip' => $clientIp], // The visitor's IP from your trusted proxy settings.
'identifiers' => ['device_token' => $deviceToken],
'request' => ['method' => $method, 'url' => $url, 'headers' => $headers],
], idempotencyKey: "claim:{$claimId}");
if (($evaluation['status'] ?? null) === 'skipped') {
// AbuseZero decided nothing. Handle it as its own branch.
} elseif ($evaluation['result'] === 'deny') {
// Don't grant the benefit.
} else {
// "allow". When $evaluation['source'] is "local_outage", this is your outage setting.
}Send IDs as strings. Use one idempotency key per claim, and send the same key when you retry that claim. AbuseZero then returns the original result instead of evaluating the claim twice. Keys are 1 to 128 printable characters with no spaces.
$deviceToken comes from the standalone browser script on your page. It needs no npm package. Every field of the request is described in the Evaluations API reference. For which identifiers to send and how, see Send identifiers.
Results
evaluate() returns an array in one of three shapes. Check for status first, then source.
| Shape | Fields | Meaning |
|---|---|---|
| Evaluated | source: abusezero, id, result, risk, reason, outcome | AbuseZero evaluated the claim. result is allow or deny. |
| Skipped | source: abusezero, status: skipped, reason | The workspace couldn't run the evaluation, so there is no result. |
| Local outage | source: local_outage, claim_id, result, error | AbuseZero couldn't be reached. result is your outage setting, and error is the AbuseZeroError behind it. There's no id yet. |
Skip reasons are insufficient_credits, billing_overdue, service_inactive and benefit_paused. New reasons can appear within API v1, so handle a reason you don't recognize like any other skip. Your outage setting never applies to a skip. A skip is final for its idempotency key: once the workspace can run evaluations again, evaluate the claim with a new key.
risk, reason and outcome are described in Evaluations, and every reason code in Reason codes. Responses can gain new fields and values within v1, and the SDK passes them through.
The outage option
outage decides what evaluate() does when AbuseZero can't be reached or can't finish the request in time:
throw:evaluate()throws theAbuseZeroError, and your code decides.allowordeny:evaluate()returns alocal_outageresult with that decision and the error.
These are always thrown, whatever your setting:
- Rate limits (
429). Request volume can never switch protection off. - Errors that aren't retryable, such as an invalid request or a revoked key.
A local_outage result was decided by your code, not by AbuseZero, and has no evaluation to report an outcome on. When AbuseZero is reachable again, evaluate the same claim with the same idempotency key to get AbuseZero's result, then report the outcome on that evaluation. See Handle outages and retries.
Retries
Every call runs within a request budget: 1.8 seconds for evaluate() and 5 seconds for other methods, including waits. events() adds 5 seconds to the wait you request. Inside the budget, the SDK makes up to three attempts. It retries network failures, 429, 502, 503 and 504 responses, and any error AbuseZero marks retryable. Each retry waits at least as long as the response's Retry-After header asks, and sends the same body and idempotency key, so a retried write is never applied twice.
When the budget runs out, the call fails with DEADLINE_EXCEEDED. When AbuseZero can't be reached or the response doesn't arrive complete, it fails with TRANSPORT_ERROR. When a response arrives but can't be used, it fails with INVALID_RESPONSE. All three are retryable: send the same call with the same idempotency key to recover its result before acting on the claim.
Report an outcome
After you grant the benefit, report the outcome on the evaluation:
$abusezero->outcome(['outcome' => 'granted'], ['id' => $evaluation['id']], "grant:{$claimId}");Report only after your own grant succeeds. If reporting fails, retry with the same idempotency key.
Hash phone numbers and custom identifiers
Send phone numbers and custom identifiers as keyed hashes made with a secret only your server holds:
$secret = getenv('IDENTIFIER_HASH_SECRET');
$phone = AbuseZero\Helpers::createPhoneHash($secret, 'v1', '+14155550123');
$license = AbuseZero\Helpers::createCustomIdentifier($secret, 'v1', 'license_id', $licenseId);
$evaluation = $abusezero->evaluate([
// benefit, claim_id, subject and context as above
'identifiers' => ['device_token' => $deviceToken, 'phone_hash' => $phone, 'phone_verified' => true, 'custom' => [$license]],
], idempotencyKey: "claim:{$claimId}");createPhoneHash() takes an E.164 phone number. createCustomIdentifier() takes the identifier's key and its value. Both return the hash objects the API accepts, and refuse an empty secret. Register a custom identifier's key before you send it. Use the same secret and key version in every application that should recognize the same people. See Send identifiers.
Send the incoming request
Pass the request your server received as request, with its method, full URL and headers. headers maps each header name to a string or a list of strings, as getallheaders() or your framework returns them. The SDK leaves out credential headers, such as Authorization and Cookie, and keeps the request object within its limits. The SDK doesn't infer the client's IP address: send context.ip from your trusted proxy settings.
Verify webhooks
$event = AbuseZero\Helpers::verifyWebhook(
$rawBody, // The request body exactly as received.
$headers,
[getenv('ABUSEZERO_WEBHOOK_SECRET'), getenv('ABUSEZERO_WEBHOOK_SECRET_PREVIOUS')],
);verifyWebhook() checks an AbuseZero webhook request and returns its event. It throws AbuseZero\WebhookVerificationError when the request isn't signed with the endpoint's whsk_ secret, was changed, or is more than 5 minutes old. A fourth argument changes the tolerance, in seconds. During a secret rotation, pass both secrets; an entry that isn't set is skipped. A secret that isn't a complete whsk_ signing secret throws an InvalidArgumentException. Reply with a 2xx status within 10 seconds and process the event afterwards. An event can arrive more than once: skip IDs you already handled. See Receive webhooks.
Methods and pagination
API.md in the package lists every method with its HTTP operation. Pass fields in the input array, path fields such as id in the second argument, and the idempotency key in the third. Leave out a field to use its default. Methods marked Required in API.md, including dryRunEvaluation(), need an idempotency key.
$page = $abusezero->benefits(['limit' => 20]);
while (true) {
foreach ($page['data'] as $benefit) {
// Handle $benefit.
}
if ($page['next_cursor'] === null) break;
$page = $abusezero->benefits(['limit' => 20, 'cursor' => $page['next_cursor']]);
}Keep IDs and cursors as strings. events() always returns next_cursor: save it, and read again straight away while has_more is true. Management operations need an OAuth sign-in or a machine client: API keys never hold operations:management. See Keys and access.
Public API
AbuseZero\PublicClient calls the public API: it reads prices, the developer docs, help articles, the API's references, legal documents, the changelog, the blog, versions and service status, contacts sales or support, and starts agent onboarding. It needs no key or sign-in.
$public = new AbuseZero\PublicClient();
$quote = $public->priceQuote(['plan' => 'pro', 'interval' => 'year']);Use your own transport
Pass a transport callable to send requests through your own code, such as a proxy or a test double. It receives the method, URL, headers, body and the remaining seconds, and returns ['status' => …, 'headers' => […], 'body' => …] with lowercase header names. It must honor the remaining time, verify TLS and refuse redirects, as the built-in transport does. To report a network failure, throw new AbuseZero\AbuseZeroError('TRANSPORT_ERROR', $message, retryable: true): the SDK retries it and applies your outage setting. Any other exception stops the call and reaches your code unchanged, with no retry.
PHP SDK errors
Failed calls throw an AbuseZero\AbuseZeroError.
| Property or method | Description |
|---|---|
errorCode | The error code, such as CURSOR_INVALID. |
getMessage() | What to do next, written for a developer. |
status | The HTTP status. Errors the SDK raises before sending use 401 for credential errors, 403 for OAUTH_REQUIRED and 422 for the others. INVALID_RESPONSE uses 502, and 0 means no response arrived. |
requestId | The X-Request-ID of the failed request, when there is one. Include it when you contact support. |
retryable | true when the same call, with the same idempotency key, can succeed. |
docsUrl | The error code reference's section for this error, when AbuseZero sent one. |
REST API error codes are listed in REST API errors. The SDK adds these, raised before a request is sent or when a response can't be used:
| Code | Meaning |
|---|---|
CREDENTIAL_REQUIRED | Pass exactly one of key and accessToken. |
INVALID_KEY | Use a secret key (sk_…) or restricted key (rk_…). |
INVALID_TOKEN | Use the access token from an OAuth sign-in or a machine client. |
WORKSPACE_REQUIRED | Pass workspace with an OAuth access token. |
OAUTH_REQUIRED | The method needs operations:management, which API keys never hold. Use an OAuth sign-in or a machine client. |
INVALID_IDEMPOTENCY_KEY | The method needs an idempotency key of 1 to 128 printable characters with no spaces. |
INVALID_REQUEST | The input doesn't match the API contract. The message names the field. |
DEADLINE_EXCEEDED | The request budget ran out. Retry with the same idempotency key. |
TRANSPORT_ERROR | AbuseZero couldn't be reached, or the response didn't arrive complete. Retry with the same idempotency key. |
INVALID_RESPONSE | AbuseZero's response couldn't be used. Retry with the same idempotency key before acting on the claim. |
HTTP_ERROR | AbuseZero answered with an HTTP error or a redirect that has no error code. status has the HTTP status, and retryable says whether to retry with the same idempotency key. |
Other invalid options, path fields, a request without a method, full URL and headers, and invalid helper arguments throw an InvalidArgumentException. Nothing is sent in any of these cases.
How is this guide?
Last updated on
AbuseZero Go SDK
Use the AbuseZero Go SDK, github.com/abusezero/abusezero-go, to evaluate claims, report outcomes and manage your workspace from your Go server.
AbuseZero Ruby SDK
Use the AbuseZero Ruby SDK, the abusezero gem, to evaluate claims, report outcomes and manage your workspace from your Ruby server.