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

Resend Php Laravel Package

resend/resend-php

Resend PHP is an official PHP 8.1+ client for the Resend email API. Install via Composer and send transactional emails with a clean, simple interface (e.g., $resend->emails->send) in PHP or Laravel.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require resend/resend-php
    

    Add to composer.json if using Laravel:

    "require": {
        "resend/resend-php": "^1.3"
    }
    
  2. First Use Case: Sending an Email Initialize the client in a service or controller:

    use Resend\ResendClient;
    
    $resend = new ResendClient('re_your_api_key_here');
    $response = $resend->emails->send([
        'from' => 'acme@yourdomain.com',
        'to' => ['user@example.com'],
        'subject' => 'Welcome!',
        'html' => '<p>Hello, welcome to our platform!</p>',
    ]);
    
  3. Where to Look First


Implementation Patterns

Core Workflows

  1. Transactional Emails

    $resend->emails->send([
        'from' => 'notifications@yourdomain.com',
        'to' => ['user@example.com'],
        'subject' => 'Your order is confirmed',
        'text' => 'Order #12345 is processing...',
        'headers' => ['X-Custom-ID' => 'order_123'],
    ]);
    
  2. Templated Emails

    $templateId = 'your-template-id';
    $response = $resend->emails->send([
        'from' => 'marketing@yourdomain.com',
        'to' => ['user@example.com'],
        'template_id' => $templateId,
        'template_data' => ['name' => 'John'],
    ]);
    
  3. Batch Emails

    $batch = $resend->batches->create([
        'emails' => [
            ['to' => 'user1@example.com', 'subject' => 'Batch Email 1'],
            ['to' => 'user2@example.com', 'subject' => 'Batch Email 2'],
        ],
        'options' => ['batch_id' => 'unique_batch_123'],
    ]);
    
  4. Contacts Management

    // Create/update a contact
    $contact = $resend->contacts->upsert([
        'email' => 'user@example.com',
        'first_name' => 'John',
        'last_name' => 'Doe',
    ]);
    
    // Add to a segment
    $resend->contacts->segments->upsert($contact->id, ['segment_id' => 'premium_users']);
    
  5. Webhooks (Laravel Integration)

    // In a Laravel route (e.g., `webhook/resend`)
    $payload = json_decode(request()->getContent(), true);
    $event = $resend->webhooks->verify($payload, request()->header('X-Resend-Signature'));
    

Laravel-Specific Patterns

  1. Service Provider Binding

    // app/Providers/ResendServiceProvider.php
    public function register()
    {
        $this->app->singleton(ResendClient::class, function ($app) {
            return new ResendClient(config('services.resend.api_key'));
        });
    }
    
  2. Mailable Integration Extend Laravel’s Mailable to use Resend:

    use Resend\ResendClient;
    
    class WelcomeMail extends Mailable
    {
        public function build()
        {
            $resend = app(ResendClient::class);
            return $this->withSwiftMessage(function ($message) use ($resend) {
                $message->setFrom('no-reply@yourdomain.com');
                $message->setTo('user@example.com');
                $message->setSubject('Welcome!');
                // Use Resend’s API for advanced features (e.g., templates)
            });
        }
    }
    
  3. Config File

    // config/services.php
    'resend' => [
        'api_key' => env('RESEND_API_KEY'),
        'api_url' => env('RESEND_API_URL', 'https://api.resend.com'), // Custom URL support
    ];
    
  4. Event Listeners Listen to Resend webhook events:

    // app/Listeners/HandleResendWebhook.php
    public function handle($event)
    {
        $payload = $event->payload;
        if ($payload->event === 'email.bounce') {
            // Handle bounce logic
        }
    }
    

Gotchas and Tips

Common Pitfalls

  1. API Key Exposure

    • Never hardcode API keys in source files. Use Laravel’s .env:
      RESEND_API_KEY=re_your_api_key_here
      
    • Restrict keys to specific IPs in Resend’s dashboard.
  2. Idempotency Keys

    • Use idempotency_key for batch emails to avoid duplicates:
      $resend->batches->create([
          'emails' => [...],
          'options' => ['idempotency_key' => uniqid()],
      ]);
      
  3. Rate Limits

    • Resend enforces rate limits (e.g., 1000 emails/hour for free tier). Handle 429 Too Many Requests:
      try {
          $resend->emails->send(...);
      } catch (ResendException $e) {
          if ($e->getCode() === 429) {
              sleep(60); // Retry after 60 seconds
              retry();
          }
      }
      
  4. Webhook Verification

    • Always verify webhook signatures to prevent spoofing:
      $event = $resend->webhooks->verify($payload, $signature);
      if (!$event) {
          abort(401, 'Invalid webhook signature');
      }
      
  5. Empty Email Bodies

    • Ensure text or html is provided; empty bodies may fail silently.

Debugging Tips

  1. Enable Debug Mode

    $resend = new ResendClient('api_key', [
        'debug' => true, // Logs requests/responses to stderr
    ]);
    
  2. Inspect Responses

    $response = $resend->emails->send([...]);
    if ($response->error) {
        logger()->error('Resend error:', ['error' => $response->error]);
    }
    
  3. Common Errors

    • invalid_parameter: Validate required fields (from, to, subject).
    • invalid_to_address: Check email format (use filter_var($email, FILTER_VALIDATE_EMAIL)).
    • rate_limit_exceeded: Implement exponential backoff.

Extension Points

  1. Custom HTTP Client Override the default Guzzle client for retries/timeouts:

    $client = new ResendClient('api_key', [
        'http_client' => new \GuzzleHttp\Client([
            'timeout' => 30,
            'connect_timeout' => 5,
        ]),
    ]);
    
  2. Extend Resources Add custom methods to the client:

    $resend->extend('custom', function ($client) {
        return new class($client) {
            public function sendSMS($to, $message) {
                return $client->post('/sms', ['body' => compact('to', 'message')]);
            }
        };
    });
    
  3. Laravel Facade Create a facade for cleaner syntax:

    // app/Facades/Resend.php
    class Resend extends \Illuminate\Support\Facades\Facade {
        protected static function getFacadeAccessor() {
            return 'resend';
        }
    }
    

    Usage:

    Resend::emails()->send([...]);
    
  4. Testing Use mocks in PHPUnit:

    $mock = Mockery::mock(ResendClient::class);
    $mock->shouldReceive('emails->send')->once()->andReturn(new \stdClass());
    $this->app->instance(ResendClient::class, $mock);
    

Configuration Quirks

  1. API URL Override Useful for staging environments:

    $resend = new ResendClient('api_key', [
        'api_url' => 'https://staging.api.resend.com',
    ]);
    
  2. Default Headers Add headers globally:

    $res
    
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle