Webhooks are a powerful way to enable real-time communication between different applications. In Laravel, setting up a webhook is straightforward and allows your application to listen for and respond to events triggered by external services. This blog will guide you through the process of creating a webhook in Laravel and provide detailed use cases where webhooks are commonly used.

What is a Webhook?

A webhook is an HTTP callback that sends real-time data from one application to another when a specific event occurs. Unlike APIs, which require polling for updates, webhooks push data automatically when triggered. Webhooks are commonly used in payment processing, order fulfillment, notifications, and third-party integrations.

Scenarios Where Webhooks Are Used

  1. Payment Processing – Services like Stripe, PayPal, and Razorpay send webhook notifications when payments are made, refunded, or fail.
  2. E-commerce Order Management – Platforms like Shopify and WooCommerce use webhooks to notify external systems about new orders, cancellations, and shipping updates.
  3. Third-party Integrations – CRM systems, marketing automation tools, and external databases use webhooks to sync data between applications in real-time.
  4. User Registration and Authentication – Webhooks can notify third-party services when a new user registers, logs in, or updates their profile.
  5. Notifications and Alerts – Webhooks enable real-time notifications in applications like Slack, Telegram, or email services when specific actions are performed.
  6. CI/CD Pipelines – Services like GitHub and GitLab use webhooks to trigger deployments or automated builds when new code is pushed to a repository.

Steps to Create a Webhook in Laravel

1. Create a Webhook Route

Define a route in routes/api.php to receive webhook requests:

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use App\Http\Controllers\WebhookController;

Route::post('/webhook', [WebhookController::class, 'handle']);

2. Create a Webhook Controller

Generate a controller to handle webhook requests:

php artisan make:controller WebhookController

Update the WebhookController with the following method:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class WebhookController extends Controller
{
    public function handle(Request $request)
    {
        Log::info('Webhook received:', $request->all());
        return response()->json(['status' => 'success']);
    }
}

This will log incoming webhook data and respond with a success message.

3. Secure the Webhook

To ensure that only trusted sources can send webhook requests, use a secret key:

public function handle(Request $request)
{
    $secret = config('services.webhook_secret');
    if ($request->header('X-Webhook-Secret') !== $secret) {
        return response()->json(['error' => 'Unauthorized'], 403);
    }
    
    Log::info('Valid Webhook received:', $request->all());
    return response()->json(['status' => 'success']);
}

Set the secret key in your .env file:

WEBHOOK_SECRET=your_secret_key

4. Test the Webhook

Use Postman or curl to send a test request:

curl -X POST http://your-app.test/webhook \
     -H "Content-Type: application/json" \
     -H "X-Webhook-Secret: your_secret_key" \
     -d '{"message": "Hello from webhook!"}'

5. Process Webhook Data

Once received, the webhook data can be processed and stored in the database:

public function handle(Request $request)
{
    $data = $request->all();
    // Store the data in the database
    WebhookLog::create(['payload' => json_encode($data)]);
    return response()->json(['status' => 'success']);
}

Create a migration and model to store webhook logs:

php artisan make:model WebhookLog -m

Update the migration file:

Schema::create('webhook_logs', function (Blueprint $table) {
    $table->id();
    $table->json('payload');
    $table->timestamps();
});

Run the migration:

php artisan migrate

6. Handling Different Webhook Events

Some services send multiple types of webhook events. You can filter them:

public function handle(Request $request)
{
    $eventType = $request->input('event');
    
    switch ($eventType) {
        case 'order.created':
            // Handle new order
            break;
        case 'payment.success':
            // Handle payment success
            break;
        default:
            Log::info('Unhandled webhook event:', ['event' => $eventType]);
    }
    
    return response()->json(['status' => 'success']);
}

Conclusion

Webhooks allow your Laravel application to receive real-time updates from external services. They are widely used in payment processing, order management, notifications, and third-party integrations. By following the steps above, you can create, secure, and process webhooks efficiently, ensuring seamless automation and integration with other platforms.

Do you have any questions or need further clarification? Drop them in the comments!

Categorized in: