<?php
namespace App\Controller;
use App\Service\SessionService;
use App\Service\CartService;
use App\Service\VoucherService;
use App\Entity\Main\CartSession;
use App\Entity\Main\History;
use App\Entity\Main\Reservation;
use App\Entity\Main\ReservationDetails;
use App\Entity\Main\Activity;
use App\Entity\Main\BookedActivity;
use App\Entity\Main\BookedActivityOptions;
use App\Entity\Customer\Customer;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
class PaiementController extends AbstractController
{
private $ss;
private $cart_service;
private $vs;
private $user_id_boutique;
private $paiement_mode = 'prod';
private $secretkey = array(
'prod' => 'sk_live_BWyADRY2i1WkCeCFSdTPB',
'test' => 'sk_test_3WPuDRaCf7EkPpwK5kLvFq',
);
public function __construct(SessionService $ss, CartService $cart_service, VoucherService $vs)
{
$this->ss = $ss;
$this->cart_service = $cart_service;
$this->vs = $vs;
$this->user_id_boutique = '1367';
}
/**
* @Route("/paiement", name="payment")
*/
public function showRecap(Request $request): Response
{
$em = $this->getDoctrine()->getManager();
$cart = $this->ss->get();
$cart_details = $this->cart_service->getCartDetails($cart);
// TO-DO faire un service pour savoir le l'environement [dev OU prod]
// $this->paiement_mode = ($this->getParameter('kernel.environment') == "dev") ? 'test' : 'prod';
if(empty($cart_details)) {
return $this->redirectToRoute('home');
} elseif($this->container->get('security.token_storage')->getToken() != null) {
$user = $this->container->get('security.token_storage')->getToken()->getUser();
} else {
return $this->redirectToRoute('customer_login',array('back' => '/paiement'));
}
// dd($this->sanitize_cart_details($cart_details));
$now = new \DateTime('now');
$cartSession = $em->getRepository(CartSession::class)->findOneBy(['id_cart_session' => $user->getId().'_'.$now->format('Ymd')]);
if(!$cartSession) {
$cartSession = new CartSession();
}
$cartSession->setIdCartSession($user->getId().'_'.$now->format('Ymd'));
$cartSession->setIdCustomer($user->getId());
$cartSession->setCartRaw(serialize(array(
'cart' => $cart,
'cart_details' => $this->sanitize_cart_details($cart_details)
)));
$cartSession->setUserAgent($_SERVER['HTTP_USER_AGENT']);
$cartSession->setDateAdd($now);
$em->persist($cartSession);
$em->flush();
return $this->render('etapes/paiement.html.twig', [
'temp' => $this->secretkey[$this->paiement_mode],
'cart' => $cart,
'cart_details' => $cart_details,
'controller_name' => 'PaiementController',
'page_name' => 'page_paiement',
]);
}
private function createReservation($action_paiement, $infos, $json_total_a_payer, $json_total_panier)
{
/* POST Method */
// $data = json_decode($request->request->get('data'));
$data = "";
$error = false;
// if(md5($this->pk) != $request->request->get('key')) exit();
$customer = $this->container->get('security.token_storage')->getToken()->getUser();
$cart = $this->ss->get();
$cart_details = $this->cart_service->getCartDetails($cart);
$date_arrive = new \DateTime($this->cart_service->getDateArrive($cart));
$cm = $this->getDoctrine()->getManager('customer');
$em = $this->getDoctrine()->getManager();
$reservation = new Reservation();
// dd($cart_details);
// On récupère les infos du client
// $customer = $em->getRepository(Customer::Class)->findOneBy(['customerNumber' => $customer->getCustomerNumber()]);
if($customer instanceof Customer)
{
$reservation->setCustomerId($customer->getId());
$reservation->setCustomerNumber($customer->getCustomerNumber());
$reservation->setFirstname($customer->getFirstname());
$reservation->setLastname($customer->getLastname());
$reservation->setCompany($customer->getCompany());
$reservation->setEmail($customer->getEmail());
$reservation->setPhone($customer->getPhone());
$reservation->setPhoneMobile($customer->getPhoneMobile());
$billingAddress = "";
if ($customer->getAddress1() != "" && $customer->getAddress1() != null) $billingAddress .= $customer->getAddress1() . "\n";
if ($customer->getAddress2() != "" && $customer->getAddress2() != null) $billingAddress .= $customer->getAddress2() . "\n";
if ($customer->getPostcode() != "" && $customer->getPostcode() != null) $billingAddress .= $customer->getPostcode() . " ";
if ($customer->getCity() != "" && $customer->getCity() != null) $billingAddress .= $customer->getCity();
$reservation->setBillingAddress($billingAddress);
}
/************************************************/
// Extraction des données du panier
/************************************************/
$formulesArray = array();
$formulesString = '';
$forfaits = array();
// $forfaitsIdArray = array();
$tarifs = array();
$montant_total_ttc = 0;
$montant_total_tva = 0;
$temp_tva_ttcArray = array();
foreach ($cart_details as $key_a => $formule) {
if($formulesString != "") $formulesString .= ', ';
$formulesArray[] = $formule['obj_formule']->getCode();
$formulesString .= $formule['obj_formule']->getCode();
foreach ($formule['forfaits'] as $key_b => $forfait) {
$montant_forfait_ttc = 0;
$montant_forfait_tva = 0;
$forfait_tva_ttcArray = array();
$forfaits[] = $forfait['obj_forfait'];
// $forfaitsIdArray[] = $forfait['obj_forfait']->getId();
foreach ($forfait['tarifs'] as $key => $tarif) {
$montant_total_ttc += $tarif['obj_tarif']->getPriceTtc() * (int) $tarif['qty'];
if(!isset($temp_tva_ttcArray[(string) $tarif['obj_tarif']->getTauxTva()])) {
$temp_tva_ttcArray[(string) $tarif['obj_tarif']->getTauxTva()] = 0;
}
$temp_tva_ttcArray[(string) $tarif['obj_tarif']->getTauxTva()] += $tarif['obj_tarif']->getPriceTtc() * (int) $tarif['qty'];
$montant_forfait_ttc += $tarif['obj_tarif']->getPriceTtc() * (int) $tarif['qty'];
if(!isset($forfait_tva_ttcArray[(string) $tarif['obj_tarif']->getTauxTva()])) {
$forfait_tva_ttcArray[(string) $tarif['obj_tarif']->getTauxTva()] = 0;
}
$forfait_tva_ttcArray[(string) $tarif['obj_tarif']->getTauxTva()] += $tarif['obj_tarif']->getPriceTtc() * (int) $tarif['qty'];
}
foreach ($forfait['options'] as $key => $option) {
$montant_total_ttc += $option['obj_option']->getPriceTtc() * (int) $option['qty'];
if(!isset($temp_tva_ttcArray[(string) $option['obj_option']->getTauxTva()])) {
$temp_tva_ttcArray[(string) $option['obj_option']->getTauxTva()] = 0;
}
$temp_tva_ttcArray[(string) $option['obj_option']->getTauxTva()] += $option['obj_option']->getPriceTtc() * (int) $option['qty'];
$montant_forfait_ttc += $option['obj_option']->getPriceTtc() * (int) $option['qty'];
if(!isset($forfait_tva_ttcArray[(string) $option['obj_option']->getTauxTva()])) {
$forfait_tva_ttcArray[(string) $option['obj_option']->getTauxTva()] = 0;
}
$forfait_tva_ttcArray[(string) $option['obj_option']->getTauxTva()] += $option['obj_option']->getPriceTtc() * (int) $option['qty'];
}
foreach ($forfait_tva_ttcArray as $tva => $montant_ttc) {
$taux = 1 + (float) $tva;
$montant_forfait_tva += $montant_ttc - $montant_ttc/$taux;
}
$cart_details[$key_a]['forfaits'][$key_b]['total_ttc'] = $montant_forfait_ttc;
$cart_details[$key_a]['forfaits'][$key_b]['total_tva'] = $montant_forfait_tva;
}
}
foreach ($temp_tva_ttcArray as $tva => $montant_ttc) {
$taux = 1 + (float) $tva;
$temp_montant_tva = $montant_ttc - $montant_ttc/$taux;
if(isset($cart['code_promo'])) {
$temp_montant_tva = $temp_montant_tva - ($temp_montant_tva * $cart['code_promo']->getPercent());
}
$montant_total_tva += $temp_montant_tva;
}
// $cart['code_promo']->getPercent()
if(isset($cart['bon_numerique'])) {
foreach ($cart['bon_numerique'] as $key => $bon) {
// $bonDetails = new ReservationDetails();
// $bonDetails->setDesignation('Bon numérique : '.$bon['bon'].' ('.$bon['total'].')');
// $bonDetails->setDate($date_arrive);
// $bonDetails->setReservation($reservation);
// $bonDetails->setTotalTTC(round(0 - $bon['total']),2);
// $em->persist($bonDetails);
// $em->flush();
$montant_total_ttc = $montant_total_ttc - $bon['total'];
$montant_total_tva = $montant_total_ttc - ($montant_total_ttc / 1.2 );
}
}
if(isset($cart['code_promo'])) {
if($cart['code_promo']->getTypeReduction() == 'percentage') {
// $montant_total_tva = $montant_total_tva - ($montant_total_tva * $cart['code_promo']->getPercent() );
$montant_total_ttc = $montant_total_ttc - ($montant_total_ttc * $cart['code_promo']->getPercent() );
} elseif($cart['code_promo']->getTypeReduction() == 'montant') {
$montant_total_ttc = $montant_total_ttc - $cart['code_promo']->getReduction();
$montant_total_tva = $montant_total_ttc - ($montant_total_ttc / 1.2 );
// $montantPromoPanier = $cart['code_promo']->getReduction();
}
}
if(in_array('anniversaire',$formulesArray)) {
$creneau_anniv = $cart_details['anniversaire']['forfaits'][0]['infos_anniv']['creneau_anniv'];
$creneauAnniversaire = $date_arrive;
$creneauAnniversaire->add(new \DateInterval('PT'.strtoupper($creneau_anniv).'M'));
$reservation->setDateResa($creneauAnniversaire);
if(isset($cart['birthday_customer_comment']) && $cart['birthday_customer_comment']) {
$reservation->setBirthdayCustomerComment($cart['birthday_customer_comment']);
}
} else {
$reservation->setDateResa($date_arrive);
}
/************************************************/
/************************************************/
$reservation->setFormule($formulesString);
$request = Request::createFromGlobals();
$reservation->setIp($request->getClientIp());
$reservation->setSstotalHT(round($montant_total_ttc - $montant_total_tva, 2));
$reservation->setTVA(round($montant_total_tva, 2));
$reservation->setTotalTTC(round($montant_total_ttc, 2));
$reservation->setActive(0);
if($action_paiement == "carte_1055") {
$reservation->setStatut('Paiement carte 1055');
$reservation->setActive(1);
$comment = "<b>Titulaire carte 1055</b> : ";
if(isset($infos['titulaire_carte_1055']) && !empty($infos['titulaire_carte_1055'])) $comment .= $infos['titulaire_carte_1055'];
if(isset($infos['numero_carte_1055']) && !empty($infos['numero_carte_1055'])) $comment .= " (Mail: ".$infos['numero_carte_1055'].")";
$reservation->setComment($comment);
} elseif($action_paiement == "panier_precommande" && round($montant_total_ttc,0) == 0) {
$reservation->setStatut('Payé');
$reservation->setActive(1);
} else {
$reservation->setStatut('Attente de paiement');
}
$reservation->setDeleted(0);
if(in_array('anniversaire',$formulesArray)) {
$comment = "";
if($reservation->getComment()) {
$comment .= $reservation->getComment();
$comment .= "\n============================\n";
}
$comment .= $cart_details['anniversaire']['forfaits'][0]['infos_anniv']['commentaire'];
// TO-DO calculer l'acompte ===================
if ($json_total_a_payer != "" && $json_total_a_payer != null && $json_total_a_payer != $json_total_panier)
$comment .= "\nAcompte : " . ($json_total_a_payer / 100) . " € ";
$reservation->setComment($comment);
if($cart_details['anniversaire']['forfaits'][0]['infos_anniv']['anniversaire_obj']) {
$reservation->setChildName($cart_details['anniversaire']['forfaits'][0]['infos_anniv']['anniversaire_obj']['name_child']);
$reservation->setChildBirthday($cart_details['anniversaire']['forfaits'][0]['infos_anniv']['anniversaire_obj']['birthday_child']);
$reservation->setChildAge($cart_details['anniversaire']['forfaits'][0]['infos_anniv']['anniversaire_obj']['age_child']);
}
}
$em->persist($reservation);
$em->flush();
$reservation_id = (int)$reservation->getId();
$reservation_number = $reservation->getNumeroResa();
foreach($cart_details as $key => $formule) {
foreach($formule['forfaits'] as $forfaitArray) {
$forfait = $forfaitArray['obj_forfait'];
$resaDetailsArgs = array(
'Reservation' => $reservation,
'Designation' => 'Forfait : ' . $forfait->getDesignation(),
'CodeActivity' => null,
'Date' => $date_arrive,
'Creneau' => null,
'Quantity' => null,
'PuTTC' => null,
'TauxTVA' => null,
'TotalHt' => $forfaitArray['total_ttc'] - $forfaitArray['total_tva'],
'MontantTva' => $forfaitArray['total_tva'],
'TotalTTC' => $forfaitArray['total_ttc'],
'Parent' => null,
);
$resaDetails = $this->addReservationDetail($resaDetailsArgs);
foreach($forfaitArray['tarifs'] as $tarifArray) {
$tarif = $tarifArray['obj_tarif'];
if($tarif) {
$tarifDetailsArgs = array(
'Reservation' => $reservation,
'Designation' => 'Tarif : '. $tarif->getDesignation(),
'CodeActivity' => null,
'Date' => $date_arrive,
'Creneau' => null,
'Quantity' => $tarifArray['qty'],
'PuTTC' => $tarif->getPriceTtc(),
'TauxTVA' => $tarif->getTauxTva(),
'TotalHt' => null,
'MontantTva' => null,
'TotalTTC' => null,
'Parent' => $resaDetails,
);
$tarifDetails = $this->addReservationDetail($tarifDetailsArgs);
}
}
foreach($forfaitArray['options'] as $optionArray) {
$option = $optionArray['obj_option'];
if($option) {
$optionDetailsArgs = array(
'Reservation' => $reservation,
'Designation' => 'Option : '. $option->getDesignation(),
'CodeActivity' => null,
'Date' => $date_arrive,
'Creneau' => null,
'Quantity' => $optionArray['qty'],
'PuTTC' => $option->getPriceTtc(),
'TauxTVA' => $option->getTauxTva(),
'TotalHt' => null,
'MontantTva' => null,
'TotalTTC' => null,
'Parent' => $resaDetails,
);
$optionDetails = $this->addReservationDetail($optionDetailsArgs);
}
}
if(isset($forfaitArray['activity'])) {
foreach($forfaitArray['activity'] as $activityArray) {
$activity = $activityArray['obj_activity'];
$bookedActivity = new BookedActivity();
$bookedActivity->setFormule($formule['obj_formule']->getCode());
$bookedActivity->setForfait($forfait->getDesignation());
$activitySearch = $em->getRepository(Activity::class)->find($activity->getId());
if($activitySearch)
{
$bookedActivity->setCodeActivity($activitySearch->getCode());
$bookedActivity->setDesignation($activitySearch->getDesignation());
} else {
$bookedActivity->setCodeActivity(Tools::str2url($activity->getDesignation()));
$bookedActivity->setDesignation($activity->getDesignation());
}
if(isset($activityArray['creneau'])) {
$creneau_activity = $activityArray['creneau'];
$creneauActivity = new \DateTime($date_arrive->format('Y-m-d'));
$creneauActivity->add(new \DateInterval('PT'.strtoupper($creneau_activity).'M'));
$creneauActivity_Check = new \DateTime($date_arrive->format('Y-m-d'));
$creneauActivity_Check->add(new \DateInterval('P1D'));
$creneauActivity_Check->add(new \DateInterval('PT'.strtoupper($creneau_activity).'M'));
$interval = $creneauActivity->diff($creneauActivity_Check);
if($interval->format('%R%h') == '+1') {
$creneauActivity->add(new \DateInterval('PT1H'));
} elseif( $interval->format('%R%h') == '-1') {
$creneauActivity->sub(new \DateInterval('PT1H'));
}
$bookedActivity->setDate($creneauActivity);
$bookedActivity->setCreneau($creneauActivity);
} else {
$bookedActivity->setDate($date_arrive);
//TO-DO : voir si on réserve toutes les activités au créneau de l'anniversaire ou non
if(in_array('anniversaire',$formulesArray)) {
$bookedActivity->setCreneau($creneauAnniversaire);
}
// =========================================================================
}
$bookedQty = (isset($activityArray['parties'])) ? $activityArray['qty'] : ($activityArray['qty'] / $activityArray['parties']);
$bookedActivity->setQuantity($bookedQty);
// $bookedActivity->setQuantity($activityArray['qty']);
$bookedActivity->setNbreParties($activityArray['parties']);
$bookedActivity->setReservation($reservation);
$bookedActivity->setAdmin(0);
$em->persist($bookedActivity);
$em->flush();
}
}
}
}
if(isset($cart['bon_numerique'])) {
foreach ($cart['bon_numerique'] as $key => $bon) {
$bonDetails = new ReservationDetails();
$bonDetails->setDesignation('E-ticket : '.$bon['bon'].' ('.$bon['total'].')');
$bonDetails->setDate($date_arrive);
$bonDetails->setReservation($reservation);
$bonDetails->setTotalTTC(round(0 - $bon['total'],2));
$em->persist($bonDetails);
$em->flush();
}
}
if(isset($cart['code_promo'])) {
if($cart['code_promo']->getTypeReduction() == 'percentage') $montantPromoPanier = '-'.($cart['code_promo']->getPercent()*100).'%';
elseif($cart['code_promo']->getTypeReduction() == 'montant') $montantPromoPanier = '-'.$cart['code_promo']->getReduction().'€';
$promoPanierDetails = new ReservationDetails();
$promoPanierDetails->setDesignation('Code promo : '.$cart['code_promo']->getCode().' ('.$montantPromoPanier.')');
$promoPanierDetails->setDate($date_arrive);
$promoPanierDetails->setReservation($reservation);
if($cart['code_promo']->getTypeReduction() == 'percentage') {
$montant_reduction = round(0 - ($reservation->getTotalTTC()*$cart['code_promo']->getPercent()),2);
} else if($cart['code_promo']->getTypeReduction() == 'montant') {
$montant_reduction = round(0 - $cart['code_promo']->getReduction(),2);
}
$promoPanierDetails->setTotalTTC($montant_reduction);
$em->persist($promoPanierDetails);
$em->flush();
}
$em->persist($reservation);
$em->flush();
//Historique de solde
$history_resa = new History();
if($customer instanceof Customer)
{
$history_resa->setCustomerId($customer->getId());
$history_resa->setInformation("Réservation " . $reservation_number . " (#" . $reservation_id . ")");
$resa_total_ttc = abs($reservation->getTotalTTC()) * -1;
$history_resa->setMouvement($resa_total_ttc);
$history_resa->setReservation($reservation);
$em->persist($history_resa);
$em->flush();
}
// dd($forfaitArray['activity']);
return $reservation;
}
/**
* @Route("/createpaiement", methods={"POST"}, name="booking_createpaiement")
* Cette fonction permet de créer le formulaire de paiement
*/
public function createPaiement(Request $request)
{
// action_paiement : - carte_payplug
// - carte_1055
// dd($this->secretkey[$this->paiement_mode]);
$data = json_decode($request->request->get('data'));
$error = false;
$action_paiement = $data->action_paiement;
$json_total_panier = $data->total_panier;
$json_total_a_payer = $data->total_a_payer;
$titulaire_carte_1055 = $data->titulaire_carte_1055;
$numero_carte_1055 = $data->numero_carte_1055;
$infos = array();
if($titulaire_carte_1055) $infos['titulaire_carte_1055'] = $titulaire_carte_1055;
if($numero_carte_1055) $infos['numero_carte_1055'] = $numero_carte_1055;
$reservation = $this->createReservation($action_paiement, $infos, $json_total_a_payer, $json_total_panier);
$reservation_id = (int)$reservation->getId();
$reservation_number = $reservation->getNumeroResa();
$total_a_payer = $reservation->getTotalTTC();
$customer = $this->container->get('security.token_storage')->getToken()->getUser();
$customer_number = $customer->getCustomerNumber();
$return_url = $this->generateUrl('success', array(), UrlGeneratorInterface::ABSOLUTE_URL);
$cancel_url = $this->generateUrl('cancel', array(), UrlGeneratorInterface::ABSOLUTE_URL);
$notification_url = $this->generateUrl('notification', array(), UrlGeneratorInterface::ABSOLUTE_URL);
if($action_paiement == "carte_1055") {
file_get_contents($notification_url . '?idresa='.$reservation_number."&p=1");
$data->return_url = $return_url . '?idresa='.$reservation_number."&p=1";
} else if($action_paiement == "panier_precommande") {
file_get_contents($notification_url . '?idresa='.$reservation_number."&pre=1");
$data->return_url = $return_url . '?idresa='.$reservation_number."&pre=1";
} else if($action_paiement == "carte_payplug") {
$vendor_dir = str_replace('src','vendor',dirname(__DIR__));
require_once($vendor_dir . '/payplug/payplug-php/lib/init.php');
// \Payplug\Payplug::setSecretKey($this->secretkey);
\Payplug\Payplug::init(array(
'secretKey' => $this->secretkey[$this->paiement_mode],
));
if($customer->getEmail() != "")
$email = $customer->getEmail();
else
$error = 'no email';
if( $customer->getPhoneMobile() != "") {
$phoneMobile = str_replace(' ','',$customer->getPhoneMobile());
$phoneMobile = str_replace('.','',$phoneMobile);
$phoneMobile = str_replace('-','',$phoneMobile);
if(strlen($phoneMobile) == 10 && strpos($customer->getPhoneMobile(),'+') === false) {
$phoneMobile = '+33'.substr($phoneMobile,1);
} elseif(substr($phoneMobile, 0, 2) === "00" && strlen($phoneMobile) == 13) {
$phoneMobile = '+'.substr($phoneMobile, 2);
}
}
else
$error = 'no mobile phone';
$firstname = $customer->getFirstname();
$lastname = $customer->getLastname();
$address1 = $customer->getAddress1();
$address2 = ($customer->getAddress2() != "") ? $customer->getAddress2() : null;
$postcode = $customer->getPostcode();
$city = $customer->getCity();
$country = $customer->getCountry();
// if (isset($reservation->acompte_paiement) && ($reservation->acompte_paiement) > 0)
// $amount = intval(number_format($reservation->acompte_paiement * 100, 0, '.', ''));
// elseif (isset($reservation->total_a_payer) && ($reservation->total_a_payer) > 0)
// $amount = intval(number_format($reservation->total_a_payer * 100, 0, '.', ''));
// else
// $error = 'no amount';
if($total_a_payer != ($json_total_a_payer/100) && ((int) round($total_a_payer*100,0)) == $json_total_panier) {
$amount = $json_total_a_payer;
} else {
$amount = (int) round($total_a_payer*100,0);
}
$arg_payplug = array(
'amount' => $amount,
'currency' => 'EUR',
// 'save_card' => true, // TO-DO : change to true en mode PROD si 1055 OK
'billing' => array(
'first_name' => $firstname,
'last_name' => $lastname,
'email' => $email,
'address1' => $address1,
'address2' => $address2,
'mobile_phone_number' => $phoneMobile,
'city' => $city,
'postcode' => $postcode,
'country' => $country,
'language' => 'fr',
),
'shipping' => array(
'email' => $email,
'first_name' => $firstname,
'last_name' => $lastname,
'address1' => $address1,
'address2' => $address2,
'mobile_phone_number' => $phoneMobile,
'city' => $city,
'postcode' => $postcode,
'country' => $country,
'language' => 'fr',
'delivery_type' => 'TRAVEL_OR_EVENT', // OTHER ou BILLING
),
'hosted_payment' => array(
'return_url' => $return_url . '?idresa='.$reservation_number,
'cancel_url' => $cancel_url . '?idresa='.$reservation_number,
),
'notification_url' => $notification_url . '?idresa='.$reservation_number,
'metadata' => array(
'customer_number' => $customer_number,
'reservation_id' => $reservation_id,
'reservation_number' => $reservation_number
)
);
// dd($arg_payplug);
try{
$payment = \Payplug\Payment::create($arg_payplug);
}
catch(\Exception $e){
$error = serialize($arg_payplug);
}
if(!$error){
$data->payment_url = $payment->hosted_payment->payment_url;
$data->payment_id = $payment->id;
$em = $this->getDoctrine()->getManager();
$reservation->setPaymentId($payment->id);
$today = new \DateTime('now');
$history = $reservation->getHistory();
$request = Request::createFromGlobals();
$history .= $request->headers->get('User-Agent')."\n".'--------------------------'."\n";
$history .= $today->format("d/m/Y H:i:s") . " : Transaction créée (" . $payment->id . ")\n";
$reservation->setHistory($history);
$em->persist($reservation);
$em->flush();
}
}
if(!$error){
$today = new \DateTime('now');
$em = $this->getDoctrine()->getManager();
$cartSession = $em->getRepository(CartSession::class)->findOneBy(['id_cart_session' => $customer->getId().'_'.$today->format('Ymd')]);
if($cartSession instanceof CartSession) {
$em->remove($cartSession);
$em->flush();
}
}
if ($error) {
return new JsonResponse(['error' => $error, 'data' => $arg_payplug], JsonResponse::HTTP_CREATED);
} else {
return new JsonResponse($data, JsonResponse::HTTP_CREATED);
}
}
/**
* @Route("/success", methods={"GET", "POST"}, name="success")
* Cette fonction permet d'afficher la page de succès après paiement réussi
*/
public function successAction(Request $request, MailerInterface $mailer)
{
$cart = $this->ss->get();
$this->ss->empty();
$vendor_dir = str_replace('src','vendor',dirname(__DIR__));
require_once($vendor_dir . '/payplug/payplug-php/lib/init.php');
\Payplug\Payplug::init(array(
'secretKey' => $this->secretkey[$this->paiement_mode],
));
/* GET Method */
$reservation_number = $request->query->get('idresa');
$carte_1055 = ($request->query->get('p') != null && $request->query->get('p') == '1') ? true : false;
$panier_precommande = ($request->query->get('pre') != null && $request->query->get('pre') == '1') ? true : false;
$reservation_date = null;
$transaction_ok = null;
$failure_id = null;
$error = null;
$print_url = $this->generateUrl('print', array(), UrlGeneratorInterface::ABSOLUTE_URL);
$print_url .= '?idresa=';
if($reservation_number != null && $reservation_number != "")
{
$em = $this->getDoctrine()->getManager();
$reservation = $em->getRepository(Reservation::class)->findOneBy(['numeroResa' => $reservation_number]);
if (!$reservation) {
$error = 'Aucune réservation trouvée. Veuillez nous contacter par téléphone.';
}
if($reservation instanceof Reservation)
{
$payment_id = $reservation->getPaymentId();
$reservation_number = $reservation->getNumeroResa();
$reservation_date = $reservation->getDateResa();
$reservation_montant_ht = $reservation->getSstotalHT();
$reservation_montant = $reservation->getTotalTTC();
$transaction_ok = false;
$print_url .= $reservation_number;
$reservation_regle = 0;
if($payment_id != null && $payment_id != "" && $this->paiement_mode != "test")
{
$payment = \Payplug\Payment::retrieve($payment_id);
if($payment->is_paid && $payment->failure == null) {
$transaction_ok = true;
$reservation_regle = $payment->amount / 100;
} elseif(!$payment->is_paid && $payment->failure != null) {
$failure_id = $payment->failure->message;
}
}
if($carte_1055) {
$print_url .= "&p=1";
}
// ##################
// Compostage Voucher
if(($carte_1055 || $transaction_ok || (float) $reservation_montant == 0) && isset($cart['bon_numerique'])) {
foreach ($cart['bon_numerique'] as $key => $bon) {
$data = $this->vs->getVoucher($bon['bon']);
if ( $data['_remaining_value'] != 0 && $data['status'] == "wcpdf-active") {
$target = $bon['bon'];
$quantity = isset($bon['qty']) ? $bon['qty'] : '';
$amount = isset($bon['bon_total']) ? $bon['bon_total'] : '';
if($data['unlimited_voucher']) {
$amount = 1 * $bon['total'] / 1.1;
}
$param = 'action=set&target='.$target.'&quantity='.$quantity.'&amount='.$amount.'&user='.$this->user_id_boutique.'&demandeur=client';
$result = $this->vs->getData($param);
}
}
}
// FIN Compostage Voucher
// ##################
}
} else $error = "Votre numéro de réservation n'est pas indiqué ou il est non valide.";
$formules = explode(',',$reservation->getFormule());
return $this->render('paiement/success.html.twig', array(
'environnement' => $this->paiement_mode,
'date_resa' => ($reservation_date != null) ? $reservation_date->format("d/m/Y") : null ,
'creneau_resa' => ($reservation_date != null && in_array('anniversaire',$formules)) ? $reservation_date->format('H:i') : null ,
'reservation' => $reservation,
'carte_1055' => $carte_1055,
'panier_precommande' => $panier_precommande,
'transaction_ok' => $transaction_ok,
'reservation_regle' => number_format($reservation_regle, 2, ',', ' ') . ' €',
'reservation_montant' => number_format($reservation_montant, 2, ',', ' ') . ' €',
'reservation_montant_tva' => number_format(($reservation_montant - $reservation_montant_ht), 2, ',', ' ') . ' €',
'reservation_montant_ht' => number_format($reservation_montant_ht, 2, ',', ' ') . ' €',
'print_url' => $print_url,
'failure_id' => $failure_id,
'error' => $error
));
}
/**
* @Route("/cancel", methods={"GET", "POST"}, name="cancel")
* Cette fonction permet d'afficher la page de paiement annulé
*/
public function cancelAction(Request $request)
{
$vendor_dir = str_replace('src','vendor',dirname(__DIR__));
require_once($vendor_dir . '/payplug/payplug-php/lib/init.php');
\Payplug\Payplug::init(array(
'secretKey' => $this->secretkey[$this->paiement_mode],
));
$reservation_number = $request->query->get('idresa');
if($reservation_number != null && $reservation_number != "")
{
$em = $this->getDoctrine()->getManager();
$reservation = $em->getRepository(Reservation::class)->findOneBy(['numeroResa' => $reservation_number]);
$resource = \Payplug\Payment::retrieve($reservation->getPaymentId());
$payment_id = $resource->id;
$payment_amount = $resource->amount / 100;
$payment_amount_format = number_format($resource->amount / 100, 2, ',', ' ');
if($reservation instanceof Reservation && $reservation->getPaymentId() == $payment_id ) {
$customer_number = $reservation->getCustomerNumber();
$cm = $this->getDoctrine()->getManager("customer");
$customer = $cm->getRepository(Customer::class)->findOneBy(['customerNumber' => $customer_number]);
if ($resource instanceof \Payplug\Resource\Payment && !$resource->is_paid)
{
$message_error = $this->getErrorMsgPayplug($resource->failure->code);
// $reservation->setStatut('Payé');
$failure_code = 'non disponible';
if($resource->failure != null && ($resource->failure->code == 'aborted' || $resource->failure->code == 'timeout')){
$failure_code = $resource->failure->code;
$reservation->setStatut('Abandon');
} else {
$reservation->setStatut('Erreur paiement');
}
$dateTimeZone = new \DateTimeZone('Europe/Paris');
$today = new \DateTime('now', $dateTimeZone);
$history = $reservation->getHistory();
$history .= $today->format("d/m/Y H:i:s") . " : Transaction échoué de " . $payment_amount_format . " € (" . $payment_id . ")\n";
$history .= "------------------- : Payplug #(".$message_error.")\n";
$reservation->setHistory($history);
$history_solde = new History();
if($customer instanceof Customer)
{
$history_solde->setCustomerId($customer->getId());
$history_solde->setInformation("Erreur PAYPLUG : " . $reservation_number . " (" . $payment_id . ") [".$failure_code."]");
$history_solde->setMouvement($payment_amount);
$history_solde->setReservation($reservation);
$em->persist($history_solde);
}
}
}
$em->persist($reservation);
$em->flush();
}
return $this->redirectToRoute('payment');
}
private function getErrorMsgPayplug($error_code)
{
switch ($error_code) {
case 'processing_error':
$error_msg = "Erreur lors du traitement de la carte.";
break;
case 'card_declined':
$error_msg = "La banque du client a refusé la demande de paiement.";
break;
case '3ds_declined':
$error_msg = "La requête d'authentification 3D Secure a échoué";
break;
case 'insufficient_funds':
$error_msg = "La carte a atteint son plafond autorisé";
break;
case 'incorrect_number':
$error_msg = "Les informations de la carte sont incorrectes (numéro, date d’exp. ou le CVV)";
break;
case 'fraud_suspected':
$error_msg = "Paiement refusé car une fraude a été détectée.";
break;
case 'method_unsupported':
$error_msg = "Le moyen de paiement n'est pas supporté";
break;
case 'card_scheme_mismatch':
$error_msg = "Le numéro de carte ne correspond pas à la marque sélectionnée.";
break;
case 'card_expiration_date_prior_to_last_installment_date':
$error_msg = "La date d'expiration de la carte est antérieure à la date du dernier versement.";
break;
case 'aborted':
$error_msg = "Le paiement a été abandonné";
break;
case 'timeout':
$error_msg = "Le client n'a pas essayé de payer et a quitté la page de paiement.";
break;
default:
$error_msg = "Erreur de paiement";
break;
}
return $error_msg;
}
/**
* @Route("/notification", methods={"GET", "POST"}, name="notification")
* Cette fonction permet d'afficher la page de succès après paiement réussi
*/
public function notificationAction(Request $request, MailerInterface $mailer)
{
$vendor_dir = str_replace('src','vendor',dirname(__DIR__));
require_once($vendor_dir . '/payplug/payplug-php/lib/init.php');
\Payplug\Payplug::init(array(
'secretKey' => $this->secretkey[$this->paiement_mode],
));
$error = null;
// $input = file_get_contents('php://input');
$idresa = $request->query->get('idresa');
$carte_1055 = ($request->query->get('p') != null && $request->query->get('p') == '1') ? true : false;
$panier_precommande = ($request->query->get('pre') != null && $request->query->get('pre') == '1') ? true : false;
$em = $this->getDoctrine()->getManager();
$reservationVerif = $em->getRepository(Reservation::class)->findOneBy(['numeroResa' => $idresa]);
// $resource = \Payplug\Payment::retrieve($reservationVerif->getPaymentId());
// $input = file_get_contents('php://input');
try {
// $resource = \Payplug\Notification::treat($input);
if($reservationVerif->getPaymentId() != "") {
$resource = \Payplug\Payment::retrieve($reservationVerif->getPaymentId());
// $payment_id = 'pay_1GJ2PMEWFPSIgfNbeWkv9a'; $resource = \Payplug\Payment::retrieve($payment_id); // POUR DEBUG
if ($resource instanceof \Payplug\Resource\Payment)
{
$payment_id = $resource->id;
$payment_state = $resource->is_paid;
$payment_date = $resource->hosted_payment->paid_at;
$payment_amount = $resource->amount / 100;
$payment_amount_format = number_format($resource->amount / 100, 2, ',', ' ');
if (isset($resource->metadata['customer_number'])) $customer_number = $resource->metadata['customer_number'];
if (isset($resource->metadata['customer_id'])) $customer_number = $resource->metadata['customer_id'];
$reservation_id = $resource->metadata['reservation_id'];
$reservation_number = $resource->metadata['reservation_number'];
$failure_id = $resource->failure;
$reservation = $em->getRepository(Reservation::class)->findOneBy(['numeroResa' => $reservation_number]);
if($reservation instanceof Reservation && $reservation->getPaymentId() == $payment_id && !$reservation->getActive())
{
$customer_number = $reservation->getCustomerNumber();
$cm = $this->getDoctrine()->getManager("customer");
$customer = $cm->getRepository(Customer::class)->findOneBy(['customerNumber' => $customer_number]);
if($resource->is_paid && $resource->failure == null)
{
$reservation->setStatut('Payé');
$reservation->setActive(1);
$dateTimeZone = new \DateTimeZone('Europe/Paris');
$today = new \DateTime('now', $dateTimeZone);
$history = $reservation->getHistory();
$history .= $today->format("d/m/Y H:i:s") . " : Transaction réussie de " . $payment_amount_format . " € (" . $payment_id . ")\n";
$reservation->setHistory($history);
$history_solde = new History();
// $customer = $em->getRepository(Customer::Class)->findOneBy(['customerNumber' => $customer_number]);
if($customer instanceof Customer)
{
$history_solde->setCustomerId($customer->getId());
$history_solde->setInformation("Paiement PAYPLUG : " . $reservation_number . " (" . $payment_id . ")");
$history_solde->setMouvement($payment_amount);
$history_solde->setReservation($reservation);
$em->persist($history_solde);
}
//Envoi des emails
$transaction_ok = true;
$comment = $reservation->getComment();
// if(strpos($comment,'Titulaire carte 1055') !== false) {
// $transaction_ok = 'carte_1055';
// }
$reservation_date = $reservation->getDateResa();
$reservation_montant_ht = $reservation->getSstotalHT();
$reservation_montant = $reservation->getTotalTTC();
$reservation_regle = $resource->amount / 100;
$print_url = $this->generateUrl('print', array(), UrlGeneratorInterface::ABSOLUTE_URL);
$message = (new Email())
->subject('Votre réservation au 1055 : ' . $reservation_number)
->from('reservationbesancon@1055.fr')
->to($customer->getEmail())
->cc('reservationbesancon@1055.fr')
->replyTo('besancon@1055.fr')
// ->addCc('dev@publigo.fr')
->html(
$this->renderView(
'email/confirmation.html.twig',
array(
'email' => strtolower($customer->getEmail()),
'firstname' => ucfirst($customer->getFirstname()),
'lastname' => strtoupper($customer->getLastname()),
'address1' => strtoupper($customer->getAddress1()),
'address2' => strtoupper($customer->getAddress2()),
'postcode' => $customer->getPostcode(),
'city' => strtoupper($customer->getCity()),
'phone' => $customer->getPhone(),
'phoneMobile' => $customer->getPhoneMobile(),
'reservation' => $reservation,
'infos_resa' => $reservation->getComment(),
'date_resa' => ($reservation_date != null) ? $reservation_date->format("d/m/Y") : null,
'creneau_resa' => ($reservation_date != null && $reservation->getFormule() == 'anniversaire') ? $reservation_date->format('H:i') : null ,
'numero_resa' => $reservation_number,
'carte_1055' => false,
'panier_precommande' => false,
'transaction_ok' => $transaction_ok,
'reservation_regle' => number_format($reservation_regle, 2, ',', ' ') . ' €',
'reservation_montant' => number_format($reservation_montant, 2, ',', ' ') . ' €',
'reservation_montant_tva' => number_format(($reservation_montant - $reservation_montant_ht), 2, ',', ' ') . ' €',
'reservation_montant_ht' => number_format($reservation_montant_ht, 2, ',', ' ') . ' €',
'print_url' => $print_url . '?idresa='.$reservation_number,
'failure_id' => $failure_id,
'error' => $error
)
)
);
$mailer->send($message);
$em->persist($reservation);
$em->flush();
} else {
$cancel_url = $this->generateUrl('cancel', array(), UrlGeneratorInterface::ABSOLUTE_URL);
// $cancel_url . '?idresa='.$reservation_number
return $this->redirectToRoute('cancel',array('idresa' => $reservation_number));
}
$em->persist($reservation);
$em->flush();
}
}
}
if($carte_1055 || $panier_precommande) {
if($reservationVerif instanceof Reservation )
{
$customer_number = $reservationVerif->getCustomerNumber();
$cm = $this->getDoctrine()->getManager("customer");
$customer = $cm->getRepository(Customer::class)->findOneBy(['customerNumber' => $customer_number]);
$today = new \DateTime('now');
$history = $reservationVerif->getHistory();
$request = Request::createFromGlobals();
$history .= $request->headers->get('User-Agent')."\n".'--------------------------'."\n";
if($carte_1055) $history .= $today->format("d/m/Y H:i:s") . " : Demande de paiement par Carte 10 55\n";
else if($panier_precommande) $history .= $today->format("d/m/Y H:i:s") . " : Paiement par bon numérique\n";
$reservationVerif->setHistory($history);
$failure_id = false;
$transaction_ok = $carte_1055 ? $carte_1055 : $panier_precommande;
$comment = $reservationVerif->getComment();
$reservation_date = $reservationVerif->getDateResa();
$reservation_montant_ht = $reservationVerif->getSstotalHT();
$reservation_montant = $reservationVerif->getTotalTTC();
$reservation_regle = 0;
$print_url = $this->generateUrl('print', array(), UrlGeneratorInterface::ABSOLUTE_URL);
$message = (new Email())
->subject('Votre réservation au 1055 : ' . $idresa)
->from('reservationbesancon@1055.fr')
->to($customer->getEmail())
->cc('reservationbesancon@1055.fr')
->replyTo('besancon@1055.fr')
// ->addCc('dev@publigo.fr')
->html(
$this->renderView(
'email/confirmation.html.twig',
array(
'email' => strtolower($customer->getEmail()),
'firstname' => ucfirst($customer->getFirstname()),
'lastname' => strtoupper($customer->getLastname()),
'address1' => strtoupper($customer->getAddress1()),
'address2' => strtoupper($customer->getAddress2()),
'postcode' => $customer->getPostcode(),
'city' => strtoupper($customer->getCity()),
'phone' => $customer->getPhone(),
'phoneMobile' => $customer->getPhoneMobile(),
'reservation' => $reservationVerif,
'infos_resa' => $reservationVerif->getComment(),
'date_resa' => ($reservation_date != null) ? $reservation_date->format("d/m/Y") : null,
'creneau_resa' => ($reservation_date != null && $reservationVerif->getFormule() == 'anniversaire') ? $reservation_date->format('H:i') : null ,
'numero_resa' => $idresa,
'carte_1055' => $carte_1055,
'panier_precommande' => $panier_precommande,
'transaction_ok' => false,
'reservation_regle' => number_format($reservation_regle, 2, ',', ' ') . ' €',
'reservation_montant' => number_format($reservation_montant, 2, ',', ' ') . ' €',
'reservation_montant_tva' => number_format(($reservation_montant - $reservation_montant_ht), 2, ',', ' ') . ' €',
'reservation_montant_ht' => number_format($reservation_montant_ht, 2, ',', ' ') . ' €',
'print_url' => $print_url . '?idresa='.$idresa,
'failure_id' => $failure_id,
'error' => $error
)
)
);
$mailer->send($message);
$em->persist($reservationVerif);
$em->flush();
}
}
}
catch (\Payplug\Exception\PayplugException $exception) {
echo $exception;
}
return $this->render('paiement/notification.html.twig', array());
}
/**
* @Route("/print", methods={"GET", "POST"}, name="print")
* Cette fonction permet d'imprimer le PDF de réservation
*/
public function printAction(Request $request)
{
$vendor_dir = str_replace('src','vendor',dirname(__DIR__));
require_once($vendor_dir . '/payplug/payplug-php/lib/init.php');
\Payplug\Payplug::init(array(
'secretKey' => $this->secretkey[$this->paiement_mode],
));
/* GET Method */
$reservation_number = $request->query->get('idresa');
$carte_1055 = $request->query->get('p');
$panier_precommande = $request->query->get('pre');
$error = null;
// $snappy = $this->get('knp_snappy.pdf');
$pageUrl = $this->generateUrl('home', array(), false);
if($reservation_number != null && $reservation_number != "")
{
$em = $this->getDoctrine()->getManager();
$reservation = $em->getRepository(Reservation::class)->findOneBy(['numeroResa' => $reservation_number]);
$customer_id = $reservation->getCustomerId();
$cm = $this->getDoctrine()->getManager("customer");
$customer = $cm->getRepository(Customer::class)->findOneBy(['id' => $customer_id]);
if (!$reservation) {
$error = 'Aucune réservation trouvée. Veuillez nous contacter par téléphone.';
}
if($reservation instanceof Reservation)
{
$payment_id = $reservation->getPaymentId();
$reservation_number = $reservation->getNumeroResa();
$reservation_date = $reservation->getDateResa();
$reservation_montant_ht = $reservation->getSstotalHT();
$reservation_montant = $reservation->getTotalTTC();
$transaction_ok = false;
$failure_id = false;
$reservation_regle = 0;
if($payment_id != null && $payment_id != "")
{
$payment = \Payplug\Payment::retrieve($payment_id);
if($payment->is_paid && $payment->failure == null) {
$transaction_ok = true;
$reservation_regle = $payment->amount / 100;
} elseif(!$payment->is_paid && $payment->failure != null) {
$transaction_ok = false;
$failure_id = $payment->failure->message;
}
}
if($carte_1055) {
$transaction_ok = 'carte_1055';
}
if($panier_precommande) {
$transaction_ok = 'panier_precommande';
}
}
} else $error = "Votre numéro de réservation n'est pas indiqué ou il est non valide.";
return $this->render(
'paiement/print.html.twig',
array(
'environnement' => $this->paiement_mode,
'date_resa' => ($reservation_date != null) ? $reservation_date->format("d/m/Y") : null ,
'creneau_resa' => ($reservation_date != null && $reservation->getFormule() == 'anniversaire') ? $reservation_date->format('H:i') : null ,
'numero_resa' => $reservation_number,
'transaction_ok' => $transaction_ok,
'reservation' => $reservation,
'customer' => $customer,
'reservation_regle' => number_format($reservation_regle, 2, ',', ' ') . ' €',
'reservation_montant' => number_format($reservation_montant, 2, ',', ' ') . ' €',
'reservation_montant_tva' => number_format(($reservation_montant - $reservation_montant_ht), 2, ',', ' ') . ' €',
'reservation_montant_ht' => number_format($reservation_montant_ht, 2, ',', ' ') . ' €',
// 'print_url' => '?idresa='.$reservation_number,
'failure_id' => $failure_id,
'page_url' => $pageUrl,
'error' => $error
)
);
}
private function addReservationDetail(array $args)
{
$em = $this->getDoctrine()->getManager();
$reservationDetails = new ReservationDetails();
$reservationDetails->setReservation($args['Reservation']);
$reservationDetails->setDesignation($args['Designation']);
$reservationDetails->setCodeActivity($args['CodeActivity']);
$reservationDetails->setDate($args['Date']);
$reservationDetails->setCreneau($args['Creneau']);
$reservationDetails->setQuantity($args['Quantity']);
$reservationDetails->setPuTTC($args['PuTTC']);
$reservationDetails->setTauxTVA($args['TauxTVA']);
$reservationDetails->setTotalHt($args['TotalHt']);
$reservationDetails->setMontantTva($args['MontantTva']);
$reservationDetails->setTotalTTC($args['TotalTTC']);
$reservationDetails->setParent($args['Parent']);
$em->persist($reservationDetails);
$em->flush();
return $reservationDetails;
}
private function sanitize_cart_details($cart_details)
{
$return_cart_details = $cart_details;
foreach ($cart_details as $code_formule => $value_formule) {
$return_cart_details[$code_formule]['obj_formule'] = $value_formule['obj_formule']->getID();
foreach ($value_formule['forfaits'] as $key_forfait => $value_forfait) {
$return_cart_details[$code_formule]['forfaits'][$key_forfait]['obj_forfait'] = $value_forfait['obj_forfait']->getDesignation();
foreach ($value_forfait['tarifs'] as $key_tarif => $value_tarif) {
$return_cart_details[$code_formule]['forfaits'][$key_forfait]['tarifs'][$key_tarif]['obj_tarif'] = $value_tarif['obj_tarif']->getDesignation();
}
if(isset($value_forfait['options']) && $value_forfait['options']) {
foreach ($value_forfait['options'] as $key_option => $value_option) {
$return_cart_details[$code_formule]['forfaits'][$key_forfait]['options'][$key_option]['obj_option'] = $value_option['obj_option']->getDesignation();
}
}
if(isset($value_forfait['activity']) && $value_forfait['activity']) {
foreach ($value_forfait['activity'] as $key_activity => $value_activity) {
$return_cart_details[$code_formule]['forfaits'][$key_forfait]['activity'][$key_activity]['obj_activity'] = $value_activity['obj_activity']->getDesignation();
}
}
}
}
return $return_cart_details;
}
}