Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Sdk Laravel Package

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.

View on GitHub
Deep Wiki
Context7
## 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).

  1. 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.
    
  2. Where to Look First:

    • API Key: Store in .env (e.g., ZEROBUNCE_API_KEY) and reference via config('services.zerobounce.api_key').
    • Base URL: Defaults to API_DEFAULT_URL; override in initialize() if needed (e.g., ZBBaseUrl::API_USA_URL).
    • Error Handling: Wrap calls in try-catch for ZBException (e.g., invalid API responses).

Implementation Patterns

Core Workflows

  1. 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;
    }
    
  2. 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);
    }
    
  3. 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
    }
    
  4. Credit Management:

    // Check credits before bulk operations
    public function canProcessBulk(int $emailCount): bool {
        $credits = ZeroBounce::Instance()->getCredits()->credits;
        return $credits >= $emailCount;
    }
    

Integration Tips

  • 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);
    

Gotchas and Tips

Pitfalls

  1. API Key Exposure:

    • Never hardcode API keys. Use Laravel’s .env and config/services.php:
      'zerobounce' => [
          'api_key' => env('ZEROBUNCE_API_KEY'),
      ],
      
    • Restrict access to .env files in production.
  2. Credit Limits:

    • Batch operations consume credits per email. Always check remaining credits before bulk operations:
      $credits = ZeroBounce::Instance()->getCredits()->credits;
      if ($credits < $emailCount) {
          throw new \RuntimeException('Insufficient credits for bulk operation.');
      }
      
  3. File Processing Quirks:

    • Column Indices: Start at 1 (not 0) for file columns (e.g., 1 for email column).
    • Header Rows: Set hasHeaderRow to true if your CSV has headers, even if empty.
    • File Deletion: Files can only be deleted when fileStatus is "Complete". Check status first:
      $status = ZeroBounce::Instance()->fileStatus($fileId)->fileStatus;
      if ($status === 'Complete') {
          ZeroBounce::Instance()->deleteFile($fileId);
      }
      
  4. Error Handling:

    • The SDK throws 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);
      }
      
    • For custom error parsing, use ZeroBounce::getFileJsonIndicatesError($jsonString).
  5. Rate Limiting:

    • ZeroBounce enforces rate limits. Implement exponential backoff for retries:
      $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++;
          }
      }
      
  6. IP Addresses:

    • For validate(), passing an IP improves accuracy. Use Laravel’s request()->ip() or a trusted proxy IP.

Debugging Tips

  • 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);
    

Extension Points

  1. 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';
        }
    }
    
  2. 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
        }
    }
    
  3. Event Dispatching: Trigger Laravel events after API calls (e.g., EmailValidated):

    event(new EmailValidated($email, $response->status));
    
  4. 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 ($
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor