# PHP SDK

Source: https://docs.rocketverifier.com/sdks/php

> Run composer require rocketverifier/sdk, create new RocketVerifier\RocketVerifier($apiKey) and call $rv->verify($email). The package needs only PHP 8.1 and ext-curl, returns readonly typed models with yes and no flags as booleans, and retries safely with a stable Idempotency-Key.

`rocketverifier/sdk` is the official PHP library for the RocketVerifier API. It covers real-time verification, bulk jobs from a list or a file, progress and downloads, webhooks, monitors, credits and RocketVerifier Connect OAuth, with no Composer runtime dependencies.

## Install the SDK

Install with Composer. Classes live in the `RocketVerifier` namespace and load through PSR-4.

Terminal:

```bash
composer require rocketverifier/sdk
```

## Create a client

Pass your API key as the first argument and any options as an array. Read the key from `ROCKETVERIFIER_API_KEY` so it never lands in source control.

PHP:

```php
<?php
require 'vendor/autoload.php';

use RocketVerifier\RocketVerifier;

$rv = new RocketVerifier(getenv('ROCKETVERIFIER_API_KEY'), [
    'timeout' => 15,
    'max_retries' => 5,
]);
```

The constructor throws `AuthenticationException` without a credential and `ValidationException` for an unknown option. Live keys start with `rv_live_`; sandbox keys start with `rv_test_` and accept only [sandbox addresses](https://docs.rocketverifier.com/sandbox). See [authentication](https://docs.rocketverifier.com/authentication).

| Option | Default | What it does |
| --- | --- | --- |
| `api_key` | none | The API key, when the first argument is `null`. |
| `access_token` | none | An OAuth access token (`rv_at_...`). Calls run on the connected user's credits. |
| `refresh_token` | none | OAuth refresh token for automatic refresh. |
| `oauth` | none | A `RocketVerifier\OAuth` instance used for automatic refresh. |
| `on_token_refresh` | none | `callable(TokenSet)` called after a refresh. Persist the new token here. |
| `base_url` | `https://api.rocketverifier.com` | API base URL. |
| `timeout` | `30` | Seconds per request. |
| `max_retries` | `3` | Retries on 429, timeouts and network errors. `0` turns retries off. |
| `headers` | `[]` | Extra headers on every request, applied last. |
| `http_client` | `CurlHttpClient` | Any `HttpClientInterface` implementation. |

## Verify an email

`$rv->verify($email, $idempotencyKey = null, $timeout = null)` checks one address with [`POST /v1/verify`](https://docs.rocketverifier.com/api/verify) and returns a `VerificationResult`. Branch on `status` and read `subStatus` for the reason.

PHP:

```php
$result = $rv->verify('deliverable@sandbox.rocketverifier.com');

switch ($result->status) {
    case 'deliverable':
        break; // send
    case 'risky':
        echo "Review: {$result->subStatus} {$result->catchAllVerdict}\n";
        break;
    case 'undeliverable':
        echo "Remove. Suggestion: {$result->didYouMean}\n";
        break;
    case 'unknown':
        break; // free: check again later
}
```

`$timeout` is the server side verification timeout in seconds. The SDK accepts 5 to 60 and grows the HTTP timeout to cover it. Input without an `@` throws `ValidationException` before any request is sent. The [reading results guide](https://docs.rocketverifier.com/results) explains every status and `sub_status`.

### Result fields

`VerificationResult` exposes readonly camelCase properties.

| Property | Type | API field |
| --- | --- | --- |
| `email`, `status`, `reason` | `string` | `email`, `status`, `reason` |
| `subStatus` | `string` | `sub_status`, `"none"` when not specific |
| `score` | `int\|float\|null` | `score` |
| `catchAllVerdict` | `?string` | `catch_all_verdict` |
| `didYouMean` | `?string` | `did_you_mean` |
| `verifiedAt` | `?string` | `verified_at` |
| `provider` | `?string` | `provider` |
| `domain` | `DomainInfo` | `name`, `acceptAll` (`?bool`), `disposable` (`bool`), `free` (`bool`), `acceptAllConfidence`, `acceptAllVerdict` |
| `account` | `?AccountInfo` | `role` (`bool`), `disabled` (`?bool`), `fullMailbox` (`?bool`) |
| `dns` | `?array` | `dns` |
| `authenticationScore` | `int\|float\|null` | `authentication_score` |
| `deliverabilityTier` | `?string` | `deliverability_tier` |
| `toxic`, `abuse` | `?string` | `"yes"`, `"no"` or `"unknown"` |
| `spamTrap` | `?bool` | `spam_trap` |
| `activity`, `evidence` | `?array` | `activity`, `evidence` |
| `raw` | `array` | The full response |

`isDeliverable()`, `isUndeliverable()`, `isRisky()` and `isUnknown()` test the status. Flags become real booleans: `bool` properties are `true` only for `"yes"`, and `?bool` properties are `null` when the server reports `"unknown"`.

## Verify a list in bulk

`$rv->batch` runs bulk jobs of up to 100,000 unique addresses. The [batch API reference](https://docs.rocketverifier.com/api/batch) covers the endpoints.

PHP:

```php
$job = $rv->batch->create(
    ['deliverable@sandbox.rocketverifier.com', 'undeliverable@sandbox.rocketverifier.com'],
    'October signups'
);

$done = $rv->batch->wait($job->jobId, pollInterval: 3, onProgress: function ($j) {
    echo "{$j->processedEmails}/{$j->totalEmails}\n";
});

$rows = $rv->batch->download($done->id, parse: true, filter: 'send_safe');
```

| Method | Returns |
| --- | --- |
| `create(array $emails, ?string $name = null, ?string $idempotencyKey = null)` | `BatchCreateResult` with `jobId`, `totalEmails`, `estimatedTimeSeconds`, `creditsToUse`, `creditsRemaining` |
| `get($jobId)` | `BatchJob` with counts, `progressPercent` and timestamps |
| `progress($jobId)` | `JobProgress` with `percent`, `counts`, `countsByStatus`, `ratePerMinute`, `etaSeconds` |
| `wait($jobId, $pollInterval = 5, $timeout = 300, $onProgress = null)` | The final `BatchJob`. Seconds. Throws code `timeout` past `$timeout`. |
| `results($jobId, $page = 1, $limit = 100, $classification = null)` | `JobResultsPage`. `limit` up to 1000. |
| `iterateResults($jobId, $pageSize = 1000, $classification = null)` | A `Generator` of `JobResult` |
| `allResults($jobId, $classification = null)` | `list<JobResult>` |
| `download($jobId, $format = 'csv', $parse = false, $filter = null, $includeOriginal = false)` | CSV string, parsed rows, or the decoded JSON array |
| `list($page = 1, $limit = 20, $status = null)` | `JobsPage`. `limit` up to 100. |
| `delete($jobId)`, `cancel($jobId)` | `JobDeleteResult` with `refundedCredits` |

`wait()` also returns when a previewed upload reaches `awaiting_confirmation`. `download()` filters by `deliverable`, `undeliverable`, `risky`, `unknown` or `send_safe`, and `includeOriginal` joins upload jobs with your file's own columns.

## Upload a file

`$rv->batch->upload([...])` creates a job from a CSV, TSV, TXT or XLSX file of up to 50 MB, or from a public HTTPS URL. Pass exactly one of `file` or `source_url`. See [bulk upload](https://docs.rocketverifier.com/api/bulk-upload).

PHP:

```php
$upload = $rv->batch->upload([
    'file' => 'contacts.csv',
    'email_column' => 'Work Email',
    'preview' => true,
]);

$res = $rv->batch->preview($upload->jobId);
while ($res->pending) {
    sleep(2);
    $res = $rv->batch->preview($upload->jobId);
}
echo $res->preview['estimated_bounce_rate'], "\n";

$confirmed = $rv->batch->confirm($upload->jobId);
echo $confirmed->creditsCharged, "\n";
```

- `file` is a local path, an open stream resource, or the bytes as a string (then pass `filename`).
- Other keys: `filename`, `source_url`, `name`, `email_column`, `column_mapping` (array), `preview`, `callback_url`, `content_type` and `idempotency_key`.
- `BatchUploadResult` has `jobId`, `status`, `preview`, `statusUrl`, `progressUrl` and `callbackSecret`, set once when you pass `callback_url`.
- `confirm()` charges and starts the job. A job is never charged twice, so it is safe to retry.

## Check a domain, credits and account

PHP:

```php
$info = $rv->domain->check('northwind.io'); // domain, mxRecords, provider, disposable, hasValidMx
$credits = $rv->getCredits();               // credits, usedToday, usedThisMonth
$me = $rv->getMe();                         // email, accountType, organization, credits, authType, scopes, app
```

`getMe()` calls [`GET /v1/me`](https://docs.rocketverifier.com/api/account).

## Manage monitors

`$rv->monitors` schedules list health re-verification and SPF, DKIM and DMARC checks. See the [monitors API](https://docs.rocketverifier.com/api/monitors).

PHP:

```php
$monitor = $rv->monitors->create([
    'name' => 'Brand domain',
    'type' => 'domain_auth',
    'domain' => 'northwind.io',
]);
$rv->monitors->update($monitor->id, ['frequency' => 'daily']);
```

- `create()` takes `name`, `type`, `frequency` (default `weekly`), `domain`, `emails`, `alert_threshold` (default 5) and `idempotency_key`.
- `update($id, $fields)` takes `name`, `frequency`, `is_active`, `alert_threshold`, `domain` and `emails`; `null` values are left unchanged.
- `list()`, `get($id)`, `delete($id)`, `runs($id, $page = 1, $limit = 20)` and `runNow($id, $idempotencyKey = null)` complete the set. `list_health` runs cost 1 credit per address.

## Manage webhook endpoints

`$rv->webhooks` registers HTTPS endpoints for events such as `job.completed`. It needs the `webhooks:manage` scope. See the [webhooks API](https://docs.rocketverifier.com/api/webhooks).

PHP:

```php
$hook = $rv->webhooks->create(
    'https://northwind.io/hooks/rocketverifier',
    events: ['job.completed', 'job.failed', 'credits.low']
);
// Store $hook->secret now: it is shown only once.
```

The resource also has `listEvents()`, `list()`, `get($id)`, `update($id, ['name' => ..., 'url' => ..., 'events' => ..., 'is_active' => ...])`, `delete($id)`, `test($id)`, `logs($id, $page = 1, $limit = 50, $status = null)` and `rotateSecret($id)`.

## Verify webhook signatures

`Webhook::constructEvent()` checks the `X-RocketVerifier-Signature` header and the timestamp, then returns the decoded event array. Pass the raw body exactly as received.

PHP:

```php
use RocketVerifier\Webhook;
use RocketVerifier\Exception\WebhookSignatureException;

try {
    $event = Webhook::constructEvent(
        file_get_contents('php://input'),
        $_SERVER['HTTP_X_ROCKETVERIFIER_SIGNATURE'] ?? null,
        getenv('ROCKETVERIFIER_WEBHOOK_SECRET')
    );
} catch (WebhookSignatureException $e) {
    http_response_code(400);
    exit($e->reason);
}

if ($event['event'] === 'job.completed') {
    error_log('Job ' . $event['data']['job_id'] . ' finished');
}
http_response_code(200);
```

- `Webhook::verifySignature($rawBody, $header, $secret, $tolerance = 300, $now = null)` returns a `bool`.
- `WebhookSignatureException::$reason` is `missing_secret`, `missing_header`, `malformed_header`, `timestamp_out_of_tolerance`, `signature_mismatch` or `invalid_json`.
- `Webhook::generateSignatureHeader($rawBody, $secret)` builds a valid header for testing your endpoint.

## Act for a user with OAuth

`RocketVerifier\OAuth` runs the RocketVerifier Connect authorization code flow with PKCE. The [OAuth guide](https://docs.rocketverifier.com/oauth) covers app registration.

PHP:

```php
use RocketVerifier\OAuth;
use RocketVerifier\RocketVerifier;

$oauth = new OAuth(
    getenv('RV_CLIENT_ID'),
    getenv('RV_CLIENT_SECRET'),
    'https://northwind.io/rocketverifier/callback'
);

$auth = $oauth->authorizeUrl(['verify:bulk', 'account:read']);
$_SESSION['rv_state'] = $auth->state;
$_SESSION['rv_verifier'] = $auth->codeVerifier;
header('Location: ' . $auth->url);

// On the callback, after checking state:
$tokens = $oauth->exchangeCode($_GET['code'], $_SESSION['rv_verifier']);

$userRv = new RocketVerifier(null, [
    'access_token' => $tokens->accessToken,
    'refresh_token' => $tokens->refreshToken,
    'oauth' => $oauth,
    'on_token_refresh' => fn ($t) => saveTokens($userId, $t),
]);
```

- `new OAuth($clientId, $clientSecret = null, $redirectUri = null, $issuer, $tokenEndpointAuthMethod = 'client_secret_basic', $httpClient = null, $timeout = 30)`. Omit the secret for public clients.
- `authorizeUrl($scopes, $redirectUri, $state, $codeVerifier, $resource, $prompt)`, `exchangeCode()`, `refresh()`, `revoke($token, $tokenTypeHint)` and `introspect()` complete the flow. `OAuth::generatePkcePair()` and `OAuth::SCOPES` are available for custom flows.
- `TokenSet` has `accessToken`, `refreshToken`, `tokenType`, `expiresIn`, `expiresAt` (Unix seconds) and `scopes`.
- On a 401 `invalid_token` the client refreshes once, retries and calls `on_token_refresh`. Without refresh configured it throws `InvalidTokenException`. A rejected refresh token throws `OAuthException` with `$error === 'invalid_grant'`.
- `$rv->setTokens($accessToken, $refreshToken)` swaps in tokens refreshed elsewhere.

## Handle errors

Every exception extends `RocketVerifier\Exception\RocketVerifierException`, with `getErrorCode()`, `getStatusCode()` and `getDetails()`.

| Exception | Thrown when |
| --- | --- |
| `AuthenticationException` | 401, or no credential passed. |
| `InvalidTokenException` | 401 `invalid_token` for an OAuth token that cannot be refreshed. |
| `InsufficientCreditsException` | 402, or code `insufficient_credits` (including the 403 at zero balance). |
| `RateLimitException` | 429 after all retries. `$retryAfter` holds the seconds. |
| `ValidationException` | 400 or 422, or input rejected before sending. |
| `PermissionDeniedException` | 403, such as a missing scope or an IP allowlist. |
| `NotFoundException` | 404. |
| `WebhookSignatureException` | A delivery fails verification. |
| `OAuthException` | The token, revoke or introspect endpoint returns an error. |
| `RocketVerifierException` | Every other status, plus timeouts (`timeout`) and network failures (`network_error`). |

PHP:

```php
use RocketVerifier\Exception\InsufficientCreditsException;
use RocketVerifier\Exception\RateLimitException;
use RocketVerifier\Exception\RocketVerifierException;

try {
    $rv->verify('maya@northwind.io');
} catch (RateLimitException $e) {
    sleep($e->retryAfter ?? 60);
} catch (InsufficientCreditsException $e) {
    // top up
} catch (RocketVerifierException $e) {
    error_log($e->getErrorCode() . ': ' . $e->getMessage());
}
```

The [errors reference](https://docs.rocketverifier.com/errors) lists every API error code.

## Retries and timeouts

- **Rate limits (429):** retried up to `max_retries` times, waiting for the `Retry-After` seconds, or 60 seconds when the header is missing. See [rate limits](https://docs.rocketverifier.com/rate-limits).
- **Timeouts and network errors:** retried with 1, 2 and 3 second waits.
- **Other errors:** thrown straight away.
- **Idempotency:** every POST, PUT and PATCH sends an `Idempotency-Key` reused across retries of that call.

## Next steps

- [Reading results](https://docs.rocketverifier.com/results)
Every status and sub_status, what it costs and what to do with it.
- [All SDKs](https://docs.rocketverifier.com/sdks)
Compare the Node.js, Python, Go, PHP and Ruby libraries and the CLI.

## Frequently asked questions

### Which PHP version does the SDK need?

PHP 8.1 or later with the curl, json and hash extensions. There are no Composer runtime dependencies.

### Can I use Guzzle or my framework's HTTP client?

Yes. Implement `RocketVerifier\Http\HttpClientInterface` (one `send` method) and pass it as the `http_client` option. The default is the bundled cURL client.

### Which errors does the SDK retry?

Rate limits (429), timeouts and network errors, up to `max_retries` times (3 by default). Other 4xx and 5xx responses throw straight away.

### Why compare flags with booleans instead of strings?

The SDK converts the API's `"yes"` and `"no"` strings, so `$result->domain->disposable` is a real `bool`. The string `"no"` is truthy in PHP, which is why the conversion matters.
