src/Controller/Client/PaymentController.php line 196

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Client;
  3. use App\Entity\{CreditTransactionInvoice};
  4. use App\Form\CreditReloadType;
  5. use Stripe\Stripe;
  6. use Stripe\PaymentIntent;
  7. use Stripe\PaymentMethod;
  8. use App\Service\{AccessClientServiceStripePaymentService};
  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. use Doctrine\ORM\EntityManagerInterface;
  14. use Knp\Component\Pager\PaginatorInterface;
  15. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  16. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface
  17. use Symfony\Component\HttpFoundation\JsonResponse;
  18. /**
  19.  * @Route("/client")
  20.  */
  21. class PaymentController extends AbstractController
  22. {
  23.     private $stripePaymentService;
  24.     public function __construct(StripePaymentService $stripePaymentService)
  25.     {
  26.         $this->stripePaymentService $stripePaymentService;
  27.     }
  28.     /**
  29.      * @Route("/credit-reload", name="app_client_credit_reload")
  30.      */
  31.     public function creditReload(Request $requestAccessClientService $accessClientServiceEntityManagerInterface $entityManager): Response
  32.     {
  33.         $accessClientService->handleAccessControl();
  34.         $form $this->createForm(CreditReloadType::class);
  35.         $form->handleRequest($request);
  36.         if ($form->isSubmitted() && $form->isValid()) {
  37.             $amount $form->get('amount')->getData() * 100;
  38.             
  39.             Stripe::setApiKey($this->getParameter('stripe_secret_key'));
  40.             $paymentIntent PaymentIntent::create([
  41.                 'amount' => $amount
  42.                 'currency' => 'eur',
  43.                 'payment_method_types' => ['card'],
  44.             ]);
  45.             if ($request->isXmlHttpRequest()) {
  46.                 return new JsonResponse([
  47.                     'client_secret' => $paymentIntent->client_secret,
  48.                     'success' => true
  49.                 ]);
  50.             }
  51.         }                                                                                                       
  52.         return $this->render('client/payment/credit_reload.html.twig', [
  53.             'form' => $form->createView(),
  54.             'stripe_public_key' => $this->getParameter('stripe_public_key')
  55.         ]);
  56.     }
  57.     /**
  58.      * @Route("/complete-payment", name="app_client_complete_payment")
  59.      */
  60.     public function completePayment(Request $requestEntityManagerInterface $entityManager): JsonResponse
  61.     {
  62.         $data json_decode($request->getContent(), true);
  63.         $paymentIntentId $data['payment_intent_id'] ?? null;
  64.         $amount $data['amount'] ?? null;
  65.         $status $data['status'] ?? null;
  66.         
  67.         if (!$paymentIntentId || !$status) {
  68.             return new JsonResponse(['error' => 'Informations de paiement manquantes'], 400);
  69.         }
  70.         Stripe::setApiKey($this->getParameter('stripe_secret_key'));
  71.         
  72.         try {
  73.             $paymentIntent PaymentIntent::retrieve($paymentIntentId);
  74.             if ($paymentIntent->status === 'succeeded') {
  75.                 $user $this->getUser();
  76.                 if (!$user) {
  77.                     throw new NotFoundHttpException('Utilisateur non trouvé');
  78.                 }
  79.                 $paymentMethodId $paymentIntent->payment_method;
  80.                 $paymentMethod PaymentMethod::retrieve($paymentMethodId);
  81.                 $cardDetails $paymentMethod->card;
  82.                 $cardType $cardDetails->brand;  
  83.                 $last4 $cardDetails->last4;     
  84.                 $cardNumber '**** **** **** ' $last4;
  85.                 $cardHolder $paymentMethod->billing_details->name
  86.                 $expMonth $cardDetails->exp_month;
  87.                 $expYear $cardDetails->exp_year;
  88.                 $cardExpiration $expMonth '/' $expYear
  89.                 $transaction = new CreditTransaction();
  90.                 $transaction->setAmount($amount 100);
  91.                 $transaction->setStatus('succeeded'); 
  92.                 $transaction->setPaymentIntentId($paymentIntent->id);
  93.                 $transaction->setCardType($cardType);
  94.                 $transaction->setCardNumber($cardNumber);
  95.                 $transaction->setCardHolder($cardHolder);
  96.                 $transaction->setCardExpiration($cardExpiration);
  97.                 $transaction->setDescription('Recharge crédit');
  98.                 $transaction->setTransactionType('credit');  
  99.                 $transaction->setUser($user);   
  100.                 $entityManager->persist($transaction);
  101.                 $entityManager->flush();
  102.                 $transaction->generateTransactionNumber(); 
  103.                 $user->setCreditBalance($user->getCreditBalance() + ($amount 100)); 
  104.                 $entityManager->flush();
  105.                 $invoice = new Invoice();
  106.                 $invoice->setStatus('Paid'); 
  107.                 $invoice->setCreditTransaction($transaction);
  108.                 $entityManager->persist($invoice);
  109.                 $entityManager->flush();
  110.                 $invoice->setInvoiceNumber('F' str_pad($invoice->getId(), 5'0'STR_PAD_LEFT));
  111.                 $entityManager->flush();
  112.                 // $this->addFlash('success', 'Succès ! Paiement réussi et crédit ajouté.');
  113.                 return new JsonResponse([
  114.                     'success' => true,
  115.                 ]);
  116.             } else {
  117.                 $this->addFlash('danger''Error ! Le paiement a échoué, veuillez réessayer.');
  118.                 return new JsonResponse([
  119.                     'success' => false,
  120.                 ]);          
  121.             }
  122.         } catch (\Exception $e) {
  123.             return new JsonResponse([
  124.                 'error' => $e->getMessage(),
  125.                 'success' => false
  126.             ]);
  127.         }
  128.     }
  129.     /**
  130.      * @Route("/credit-reload/confirmation/{paymentIntentId}", name="app_client_credit_reload_confirmation")
  131.      */
  132.     public function creditReloadConfirmation(AccessClientService $accessClientService$paymentIntentIdRequest $requestEntityManagerInterface $entityManager): Response
  133.     {
  134.         $accessClientService->handleAccessControl();
  135.         $user $this->getUser();
  136.         $client $user->getClient();
  137.         if (!$client) {
  138.             throw new NotFoundHttpException('Aucun client trouvé pour cet utilisateur ' $user->getFirstname());
  139.         }
  140.         $transaction $entityManager->getRepository(CreditTransaction::class)->findOneBy(['paymentIntentId' => $paymentIntentId'user' => $user], ['id' => 'DESC']);
  141.         if (!$transaction) {
  142.             throw new NotFoundHttpException('Transaction non trouvée');
  143.         }
  144.         return $this->render('client/payment/confirmation.html.twig', [
  145.             'transaction' => $transaction,
  146.         ]);
  147.     }
  148.     /**
  149.      * @Route("/transactions", name="app_client_credit_transactions")
  150.      */
  151.     public function transactions(AccessClientService $accessClientServiceRequest $requestEntityManagerInterface $entityManagerPaginatorInterface $paginator): Response
  152.     {
  153.         $accessClientService->handleAccessControl();
  154.         $user $this->getUser();
  155.         $client $user->getClient();
  156.         if (!$client) {
  157.             throw new NotFoundHttpException('Aucun client trouvé pour cet utilisateur ' $user->getFirstname());
  158.         }
  159.         
  160.         $query $entityManager->getRepository(CreditTransaction::class)->findBy(['user' => $user], ['id' => 'DESC']);
  161.         $pagination $paginator->paginate(
  162.             $query,
  163.             $request->query->getInt('page'1),
  164.             12
  165.         ); 
  166.         return $this->render('client/payment/transactions.html.twig', [
  167.             'transactions' => $pagination,
  168.         ]);
  169.     }
  170.     // ****************** MODAL ******************* //
  171.     /**
  172.      * @Route("/reload-credit", name="app_client_credit_reload_modal")
  173.      */
  174.     public function creditReloadModal(Request $requestAccessClientService $accessClientService): Response
  175.     {
  176.         $accessClientService->handleAccessControl();
  177.         if ($request->isXmlHttpRequest()) {
  178.             $amount $request->request->get('sg_credit_reload')['amount'] * 100;
  179.             Stripe::setApiKey($this->getParameter('stripe_secret_key'));
  180.             $paymentIntent PaymentIntent::create([
  181.                 'amount' => $amount
  182.                 'currency' => 'eur',
  183.                 'payment_method_types' => ['card'],
  184.             ]);
  185.             return new JsonResponse([
  186.                 'client_secret' => $paymentIntent->client_secret,
  187.                 'success' => true
  188.             ]);
  189.         }                                                                                                
  190.     }
  191.     /**
  192.      * @Route("/confirm-payment", name="app_client_complete_payment_modal")
  193.      */
  194.     public function completePaymentModal(Request $requestEntityManagerInterface $entityManager): JsonResponse
  195.     {
  196.         $data json_decode($request->getContent(), true);
  197.         $paymentIntentId $data['payment_intent_id'] ?? null;
  198.         $amount $data['amount'] ?? null;
  199.         $status $data['status'] ?? null;
  200.         
  201.         if (!$paymentIntentId || !$status) {
  202.             return new JsonResponse(['error' => 'Informations de paiement manquantes'], 400);
  203.         }
  204.         Stripe::setApiKey($this->getParameter('stripe_secret_key'));
  205.         
  206.         try {
  207.             $paymentIntent PaymentIntent::retrieve($paymentIntentId);
  208.             if ($paymentIntent->status === 'succeeded') {
  209.                 $user $this->getUser();
  210.                 if (!$user) {
  211.                     throw new NotFoundHttpException('Utilisateur non trouvé');
  212.                 }
  213.                 $paymentMethodId $paymentIntent->payment_method;
  214.                 $paymentMethod PaymentMethod::retrieve($paymentMethodId);
  215.                 $cardDetails $paymentMethod->card;
  216.                 $cardType $cardDetails->brand;  
  217.                 $last4 $cardDetails->last4;     
  218.                 $cardNumber '**** **** **** ' $last4;
  219.                 $cardHolder $paymentMethod->billing_details->name
  220.                 $expMonth $cardDetails->exp_month;
  221.                 $expYear $cardDetails->exp_year;
  222.                 $cardExpiration $expMonth '/' $expYear
  223.                 $transaction = new CreditTransaction();
  224.                 $transaction->setAmount($amount 100);
  225.                 $transaction->setStatus('succeeded'); 
  226.                 $transaction->setPaymentIntentId($paymentIntent->id);
  227.                 $transaction->setCardType($cardType);
  228.                 $transaction->setCardNumber($cardNumber);
  229.                 $transaction->setCardHolder($cardHolder);
  230.                 $transaction->setCardExpiration($cardExpiration);
  231.                 $transaction->setDescription('Recharge crédit');
  232.                 $transaction->setTransactionType('credit');  
  233.                 $transaction->setUser($user);   
  234.                 $entityManager->persist($transaction);
  235.                 $entityManager->flush();
  236.                 $transaction->generateTransactionNumber(); 
  237.                 $user->setCreditBalance($user->getCreditBalance() + ($amount 100)); 
  238.                 $entityManager->flush();
  239.                 $invoice = new Invoice();
  240.                 $invoice->setStatus('Paid'); 
  241.                 $invoice->setCreditTransaction($transaction);
  242.                 $entityManager->persist($invoice);
  243.                 $entityManager->flush();
  244.                 $invoice->setInvoiceNumber('F' str_pad($invoice->getId(), 5'0'STR_PAD_LEFT));
  245.                 $entityManager->flush();
  246.                 $this->addFlash('success''Succès ! Paiement réussi et crédit ajouté.');
  247.                 return new JsonResponse([
  248.                     'success' => true,
  249.                 ]);
  250.             } else {
  251.                 $this->addFlash('danger''Error ! Le paiement a échoué, veuillez réessayer.');
  252.                 return new JsonResponse([
  253.                     'success' => false,
  254.                 ]);          
  255.             }
  256.         } catch (\Exception $e) {
  257.             return new JsonResponse([
  258.                 'error' => $e->getMessage(),
  259.                 'success' => false
  260.             ]);
  261.         }
  262.     }
  263. }