Skip to content
RocketVerifierDOCS

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.

Terminal
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
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.

OptionDefaultWhat it does
api_keynoneThe API key, when the first argument is null.
access_tokennoneAn OAuth access token (rv_at_...). Calls run on the connected user's credits.
refresh_tokennoneOAuth refresh token for automatic refresh.
oauthnoneA RocketVerifier\OAuth instance used for automatic refresh.
on_token_refreshnonecallable(TokenSet) called after a refresh. Persist the new token here.
base_urlhttps://api.rocketverifier.comAPI base URL.
timeout30Seconds per request.
max_retries3Retries on 429, timeouts and network errors. 0 turns retries off.
headers[]Extra headers on every request, applied last.
http_clientCurlHttpClientAny 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.

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 explains every status and sub_status.

Result fields#

VerificationResult exposes readonly camelCase properties.

PropertyTypeAPI field
email, status, reasonstringemail, status, reason
subStatusstringsub_status, "none" when not specific
scoreint|float|nullscore
catchAllVerdict?stringcatch_all_verdict
didYouMean?stringdid_you_mean
verifiedAt?stringverified_at
provider?stringprovider
domainDomainInfoname, acceptAll (?bool), disposable (bool), free (bool), acceptAllConfidence, acceptAllVerdict
account?AccountInforole (bool), disabled (?bool), fullMailbox (?bool)
dns?arraydns
authenticationScoreint|float|nullauthentication_score
deliverabilityTier?stringdeliverability_tier
toxic, abuse?string"yes", "no" or "unknown"
spamTrap?boolspam_trap
activity, evidence?arrayactivity, evidence
rawarrayThe 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.

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');
MethodReturns
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.

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
$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.

Manage monitors#

$rv->monitors schedules list health re-verification and SPF, DKIM and DMARC checks. See the monitors API.

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.

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
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 covers app registration.

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().

ExceptionThrown when
AuthenticationException401, or no credential passed.
InvalidTokenException401 invalid_token for an OAuth token that cannot be refreshed.
InsufficientCreditsException402, or code insufficient_credits (including the 403 at zero balance).
RateLimitException429 after all retries. $retryAfter holds the seconds.
ValidationException400 or 422, or input rejected before sending.
PermissionDeniedException403, such as a missing scope or an IP allowlist.
NotFoundException404.
WebhookSignatureExceptionA delivery fails verification.
OAuthExceptionThe token, revoke or introspect endpoint returns an error.
RocketVerifierExceptionEvery other status, plus timeouts (timeout) and network failures (network_error).
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 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.
  • 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#

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