Skip to content

Commit

Permalink
Update cancellation webhook
Browse files Browse the repository at this point in the history
  • Loading branch information
bobbyiliev committed Mar 25, 2024
1 parent 1715318 commit ac98ead
Showing 1 changed file with 56 additions and 13 deletions.
69 changes: 56 additions & 13 deletions wave/src/Http/Controllers/WebhookController.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Illuminate\Support\Carbon;
use App\Http\Controllers\Controller;
use Wave\Http\Middleware\VerifyWebhook;
use Illuminate\Support\Facades\Log;

class WebhookController extends Controller
{
Expand All @@ -20,32 +21,74 @@ public function __construct()

public function __invoke(Request $request)
{
$method = match ($request->get('alert_name', null)) {
'subscription.canceled' => 'subscriptionCancelled',
'subscription_payment_failed' => 'subscriptionCancelled',
default => null,
};

if (method_exists($this, $method)) {
$alertName = $request->get('event_type', null);
$method = null;

switch ($alertName) {
case 'subscription_cancelled':
case 'subscription.canceled':
case 'subscription_payment_failed':
$method = 'subscriptionCancelled';
break;
default:
$method = null;
break;
}

if ($method && method_exists($this, $method)) {
try {
$this->{$method}($request);
} catch (\Exception $e) {
return response('Webhook failed');
Log::error("Webhook handling error: " . $e->getMessage());
return response('Webhook handling failed', 500);
}
}

return response('Webhook handled');
return response('Webhook handled', 200);
}


protected function subscriptionCancelled(Request $request)
{
$subscription = PaddleSubscription::where('subscription_id', $request->subscription_id)->firstOrFail();
$subscription->cancelled_at = Carbon::now();
$subscriptionId = $request->input('data.id'); // Adjusted to match the payload structure

// Ensure the subscription ID is provided
if (is_null($subscriptionId)) {
Log::warning('Subscription ID missing in subscriptionCancelled webhook.');
return;
}

$subscription = PaddleSubscription::where('subscription_id', $subscriptionId)->first();

if (!$subscription) {
Log::warning("Subscription not found: {$subscriptionId}");
return;
}

// Use the occurred_at field from the payload for the cancellation time
$occurredAt = Carbon::parse($request->input('occurred_at', now()));

$subscription->cancelled_at = $occurredAt;
$subscription->status = 'cancelled';
$subscription->save();

$user = config('wave.user_model')::find($subscription->user_id);

// Check if user exists
if (!$user) {
Log::warning("User not found: {$subscription->user_id}");
return;
}

$cancelledRole = Role::where('name', '=', 'cancelled')->first();

// Ensure the cancelled role exists
if (!$cancelledRole) {
Log::error('Cancelled role not found.');
return;
}

$user->role_id = $cancelledRole->id;
$user->save();
}
}
}

0 comments on commit ac98ead

Please sign in to comment.