Advertisement
Guest User

WebhookController.php

a guest
Jan 23rd, 2020
220
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.24 KB | None | 0 0
  1. <?php
  2.  
  3. namespace App\Controller;
  4.  
  5. use App\Entity\Subscription;
  6. use App\Services\StripeClient;
  7. use App\Services\SubscriptionHelper;
  8. use Psr\Log\LoggerInterface;
  9. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  10. use Symfony\Component\HttpFoundation\Request;
  11. use Symfony\Component\HttpFoundation\Response;
  12. use Symfony\Component\Routing\Annotation\Route;
  13.  
  14. class WebhookController extends AbstractController
  15. {
  16.  
  17. /**
  18. * @Route("/webhooks/stripe", name="webhook_stripe")
  19. */
  20. public function stripeWebhookAction(Request $request, StripeClient $stripeClient, SubscriptionHelper $subscriptionHelper, $shouldVerifyStripeEvent)
  21. {
  22. $data = json_decode($request->getContent(), true);
  23.  
  24. if($data === null)
  25. {
  26. throw new \Exception("Bad JSON body from Stripe !");
  27. }
  28.  
  29. $eventId = $data['id'];
  30.  
  31. if($shouldVerifyStripeEvent)
  32. {
  33. $stripeEvent = $stripeClient->findEvent($eventId);
  34. }
  35. else
  36. {
  37. // test environment
  38. $stripeEvent = json_decode($request->getContent());
  39. }
  40.  
  41. switch($stripeEvent->type)
  42. {
  43. case "customer.subscription.deleted":
  44. //Cancel compl├Ętement l'abonnement de l'utilisateur
  45. $stripeSubscriptionId = $stripeEvent->data->object->id;
  46. $subscription = $this->findSubscription($stripeSubscriptionId);
  47. $subscriptionHelper->fullyCancelSubscription($subscription);
  48.  
  49. break;
  50.  
  51. default:
  52. throw new \Exception("Unexpected webhook from Stripe ".$stripeEvent->type);
  53. }
  54.  
  55. return new Response('Event handled: '.$stripeEvent->type);
  56. }
  57.  
  58. private function findSubscription($stripeSubscriptionId)
  59. {
  60. $subscription = $this->getDoctrine()->getRepository(Subscription::class)
  61. ->findOneBy([
  62. 'stripeSubscriptionId' => $stripeSubscriptionId
  63. ]);
  64.  
  65. if(!$subscription)
  66. {
  67. throw new \Exception("Il semblerait qu'il n'y ait pas d'id d'abonnement ".$stripeSubscriptionId);
  68. }
  69.  
  70. return $subscription;
  71. }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement