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 !
You should put this invoice generation in your success page provided insuccess_url
, which your customer arrives to after Checkout. You can't do anything "after"redirectToCheckout
because this involves a full redirect -- your client code is no longer running.
I think you need sth like adownloadAction
because the AJAX response is independent of the download.
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Find the answer in similar questions on our website.
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.
PHP (from the English Hypertext Preprocessor - hypertext preprocessor) is a scripting programming language for developing web applications. Supported by most hosting providers, it is one of the most popular tools for creating dynamic websites.
The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cross-platform, functionality and distribution of source codes under its own license.
https://www.php.net/
Symfony compares favorably with other PHP frameworks in terms of reliability and maturity. This framework appeared a long time ago, in 2005, that is, it has existed much longer than most of the other tools we are considering. It is popular for its web standards compliance and PHP design patterns.
https://symfony.com/
JavaScript is a multi-paradigm language that supports event-driven, functional, and mandatory (including object-oriented and prototype-based) programming types. Originally JavaScript was only used on the client side. JavaScript is now still used as a server-side programming language. To summarize, we can say that JavaScript is the language of the Internet.
https://www.javascript.com/
HTML (English "hyper text markup language" - hypertext markup language) is a special markup language that is used to create sites on the Internet.
Browsers understand html perfectly and can interpret it in an understandable way. In general, any page on the site is html-code, which the browser translates into a user-friendly form. By the way, the code of any page is available to everyone.
https://www.w3.org/html/
Welcome to the Q&A site for web developers. Here you can ask a question about the problem you are facing and get answers from other experts. We have created a user-friendly interface so that you can quickly and free of charge ask a question about a web programming problem. We also invite other experts to join our community and help other members who ask questions. In addition, you can use our search for questions with a solution.
Ask about the real problem you are facing. Describe in detail what you are doing and what you want to achieve.
Our goal is to create a strong community in which everyone will support each other. If you find a question and know the answer to it, help others with your knowledge.