Skip to content

Instantly share code, notes, and snippets.

@gabrielkoerich
Created May 24, 2018 08:49
Show Gist options
  • Save gabrielkoerich/be2e4e18d330f3f5d43c52064199d6f1 to your computer and use it in GitHub Desktop.
Save gabrielkoerich/be2e4e18d330f3f5d43c52064199d6f1 to your computer and use it in GitHub Desktop.
Refactoring to events
<?php
(...)
class WebhookController extends Controller
{
public function handleWebhook(Request $request)
{
$payload = json_decode($request->getContent(), true);
if (! $this->isInTestingEnvironment() && ! $this->eventExistsOnStripe($payload['id'])) {
return;
}
$method = 'handle'.studly_case(str_replace('.', '_', $payload['type']));
if (method_exists($this, $method)) {
return $this->{$method}($payload);
} else {
return $this->missingMethod();
}
}
protected function handleCustomerSubscriptionDeleted(array $payload)
{
$user = $this->getUserByStripeId($payload['data']['object']['customer']);
if ($user) {
$user->subscriptions->filter(function ($subscription) use ($payload) {
return $subscription->stripe_id === $payload['data']['object']['id'];
})->each(function ($subscription) {
$subscription->markAsCancelled();
});
}
return new Response('Webhook Handled', 200);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment