Symfony / Ajax : call function on success response

I’m working on payment development with stripe, using symfony 5 and Ajax call, when action end success response I want to call another action to generate an invoice document and save it in the public folder and persist it to the DB.

this what I did in the php controller :

 /**
     * @Route("/booking/checkout/{id}", name="booking_checkout")
     * @Security("is_granted('ROLE_USER')")
     * @param Booking $booking
     * @param Request $request
     * @throws ApiErrorException
     */
    public function checkoutAction(Request $request, Booking $booking)
    {
        $diff_time = (strtotime($booking->getEndDate()->format('d-m-Y')) - strtotime($booking->getStartDate()->format('d-m-Y'))) / (60 * 60 * 24) + 1;

        $amount = $request->get('amount');
        $carModel = $booking->getCar()->getModel() . " " . $booking->getCar()->getBrand();

        Stripe::setApiKey('sk_test_51HSKmkLhD9FM4Mb7keiF5NmilsUh5rBVzOamXpahjAc6ORYMlnELaroSH8cRwKe4dlEzQqRMgrxDumEQneXyFPQv00JxG2gGCD');

        header('Content-Type: application/json');

        $checkout_session = Session::create([

            'payment_method_types' => ['card'],

            'line_items' => [[

                'price_data' => [

                    'currency' => 'eur',

                    'unit_amount' => $amount * 100,

                    'product_data' => [

                        'name' => $diff_time . " " . "jour(s)" . " " . $carModel,

                    ],

                ],

                'quantity' => 1,

            ]],

            'mode' => 'payment',

            'success_url' => $this->generateUrl('user.profile.bookings', [$booking, $this->addFlash('success', 'vous avéz payé votre réservation avec succes')], UrlGeneratorInterface::ABSOLUTE_URL),

            'cancel_url' => $this->generateUrl('user.profile.bookings', [], UrlGeneratorInterface::ABSOLUTE_URL),


        ]);

        $booking->setStatus("Payée");
        $booking->getCar()->setAvailable(0);
        $this->em->persist($booking);
        $this->em->flush();
        
        return new JsonResponse(['id' => $checkout_session->id], 200);
    }

here the Ajax call :

<script type="text/javascript">
        // Create an instance of the Stripe object with your publishable API key
        var stripe = Stripe("pk_test_51HSKmkLhD9FM4Mb7HbTbsTtzd60BbXnsXpoVGcJT3N7j751XgEeLmraXvzys4DCAYo7ZC1Yjc2nr1PjVdqXsmVg400NVqgnCQH");
        var checkoutButton = document.getElementById("checkout-button");
        checkoutButton.addEventListener("click", function () {

            $.ajax({
                method: "POST",
                url: "{{ path('booking_checkout',{'id': booking.id}) }}",
                data: {
                    amount: {{ total }},
                },
                success: function (session) {

                    return stripe.redirectToCheckout({sessionId: session.id});
                }
            });
           
        });

I defined a method that generate an invoice with Dompdf library taking the current Booking object, and I didn’t find a way to call it juster after the redirect success of stripe :

  /**
     * @param Booking $booking
     * @Route("/booking/{id}/invoice", name="booking_invoice")
     * @param Booking $booking
     * @param Request $request
     */

    public function generateInvoice(Booking $booking)
    {

        $invoice = new Invoice();
        $invoice->setBooking($booking);
        $invoice->setDate(new DateTime());
        $invoice->setReference($invoice->generateReference($booking));
        $this->em->persist($invoice);
        $this->em->flush();


        $pdfOptions = new Options();
        $pdfOptions->set('defaultFont', 'Arial');

        // Instantiate Dompdf with our options
        $dompdf = new Dompdf($pdfOptions);

        // Retrieve the HTML generated in our twig file
        $html = $this->render('admin/ContractInvoice/invoice.html.twig', [
            'invoice' => $invoice
        ]);

        // Load HTML to Dompdf
        $dompdf->loadHtml($html);

        // (Optional) Setup the paper size and orientation 'portrait' or 'portrait'
        $dompdf->setPaper('A4', 'portrait');

        // Render the HTML as PDF
        $dompdf->render();

        // Store PDF Binary Data
        $output = $dompdf->output();

        // In this case, we want to write the file in the public directory
        $publicDirectory = $this->projectDir. '/public/invoices';


        // e.g /var/www/project/public/name.pdf
        $pdfFilepath = $publicDirectory . '/' . $booking->getCar()->getRegistrationNumber() . $booking->getUser()->getName() . '.pdf';

        $invoice->setFilePath($pdfFilepath);
        $this->em->persist($invoice);
        $this->em->flush();

        $filename = $booking->getCar()->getRegistrationNumber() . $booking->getUser()->getName() . '.pdf';


        $dompdf->stream($filename, [
            "Attachment" => true
        ]);
        // Write file to the desired path
        file_put_contents($pdfFilepath, $output);

    }

I tired to call the invoice action inside the checkout action but it didn’t work like I want cause it does not let the checkout send the Stripe checkout session !

any help !

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *