Libraries
PHP SDK
In short
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.
On this page
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.
- Package
- rocketverifier/sdk
- Version
- 1.0.0
- PHP
- 8.1+
- Extensions
- curl, json, hash
Install the SDK#
Install with Composer. Classes live in the RocketVerifier namespace and load through PSR-4.
composer require rocketverifier/sdkCreate 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
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. See 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 and returns a VerificationResult. Branch on status and read subStatus for the reason.
$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 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 covers the endpoints.
$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.
$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";fileis a local path, an open stream resource, or the bytes as a string (then passfilename).- Other keys:
filename,source_url,name,email_column,column_mapping(array),preview,callback_url,content_typeandidempotency_key. BatchUploadResulthasjobId,status,preview,statusUrl,progressUrlandcallbackSecret, set once when you passcallback_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#
$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, appgetMe() calls GET /v1/me.
Manage monitors#
$rv->monitors schedules list health re-verification and SPF, DKIM and DMARC checks. See the monitors API.
$monitor = $rv->monitors->create([
'name' => 'Brand domain',
'type' => 'domain_auth',
'domain' => 'northwind.io',
]);
$rv->monitors->update($monitor->id, ['frequency' => 'daily']);create()takesname,type,frequency(defaultweekly),domain,emails,alert_threshold(default 5) andidempotency_key.update($id, $fields)takesname,frequency,is_active,alert_threshold,domainandemails;nullvalues are left unchanged.list(),get($id),delete($id),runs($id, $page = 1, $limit = 20)andrunNow($id, $idempotencyKey = null)complete the set.list_healthruns 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.
$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.
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 abool.WebhookSignatureException::$reasonismissing_secret,missing_header,malformed_header,timestamp_out_of_tolerance,signature_mismatchorinvalid_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 covers app registration.
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)andintrospect()complete the flow.OAuth::generatePkcePair()andOAuth::SCOPESare available for custom flows.TokenSethasaccessToken,refreshToken,tokenType,expiresIn,expiresAt(Unix seconds) andscopes.- On a 401
invalid_tokenthe client refreshes once, retries and callson_token_refresh. Without refresh configured it throwsInvalidTokenException. A rejected refresh token throwsOAuthExceptionwith$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). |
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 lists every API error code.
Retries and timeouts#
- Rate limits (429): retried up to
max_retriestimes, waiting for theRetry-Afterseconds, or 60 seconds when the header is missing. See 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-Keyreused across retries of that call.
Next steps#
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.
Updated 11 November 2026Suggest an edit