zero-bounce/sdk
Framework-agnostic PHP SDK for the ZeroBounce email validation API. Install via Composer, initialize with your API key, and call endpoints like getCredits. Supports base URL selection (Default/USA/EU) and works smoothly in Laravel apps.
## Getting Started
### Minimal Setup
1. **Installation**:
```bash
composer require zero-bounce/sdk
Ensure vendor/autoload.php is included in your project (Laravel handles this automatically).
First Use Case: Validate a single email in a Laravel controller or service:
use ZeroBounce\SDK\ZeroBounce;
ZeroBounce::Instance()->initialize(config('services.zerobounce.api_key'));
$response = ZeroBounce::Instance()->validate('user@example.com', request()->ip());
return $response->status; // 'valid', 'invalid', etc.
Where to Look First:
.env (e.g., ZEROBUNCE_API_KEY) and reference via config('services.zerobounce.api_key').API_DEFAULT_URL; override in initialize() if needed (e.g., ZBBaseUrl::API_USA_URL).try-catch for ZBException (e.g., invalid API responses).Single Email Validation:
// In a Laravel service or controller
public function validateEmail(string $email, ?string $ip = null): string {
return ZeroBounce::Instance()->validate($email, $ip)->status;
}
Batch Validation:
// Process a collection of emails (e.g., from a database)
public function validateBatch(array $emailsWithIps): array {
$batch = array_map(fn($item) => [$item['email'], $item['ip'] ?? null], $emailsWithIps);
$response = ZeroBounce::Instance()->validateBatch($batch);
return array_map(fn($item) => $item->status, $response->emailBatch);
}
Bulk File Processing:
// Queue a job for async file upload (Laravel example)
public function queueBulkValidation(string $filePath, string $returnUrl) {
dispatch(new ProcessBulkValidationJob($filePath, $returnUrl));
}
// Job implementation
public function handle() {
$response = ZeroBounce::Instance()->sendFile(
$this->filePath,
1, // Email column index
$this->returnUrl,
true // Has header row
);
// Store $response->fileId for later status checks
}
Credit Management:
// Check credits before bulk operations
public function canProcessBulk(int $emailCount): bool {
$credits = ZeroBounce::Instance()->getCredits()->credits;
return $credits >= $emailCount;
}
Laravel Service Provider: Bind the SDK as a singleton for dependency injection:
public function register() {
$this->app->singleton(ZeroBounce::class, function () {
$instance = ZeroBounce::Instance();
$instance->initialize(config('services.zerobounce.api_key'));
return $instance;
});
}
Request Validation: Use Laravel’s validation to sanitize inputs before passing to ZeroBounce:
$validated = $request->validate([
'email' => 'required|email',
'ip' => 'nullable|ip',
]);
Async Processing: For bulk operations, use Laravel Queues to avoid timeouts:
// In a controller
$job = new ValidateBulkEmailsJob($emails);
dispatch($job)->onQueue('zerobounce');
File Handling:
Store uploaded files temporarily (e.g., in storage/app/zerobounce) and clean up after processing:
$filePath = $request->file('emails')->store('zerobounce');
// Process file...
Storage::delete($filePath);
API Key Exposure:
.env and config/services.php:
'zerobounce' => [
'api_key' => env('ZEROBUNCE_API_KEY'),
],
.env files in production.Credit Limits:
$credits = ZeroBounce::Instance()->getCredits()->credits;
if ($credits < $emailCount) {
throw new \RuntimeException('Insufficient credits for bulk operation.');
}
File Processing Quirks:
1 for email column).hasHeaderRow to true if your CSV has headers, even if empty.fileStatus is "Complete". Check status first:
$status = ZeroBounce::Instance()->fileStatus($fileId)->fileStatus;
if ($status === 'Complete') {
ZeroBounce::Instance()->deleteFile($fileId);
}
Error Handling:
ZBException for non-200 responses or JSON errors. Catch and log:
try {
$response = ZeroBounce::Instance()->validate($email);
} catch (ZBException $e) {
Log::error('ZeroBounce API error: ' . $e->getMessage());
return response()->json(['error' => 'Validation failed'], 500);
}
ZeroBounce::getFileJsonIndicatesError($jsonString).Rate Limiting:
$attempts = 0;
$maxAttempts = 3;
while ($attempts < $maxAttempts) {
try {
return ZeroBounce::Instance()->validate($email);
} catch (ZBException $e) {
if ($attempts === $maxAttempts - 1) throw $e;
sleep(2 ** $attempts); // Exponential backoff
$attempts++;
}
}
IP Addresses:
validate(), passing an IP improves accuracy. Use Laravel’s request()->ip() or a trusted proxy IP.Enable Guzzle Debugging: Configure the SDK to log HTTP requests/responses (requires modifying the SDK or using a middleware):
// Example: Override SDK initialization (if possible)
ZeroBounce::Instance()->setHttpClient(new \GuzzleHttp\Client([
'debug' => fopen('zerobounce_debug.log', 'w'),
]));
Validate API Responses:
Use json_last_error() to debug malformed JSON responses:
$json = file_get_contents('php://input');
if (json_last_error() !== JSON_ERROR_NONE) {
throw new \RuntimeException('Invalid JSON: ' . json_last_error_msg());
}
Test with Mock Data: For unit tests, mock the SDK’s HTTP client:
$mockHandler = new \GuzzleHttp\Handler\MockHandler([
new \GuzzleHttp\Psr7\Response(200, [], json_encode(['status' => 'valid'])),
]);
$client = new \GuzzleHttp\Client(['handler' => $mockHandler]);
ZeroBounce::Instance()->setHttpClient($client);
Custom Response Handling: Extend the SDK’s response objects for your needs:
class CustomValidateResponse extends \ZeroBounce\SDK\ZBValidateResponse {
public function isValid(): bool {
return $this->status === 'valid' || $this->status === 'accept_all';
}
}
Retry Logic: Create a decorator for the SDK to add retries:
class RetryableZeroBounce {
public function validate(string $email, ?string $ip = null) {
return $this->withRetry(fn() => ZeroBounce::Instance()->validate($email, $ip));
}
private function withRetry(callable $callback) {
// Implement retry logic here
}
}
Event Dispatching:
Trigger Laravel events after API calls (e.g., EmailValidated):
event(new EmailValidated($email, $response->status));
Caching: Cache validation results (e.g., 24 hours) to reduce API calls:
$cacheKey = "zb_validate_{$email}";
return Cache::remember($cacheKey, now()->addHours(24), function() use ($
How can I help you explore Laravel packages today?