src/Controller/Front/Stripe/StripeResponseController.php line 98

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Controller\Front\Stripe;
  4. use App\Application\Service\Helper\ControlPanelLinkGenerator;
  5. use App\Application\Service\Helper\LogWriterService;
  6. use App\Application\Service\Session\SessionService;
  7. use App\Manager\System\CustomerManager;
  8. use App\Manager\System\OrderManager;
  9. use App\Message\StripeResponseMessage;
  10. use App\Service\Order\OrderPaymentService;
  11. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Component\HttpFoundation\Response;
  14. use Symfony\Component\Messenger\MessageBusInterface;
  15. use Stripe\Webhook;
  16. use Stripe\Exception\SignatureVerificationException;
  17. use Stripe\Exception\UnexpectedValueException;
  18. use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
  19. use Symfony\Component\Routing\Annotation\Route;
  20. use function Sentry\captureMessage;
  21. class StripeResponseController extends AbstractController
  22. {
  23. private LogWriterService $logWriterService;
  24. private MessageBusInterface $messageBus;
  25. private OrderManager $orderManager;
  26. private SessionService $sessionService;
  27. private OrderPaymentService $orderPaymentService;
  28. private CustomerManager $customerManager;
  29. private ControlPanelLinkGenerator $controlPanelLinkGenerator;
  30. public function __construct(
  31. LogWriterService $logWriterService,
  32. MessageBusInterface $messageBus,
  33. OrderManager $orderManager,
  34. SessionService $sessionService,
  35. OrderPaymentService $orderPaymentService,
  36. CustomerManager $customerManager,
  37. ControlPanelLinkGenerator $controlPanelLinkGenerator,
  38. ) {
  39. $this->logWriterService = $logWriterService;
  40. $this->messageBus = $messageBus;
  41. $this->orderManager = $orderManager;
  42. $this->sessionService = $sessionService;
  43. $this->orderPaymentService = $orderPaymentService;
  44. $this->customerManager = $customerManager;
  45. $this->controlPanelLinkGenerator = $controlPanelLinkGenerator;
  46. }
  47. /**
  48. * @IsGranted("IS_AUTHENTICATED_FULLY")
  49. *
  50. * @Route("stripe/{orderId}/checkout", methods={"GET"}, name="stripe_checkout_session_response")
  51. */
  52. public function checkoutSessionResponse(int $orderId): Response
  53. {
  54. $message = __METHOD__.' - Procesamos la respuesta del CheckoutSession de Stripe para el pedido '.$orderId;
  55. $this->logWriterService->logOrderPayment($message);
  56. $order = $this->orderManager->findOneById($orderId);
  57. if (!$order || $this->getUser() !== $order->getCustomer()) {
  58. $this->logWriterService->logOrderPaymentError(__METHOD__.' - El pedido '.$orderId.' no existe.');
  59. return $this->redirectToRoute('homepage');
  60. }
  61. $paidOrderIds = $this->sessionService->get('paidOrderIds') ? (array)$this->sessionService->get('paidOrderIds') : [];
  62. $paidOrderIds[] = $order->getId();
  63. $paidOrders = \array_map(function (int $paidOrderId) {
  64. return $this->orderManager->getOneById($paidOrderId);
  65. }, $paidOrderIds);
  66. $this->orderPaymentService->manageOrdersInSessionOnPaymentSuccess(
  67. $paidOrders,
  68. $order,
  69. (bool)$order->getCart()->getCartParent()
  70. );
  71. if ($order->getCart()->isVirtual()) {
  72. $this->logWriterService->logOrderPayment(__METHOD__.' - Redirecting to services_order_creation route');
  73. return $this->redirectToRoute('services_order_creation');
  74. }
  75. $this->logWriterService->logOrderPayment(__METHOD__.' - Redirecting to products_order_creation route');
  76. return $this->redirectToRoute('products_order_creation');
  77. }
  78. /**
  79. * @Route("stripe/webhook/notification", name="webhook_stripe_notification", methods={"POST"})
  80. */
  81. public function checkNotification(Request $request): Response
  82. {
  83. $webhookSecret = $this->getParameter('stripe_webhook_key');
  84. $sigHeader = $request->headers->get('Stripe-Signature');
  85. $notificationRequest = \json_decode($request->getContent(), true);
  86. $this->logWriterService->logOrderPayment('LLega webhook Stripe. Request: '.$request->getContent().' y la firma es: '.$sigHeader);
  87. $sandbox = (bool)$this->getParameter('stripe_sandbox');
  88. $livemode = $notificationRequest['data']['object']['livemode'];
  89. if ($sandbox !== ($livemode === false)) {
  90. $this->logWriterService->logOrderPaymentError('Error Webhook Stripe: La variable stripe_sandbox con valor '.(int)$sandbox.' no coincide con el valor de livemode en el webhook Stripe: '.$livemode);
  91. return new Response('Invalid livemode', Response::HTTP_BAD_REQUEST);
  92. }
  93. try {
  94. $event = Webhook::constructEvent($request->getContent(), $sigHeader, $webhookSecret);
  95. } catch (UnexpectedValueException $exception) {
  96. $this->logWriterService->logOrderPaymentError('Error Webhook Stripe: Invalid payload: '.$exception->getMessage());
  97. return new Response('Invalid payload', Response::HTTP_BAD_REQUEST);
  98. } catch (SignatureVerificationException $exception) {
  99. $this->logWriterService->logOrderPaymentError('Error Webhook Stripe: Invalid signature: '.$exception->getMessage());
  100. return new Response('Invalid signature', Response::HTTP_BAD_REQUEST);
  101. }
  102. $this->logWriterService->logOrderPayment('Webhook Stripe vĂ¡lido. Mandamos mensaje a Rabbit');
  103. try {
  104. $stripeResponseMessage = new StripeResponseMessage($event);
  105. $this->messageBus->dispatch($stripeResponseMessage);
  106. } catch (\Throwable $exception) {
  107. $this->logWriterService->logOrderPaymentError(__METHOD__.' - Error publishing event '.$event->id.': '.$exception->getMessage());
  108. captureMessage(__METHOD__.' - Error publishing event '.$event->id.': '.$exception->getMessage());
  109. return new Response('Error publishing message', Response::HTTP_BAD_REQUEST);
  110. }
  111. return new Response(
  112. null,
  113. Response::HTTP_OK
  114. );
  115. }
  116. /**
  117. * @Route("stripe/{checkoutSessionId}/{customerId}/billing-agreement-success", name="webhook_stripe_billing_agreement_notification", methods={"GET"})
  118. */
  119. public function billingAgreementSuccess(string $checkoutSessionId, int $customerId): Response
  120. {
  121. $message = __METHOD__.' - BillingAgreement creado para el cliente '.$customerId.' - CheckoutSession '.$checkoutSessionId;
  122. $this->logWriterService->logAccount($message);
  123. $customer = $this->customerManager->findOneById($customerId);
  124. if (!$customer) {
  125. $this->logWriterService->logAccount(__METHOD__.'Customer not found');
  126. }
  127. return $this->redirect($this->controlPanelLinkGenerator->getBillingAgreementSuccess());
  128. }
  129. }