php - Symfony / Ajax:成功响应时调用函数
问题描述
我正在使用 symfony 5 和 Ajax 调用使用条纹进行支付开发,当操作结束成功响应时,我想调用另一个操作来生成发票文档并将其保存在公用文件夹中并将其保存到数据库中。
这就是我在 php 控制器中所做的:
/**
* @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);
}
这里是 Ajax 调用:
<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});
}
});
});
我定义了一个使用 Dompdf 库生成发票的方法,该库采用当前的 Booking 对象,但在 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);
}
我厌倦了在结帐操作中调用发票操作,但它并没有像我想要的那样工作,因为它不会让结帐发送 Stripe 结帐会话!
任何帮助!
解决方案
我认为您需要 a 之类的东西,downloadAction
因为 AJAX 响应与下载无关。
推荐阅读
- python - 在 Python 中使用过滤器从文本文件中过滤行
- swift - 核心数据:ID 已设置,但保存时显示为 nil
- laravel - 在控制器内部的 Laravel 中使用 Summer Note 文本编辑器时如何将 base64 图像转换为 Url 图像?
- spring-boot - 未经授权的错误:访问此资源需要完全身份验证
- blazor - 在通过 Http.GetStringAsync 使用 IP 访问的“本地模式”下将 Blazor WebAssembly 与 Azure 函数一起使用时,我收到“无法获取错误”
- python - 在熊猫中将月份从数字重命名为名称
- flutter - RedirectException:检测到重定向循环
- assembly - 为什么这个汇编程序两次输出相同的字符串?
- javascript - 如何将 json 数组转换为具有特定属性的 CSV 数据
- c - 我如何用c读取这个格式化的文本文件?