Décrivez ici votre problème ou ce que vous cherchez à faire.
Entourez votre code en utilisant "```" pour bien le mettre en forme. (ne copiez pas trop de code)
```"<?php
namespace App\Controller;
use Stripe\Stripe;
use App\Classe\Cart;
use App\Entity\Order;
use App\Entity\Product;
use Stripe\Checkout\Session;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class StripeController extends AbstractController
{
/**
* @Route("/commande/create-session/{reference}", name="stripe_create_session")
*/
public function index(EntityManagerInterface $entityManager, Cart $cart, $reference)
{
$products_for_stripe = [];
$YOUR_DOMAIN = 'http://127.0.0.1:8000';
$order = $entityManager(Order::class)->findOneByReference($reference);
if (!$order) {
new JsonResponse(['error' => 'order']);
}
foreach ($order->getOrderDetails()->getValues() as $product) {
$product_object = $entityManager->getRepository(Product::class)->findOneByName($product->getProduct());
$products_for_stripe[] = [
'price_data' => [
'currency' => 'eur',
'unit_amount' => $product->getPrice(),
'product_data' => [
'name' => $product->getProduct(),
'images' => [$YOUR_DOMAIN . "/uploads/" . $product_object->getIllustration()],
],
],
'quantity' => $product->getQuantity(),
];
}
dd($products_for_stripe);
Stripe::setApiKey('sk_test_51MMUZFBIHwzZq0AEx5XS2iunsu4mlIpiVDoa156lfFbURGNxHnRqh9GIyPa6nkklQY14RldaHlGLNTILfNpXapSp001ezyJZf3');
$checkout_session = Session::create([
'payment_method_types' => ['card'],
'line_items' => [
$products_for_stripe
],
'mode' => 'payment',
'success_url' => $YOUR_DOMAIN . '/success.html',
'cancel_url' => $YOUR_DOMAIN . '/cancel.html',
]);
$response = new JsonResponse(['id' => $checkout_session->id]);
return $response;
}
}
Order controller
<?php
namespace App\Controller;
use DateTime;
use Stripe\Stripe;
use App\Classe\Cart;
use App\Entity\Order;
use App\Form\OrderType;
use App\Entity\OrderDetails;
use Stripe\Checkout\Session;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class OrderController extends AbstractController
{
private $entityManager;
public function __construct(EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
}
/**
* @Route("/commande", name="order")
*/
public function index(Cart $cart, Request $request): Response
{
if (!$this->getUser()->getAdresses()->getValues()) {
return $this->redirectToRoute('account_adress_add');
}
$form = $this->createForm(OrderType::class, null, [
'user' => $this->getUser()
]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
dd($form->getData());
}
return $this->render(
'order/index.html.twig',
[
'form' => $form->createView(),
'cart' => $cart->getFull()
]
);
}
/**
* @Route("/commande/recapitulatif/", name="order_recap", methods={"POST"})
*/
public function add(Cart $cart, Request $request): Response
{
$form = $this->createForm(OrderType::class, null, [
'user' => $this->getUser()
]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$date = new DateTime();
$carriers = $form->get('carriers')->getData();
$delivery = $form->get('adresses')->getData();
$delivery_content = $delivery->getFirstName() . ' ' . $delivery->getLastName();
$delivery_content .= '<br/>' . $delivery->getPhone();
if ($delivery->getCompany()) {
$delivery_content .= '<br/>' . $delivery->getCompany();
}
$delivery_content .= '<br/>' . $delivery->getAdress();
$delivery_content .= '<br/>' . $delivery->getPostal() . ' ' . $delivery->getCity();
$delivery_content .= '<br/>' . $delivery->getCountry();
//enregister ma commande Order()
$order = new Order();
$reference = $date->format('dmY') . '-' . uniqid();
$order->setReference($reference);
$order->setUser($this->getUser());
$order->setCreatedAt($date);
$order->setCarrierName($carriers->getName());
$order->setCarrierPrice($carriers->getPrice());
$order->setDelivery($delivery_content);
$order->setIsPaid(0);
$this->entityManager->persist($order);
//enregister mes produits OrderDetails()
foreach ($cart->getFull() as $product) {
$orderDetails = new OrderDetails();
$orderDetails->setMyOrder($order);
$orderDetails->setProduct($product['product']->getName());
$orderDetails->setQuantity($product['quantity']);
$orderDetails->setPrice($product['product']->getPrice());
$orderDetails->setTotal($product['product']->getPrice() * $product['quantity']);
$this->entityManager->persist($orderDetails);
}
//$this->entityManager->flush();
return $this->render('order/add.html.twig', [
'cart' => $cart->getFull(),
'carrier' => $carriers,
'delivery' => $delivery_content,
'reference' => $order->getReference(),
'order' => $order
]);
}
return $this->redirectToRoute('cart');
}
}
Add.html.twig
{% extends 'base.html.twig' %}
{% block javascript %}
<script src="https://js.stripe.com/v3/"></script>
{% endblock %}
{% block title %}Valider ma commande-La Boutique Française
{% endblock %}
{% block content %}
<h1>Mon recapitulatif</h1>
<p>Verifier vos information vant de payer.</p>
<hr>
<div class="row">
<div class="col-md-6">
<strong>Mon adresse de livraison</strong><br>
<div class="form-check">
{{delivery|raw}}
</div>
<hr>
<strong>Mon transporteur</strong><br>
<div class="form-check">
{{carrier.name}}<br>
{{carrier.description}}<br>
{{carrier.price|number_format(2, ',','.') }}€
</div>
</div>
<div class="col-md-6">
<div class="text-center">
<b>Ma commande</b><br>
</div>
<div class="order-summary">
{% set total = null %}
{% for key,product in cart %}
<div class="row {% if key >0 %}mt-2{% endif %}">
<div class="col-2">
<img src="/uploads/{{product.product.illustration}}" alt="{{ product.product.name }}" height="75px"><br>
</div>
<div class="col-8 my-auto">
<strong>{{ product.product.name }}</strong><br>
<small>
{{ product.product.subtitle }}
<br>
X
{{product.quantity}}
</small>
</div>
<div class="col-2 my-auto">
{{ ((product.product.price * product.quantity)/100)| number_format(2, ',','.') }}€
</div>
</div>
{% set total = total + (product.product.price * product.quantity) %}
{% endfor %}
</div>
<hr>
<strong>Sous-total :</strong>
{{ ((total) /100)| number_format(2, ',','.') }}€
<br>
<Strong>Livraison :</Strong>
{{ (carrier.price)| number_format(2, ',','.') }}€
<hr>
<strong>Total :</strong>
{{ (((total) /100) + carrier.price)| number_format(2, ',','.') }}€
<hr>
<a href="{{path('stripe_create_session',{'reference': order.reference})}}" id="checkout-button" class="btn btn-success btn-block mt-3">Payer | {{ (((total) /100) + carrier.price) | number_format(2, ',','.') }}€</a>
</div>
<hr>
</div>
{% endblock %}
{% block script %}
<script type="text/javascript">
var stripe = Stripe("pk_test_51MMUZFBIHwzZq0AEdvlt0IXjOMBUPTG13peR68jm1TMHGiOOeo8JKSj0ItX7y44tdGy7CPN9CyDw9KnCbiIW5D9w009eTm242V");
var checkoutButton = document.getElementById("checkout-button");
checkoutButton.addEventListener("click", function () {
fetch("/commande/create-session/{{reference}}", {
method: "POST"
})
.then(function (response) {
return response.json();
})
.then(function (session){
if (session.error == 'order') {
window.location.replace('{{ path('order') }}');
} else {
return stripe.redirectToCheckout({sessionId: session.id});
}
})
.then(function (result) {
// If redirectToCheckout fails due to a browser or network
// error, you should display the localized error message to your
// customer using error.message.
if (result.error) {
alert(result.error.message);
}
})
.catch(function (error) {
console.error("Error:", error);
});
});
</script>
{% endblock %}
Order.php
<?php
namespace App\Entity;
use App\Repository\OrderRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass=OrderRepository::class)
* @ORM\Table(name="`order`")
*/
class Order
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\ManyToOne(targetEntity=User::class, inversedBy="orders")
* @ORM\JoinColumn(nullable=false)
*/
private $user;
/**
* @ORM\Column(type="datetime")
*/
private $createdAt;
/**
* @ORM\Column(type="string", length=255)
*/
private $carrierName;
/**
* @ORM\Column(type="float")
*/
private $carrierPrice;
/**
* @ORM\Column(type="text")
*/
private $delivery;
/**
* @ORM\OneToMany(targetEntity=OrderDetails::class, mappedBy="myOrder")
*/
private $orderDetails;
/**
* @ORM\Column(type="boolean")
*/
private $isPaid;
/**
* @ORM\Column(type="string", length=255)
*/
private $reference;
public function __construct()
{
$this->orderDetails = new ArrayCollection();
}
public function getTotal()
{
$total = null;
foreach ($this->getOrderDetails()->getValues() as $product) {
$total = $total + ($product->getPrice() * $product->getQuantity());
}
return $total;
}
public function getId(): ?int
{
return $this->id;
}
public function getUser(): ?User
{
return $this->user;
}
public function setUser(?User $user): self
{
$this->user = $user;
return $this;
}
public function getCreatedAt(): ?\DateTimeInterface
{
return $this->createdAt;
}
public function setCreatedAt(\DateTimeInterface $createdAt): self
{
$this->createdAt = $createdAt;
return $this;
}
public function getCarrierName(): ?string
{
return $this->carrierName;
}
public function setCarrierName(string $carrierName): self
{
$this->carrierName = $carrierName;
return $this;
}
public function getCarrierPrice(): ?float
{
return $this->carrierPrice;
}
public function setCarrierPrice(float $carrierPrice): self
{
$this->carrierPrice = $carrierPrice;
return $this;
}
public function getDelivery(): ?string
{
return $this->delivery;
}
public function setDelivery(string $delivery): self
{
$this->delivery = $delivery;
return $this;
}
/**
* @return Collection<int, OrderDetails>
*/
public function getOrderDetails(): Collection
{
return $this->orderDetails;
}
public function addOrderDetail(OrderDetails $orderDetail): self
{
if (!$this->orderDetails->contains($orderDetail)) {
$this->orderDetails[] = $orderDetail;
$orderDetail->setMyOrder($this);
}
return $this;
}
public function removeOrderDetail(OrderDetails $orderDetail): self
{
if ($this->orderDetails->removeElement($orderDetail)) {
// set the owning side to null (unless already changed)
if ($orderDetail->getMyOrder() === $this) {
$orderDetail->setMyOrder(null);
}
}
return $this;
}
public function isIsPaid(): ?bool
{
return $this->isPaid;
}
public function setIsPaid(bool $isPaid): self
{
$this->isPaid = $isPaid;
return $this;
}
public function getReference(): ?string
{
return $this->reference;
}
public function setReference(string $reference): self
{
$this->reference = $reference;
return $this;
}
}
"
**Ce que je veux** Comment passer le refence dans la deuxième parametre de mon url path() dans payé sur add.html.twig
Décrivez ce que vous cherchez à obtenir.
**Ce que j'obtiens**
Diriger vers la checkout-session du Stripe
Décrivez vos éventuelles erreurs ou ce que vous obtenez à la place de ce que vous attendez :(
Function name must be a string