Handle Paddle's marketing consent with Laravel

On Paddle, a buyer can opt-in to receive marketing emails and is stored as a new audience member.

But, by using an event listener, you can handle the Paddle's marketing consent on Laravel Cashier too.

The following example code uses a subscribed user attribute, but you can use an external service or tool like Spatie's Mailcoach and have it synced.

1<?php
2 
3namespace App\Listeners;
4 
5use App\Models\User;
6use Laravel\Paddle\Events\WebhookReceived;
7 
8class PaddleEventListener
9{
10 public function handle (WebhookReceived $event)
11 {
12 if ($event->payload['alert_name' ] === 'new_audience member') {
13 if ($user = User::whereEmail($event->payload['email'])->first()) {
14 $user->fill([
15 'subscribed' => $event->payload['marketing_consent'],
16 ])->save();
17 }
18 }
19 
20 if ($event->payload['alert_name'] === 'update_audience_member') {
21 if ($user = User::whereEmail($event->payload['new_customer_email'])->first()) {
22 $user->fill([
23 'subscribed' => $event->payload['new_marketing_consent'],
24 ])->save();
25 }
26 }
27 }
28}