LemonSqueezy Webhooks for Non-Auth Users in Laravel
How to handle LemonSqueezy Webhooks for non-auth users in Laravel
Laravel LemonSqueezy package default webhooks are using billable model to store the orders in the database. But what if you want to handle webhooks for non-auth users?
In this article, we will see how to handle LemonSqueezy webhooks for non-auth users in Laravel.
Step 1: Install LemonSqueezy
First, you need to install the LemonSqueezy package in your Laravel application.
Check the all installation steps in the official documentation
Step 2: Change the billable columns to nullable in lemon_squeezy_orders table
In this example we are using the orders
table to store the orders for non-auth users.
Or modify them in main migration file after publishing them
I also track user name and emails from lemon squeezy orders, so I added these columns to the lemon_squeezy_orders
table.
Step 3: Create a new route for webhooks
As default LemonSqueezy webhooks are using the billable
model to store the orders in the database we need to create a new route for webhooks.
Create a new controller WebhookController
Create a new route for LemonSqueezy webhooks in your routes/web.php
file.
Step 4: Copy from LemonSqueezy WebhookController
Open vendor/lemonsqueezy/laravel/src/Http/Controllers/WebhookController.php
file and copy the __construct(), __invoke() and handleOrderCreated() methods to your WebhookController
.
You can extend your controller with LemonSqueezy Webhook Controller for the other methods if you don’t need modifications there
For our case we need to modify our handleOrderCreated() method to store the orders for non-auth users.
Instead of $billable->orders()
we will use LemonSqueezy::$orderModel
to create the order in our database
Remove 'customer_id' => $attributes['customer_id'],
from the $order
array as we are not using the billable
model.
Add user_email and user_name to the $order
array.
Event Listener
Remove OrderCreated::dispatch($billable, $order, $payload)
as we are not using the billable
model.
Instead of OrderCreated event you can listen for WebhookHandled
event in your application.
Add LemonSqueezyEventListener if you need to do additional actions after the order is created. For example you can send a welcome email with the steps how to use your app when user makes the order.