src/Controller/TarifsController.php line 33

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Client;
  4. use App\Entity\Config;
  5. use App\Services\CallApiServices;
  6. use App\Services\QuestionMailService;
  7. use App\Services\webhooksMollie;
  8. use PhpParser\Node\Expr\Instanceof_;
  9. use Prophecy\Call\Call;
  10. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  11. use Symfony\Component\HttpFoundation\Response;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Component\Routing\Annotation\Route;
  14. use Psr\Log\LoggerInterface;
  15. use function Symfony\Component\DependencyInjection\Loader\Configurator\service;
  16. class TarifsController extends AbstractController
  17. {
  18.     private $logger;
  19.     
  20.     public function __construct(LoggerInterface $logger)
  21.     {
  22.         $this->logger $logger;
  23.     }
  24.     /**
  25.      * @Route("/tarifs", name="app_tarifs")
  26.      */
  27.     public function index(CallApiServices $callApiServices): Response
  28.     {
  29.         $config = new Config();
  30.         $serviceId $config->getServiceId();
  31.   
  32.     
  33.         $tarifsPlateforme $callApiServices->tarifsPlateforme($serviceId);
  34.         return $this->render('tarifs/index.html.twig', [
  35.             'tarifsPlateforme' => $tarifsPlateforme,
  36.         ]);
  37.     }
  38.     /**
  39.      * @Route("/payment/{id}", name="app_payment")
  40.      */
  41.     public function payment(CallApiServices $callApiServices$id): Response
  42.     {
  43.         $accountId $this->getParameter('app.accountId');
  44.         $user $this->getUser();
  45.         if ($user instanceof Client) {
  46.             $serviceId $user->getServiceId();
  47.             $code $user->getCode();
  48.             $email $user->getEmail();
  49.             $clientId $user->getClientId();
  50.             $firstName $user->getFirstName();
  51.             $lastName $user->getLastName();
  52.         }
  53.         $tarifsPlateforme $callApiServices->tarifsPlateforme($serviceId);
  54.         $prix $tarifsPlateforme[$id]['prix'];
  55.        
  56.         $data = array('act' => 'emspay''mnt' => number_format($prix2), 'devise' => '978''ref' => 'REF_' $clientId '_' time());
  57.         $table = [
  58.             'amount' => $prix,
  59.             'reference' => $data['ref'],
  60.             'accountId' =>  $accountId,
  61.             'serviceId' =>  $serviceId,
  62.             'stamp' => time() + 60,
  63.             'idClient' => $clientId,
  64.             'code' => $code,
  65.             'customREF' => $data['ref']
  66.         ];
  67.         $customTable json_encode($table);
  68.         $table base64_encode($customTable);
  69.         $time = new \DateTime();
  70.         $time $time->format('d/m/Y');
  71.         $config = new Config();
  72.         return $this->render('tarifs/payment.html.twig', [
  73.             'query' => $table,
  74.             'tarif' => $tarifsPlateforme[$id],
  75.             'config' => $config,
  76.         ]);
  77.     }
  78.    
  79.     /**
  80.      * @Route("/tarifs/{id}", name="app_parrain")
  81.      */
  82.     public function achatParrain(CallApiServices $callApiServices$idRequest $request): Response
  83.     {
  84.         $session $request->getSession();
  85.         $session->set('parrainId'$id);
  86.         return $this->redirectToRoute("app_tarifs");
  87.     }
  88.     /**
  89.      * @Route("/confirm-transaction/{id}", name="app_confirmTransaction")
  90.      */
  91.     public function confirmTransaction(CallApiServices $callApiServices$id): Response
  92.     {
  93.         $serviceId $this->getParameter('app.serviceId');
  94.         $accountId $this->getParameter('app.accountId');
  95.         $tarifsPlateforme $callApiServices->tarifsPlateforme($serviceId);
  96.         return $this->render('tarifs/confirmTransaction.html.twig', [
  97.             'tarifsPlateforme' => $tarifsPlateforme,
  98.             'tarif' => $tarifsPlateforme[$id],
  99.             'key' => $id,
  100.         ]);
  101.     }
  102.      /**
  103.      * @Route("/paymentMollie/{id}", name="app_mollie_payment")
  104.      */
  105.     public function mollieApi(CallApiServices $callApiServicesRequest $request$id)
  106.     {
  107.         
  108.         $client $this->getUser();
  109.         $serviceId $this->getParameter('app.serviceId');
  110.         $accountId $this->getParameter('app.accountId');
  111.         $http_host $request->server->get('HTTP_HOST');
  112.     
  113.         $tarifsPlateforme $callApiServices->tarifsPlateforme($serviceId);
  114.         $montant $tarifsPlateforme[$id]['prix'];
  115.         $amount number_format($montant2'.''');
  116.         $orderId 'REF-' $client->getClientId() . '_' time();
  117.         $retour "https://" $http_host "/userOperation";
  118.         $webhooks "https://" $http_host "/mollieWebhook";
  119.       
  120.         $config $callApiServices->configuratationPlateforme($accountId$serviceId);
  121.         $apikey $config['paymentInfos']['mollie']['apiKey'];
  122.         
  123.         $profileArray = [
  124.             'firstName' => $client->getFirstName(),
  125.             'lastName' => $client->getLastName(),
  126.             'emailId' => $client->getEmail(),
  127.             'mobileNo' => $client->getPhoneNumber(),
  128.             'IP' => $client->getAddressIp()
  129.         ];
  130.       
  131.         $customProfile json_encode($profileArray);
  132.         $mollie = new \Mollie\Api\MollieApiClient();
  133.         $mollie->setApiKey($apikey);
  134.     
  135.         try {
  136.             $payment $mollie->payments->create([
  137.                 "amount" => [
  138.                     "currency" => "EUR",
  139.                     "value" => "$amount"
  140.                 ],
  141.                 "description" => "Order #12345",
  142.                 "description" => "Achat d'unitées sur le site " $http_host,
  143.                 "metadata" => ["order_id" => $orderId"client_id" => $client->getClientId(), "customProfile" => $customProfile],
  144.                 "redirectUrl" => $retour,
  145.                 "webhookUrl"  => $webhooks
  146.             ]);
  147.           
  148.             header("Location: " $payment->getCheckoutUrl(), true303);
  149.             
  150.             die;
  151.             
  152.         } catch (\Mollie\Api\Exceptions\ApiException $e) {
  153.             $error_message "API call failed: " \htmlspecialchars($e->getMessage());
  154.             $this->_helper->FlashMessenger(array('error' => 'Mollie: error validate' $error_message));
  155.             $this->_redirect('/client/crediter');
  156.             return;
  157.         }
  158.         return $payment;
  159.     }
  160.     /**
  161.      * @Route("/mollieWebhook", name="app_mollie", methods={"POST"})
  162.      */
  163.     public function mollieWebhook(CallApiServices $callApiServicesRequest $requestQuestionMailService $questionMailService,): Response
  164.     {
  165.     
  166.         $client $this->getUser();
  167.         $serviceId $this->getParameter('app.serviceId');
  168.         $accountId $this->getParameter('app.accountId');
  169.         $config $callApiServices->configuratationPlateforme($accountId$serviceId);
  170.         $httpMethod $request->getMethod();
  171.                 // retrieves JSON or POST variables respectively
  172.         if ($request->isMethod('POST') || ('json' === $request->getContentType())) {
  173.             $params $request->request->all();
  174.         } else {
  175.             // retrieves GET variables 
  176.             $params $request->attributes->get('_route_params');
  177.         }
  178.     
  179.         // 
  180.         $apikey $config['paymentInfos']['mollie']['apiKey'];
  181.      
  182.         if ($httpMethod=='POST') {
  183.             // Initialize the Mollie API library with your API key.
  184.             $mollie = new \Mollie\Api\MollieApiClient();
  185.            
  186.             //'test_CBCbFx5drdcj8FWc6MhfTGFBuAKP7g'
  187.             $mollie->setApiKey($apikey);
  188.           
  189.             // Retrieve the payment's current state.
  190.             $payment $mollie->payments->get($params['id']);
  191.            
  192.             $result_tab = [
  193.                 "serviceId" => $serviceId,
  194.                 "clientId" => $payment->metadata->client_id,
  195.                 "operation" => "payment",
  196.                 "statusCode" => $payment->status,
  197.                 "responseCode" => $payment->status,
  198.                 "paymentSystem" => 'MOLLIE',
  199.                 "paymentSystem_info" => "Recharge par CB",
  200.                 "transactionID" =>  $payment->id,
  201.                 "transactionDate" => strftime("%Y-%m-%d %H:%M:%S"strtotime($payment->createdAt)),
  202.                 "transactionAmount" => number_format($payment->amount->value2),
  203.                 "refClient" => $payment->metadata->order_id,
  204.                 "etat" => ""
  205.             ];
  206.             
  207.             // database_write($orderId, $payment->status);
  208.             if ($payment->isPaid() && !$payment->hasRefunds() && !$payment->hasChargebacks()) {
  209.                 $result_tab['etat'] = 'ok';
  210.                 $sendEmail true;
  211.                 $subject "Confirmation d'une transaction";
  212.                 $__REGLEMENT_STATUS__ ">>> REGLEMENT ACCEPTÉ <<<";
  213.                 
  214.             } elseif ($payment->isOpen()) {
  215.                 //$result_tab['etat'] = 'ouvert';
  216.                 
  217.             } elseif ($payment->isPending()) {
  218.                 $result_tab['etat'] = 'attente';
  219.                 
  220.             } elseif ($payment->isFailed()) {
  221.                 $result_tab['etat'] = 'ko';
  222.                 $sendEmail false;
  223.                 $subject "Echec d'une transaction";
  224.                 $__REGLEMENT_STATUS__ ">>> REGLEMENT REFUSÉ <<<";
  225.                 $stat_str .= " - "$alloCarte->Description;
  226.                 
  227.             } elseif ($payment->isExpired()) {
  228.                 $result_tab['etat'] = 'expired';
  229.                 
  230.             } elseif ($payment->isCanceled()) {
  231.                 //$result_tab['etat'] = 'annulé';
  232.                 
  233.             }
  234.             
  235.             // Le flux a été traité
  236.             // Le marchand peut ici mettre à jour sa base de données de commandes et effectuer d'autres traitements.
  237.             //
  238.     
  239.             // debug('getStatus :'. $stat_str. ' - etat:'. $result_tab['etat'] );
  240.     
  241.             // // enregistrement data base
  242.             // $dg_result= str_replace(array("\r\n", "\n", "\r"), '', print_r($result_tab, 1) );
  243.             // debug('PARAMS :'. $dg_result);
  244.                 
  245.             //On vérifie la présence et la validité de tous les paramètres obligatoires
  246.             if ( $result_tab['clientId'] && $result_tab['transactionID'] &&
  247.                      $result_tab['transactionAmount'] && $result_tab['transactionDate'] && ($result_tab['etat'] != "")  ) 
  248.             {
  249.             
  250.               
  251.                     // process transaction
  252.                 $ret $callApiServices->cbTransaction($result_tab);
  253.                 $this->logger->debug("tableau : ".print_r($result_tab,1));
  254.                 $this->logger->debug("transaction CB retour: ".print_r($ret,1));
  255.              
  256.                 if ($ret['sendEmail']==0){
  257.                     $sendEmail false;
  258.                 }elseif ($sendEmail == true){
  259.                     $questionMailService->sendMollieEmail($client$callApiServices$result_tab);
  260.                 } 
  261.     
  262.             } else {
  263.                 // debug('Params manquants ou invalides');
  264.             }
  265.         }
  266.         header("HTTP/1.0 200 OK");
  267.         die;
  268.     }
  269.    
  270. }