src/Controller/TarifsController.php line 35

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Client;
  4. use App\Entity\Config;
  5. use Prophecy\Call\Call;
  6. use App\Services\CallApiTab;
  7. use Psr\Log\LoggerInterface;
  8. use App\Services\webhooksMollie;
  9. use App\Services\CallApiServices;
  10. use PhpParser\Node\Expr\Instanceof_;
  11. use App\Services\QuestionMailService;
  12. use DateTime;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\HttpFoundation\Response;
  15. use Symfony\Component\Routing\Annotation\Route;
  16. use Symfony\Component\HttpFoundation\JsonResponse;
  17. use Symfony\Component\Serializer\SerializerInterface;
  18. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  19. use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
  20. use function Symfony\Component\DependencyInjection\Loader\Configurator\service;
  21. class TarifsController extends AbstractController
  22. {
  23.     private $logger;
  24.     private $paypalClientID;
  25.     private $paypalSecret;
  26.     public function __construct(CallApiTab $callApiTabLoggerInterface $logger$paypalClientID$paypalSecret)
  27.     {
  28.         $this->logger $logger;
  29.         $this->endpoint $callApiTab->endpoint();
  30.         $this->paypalClientID $paypalClientID;
  31.         $this->paypalSecret $paypalSecret;
  32.     }
  33.     /**
  34.      * @Route("/tarifs", name="app_tarifs")
  35.      */
  36.     public function index(CallApiServices $callApiServicesRequest $request): Response
  37.     {
  38.         $user $this->getUser();
  39.         $serviceId $this->getParameter('app.serviceId');
  40.         if ($user) {
  41.             $client $callApiServices->clientProfileCheck($serviceId$user->getClientId());
  42.             $user->setSolde($client['solde']);
  43.         }
  44.         $serviceId $this->getParameter('app.serviceId');
  45.         $accountId $this->getParameter('app.accountId');
  46.         $session $request->getSession();
  47.         $config $callApiServices->configuratationPlateforme($accountId$serviceId);
  48.         $configPlateforme = new Config();
  49.         $configPlateforme->setKindOfCredit($config['kindOfCredit']);
  50.         $configPlateforme->setItemsPerPage($config['itemsPerPage']);
  51.         $configPlateforme->setItemsPerRow($config['itemsPerRow']);
  52.         $configPlateforme->setWelcomeCredit($config['welcomeCredit']);
  53.         $configPlateforme->setRecaptchaTab($config['recaptchaTab']);
  54.         $configPlateforme->setPaymentInfos($config['paymentInfos']);
  55.         $configPlateforme->setMail($config['mail']);
  56.         $configPlateforme->setServiceId($serviceId);
  57.         $configPlateforme->setAccountId($accountId);
  58.         $configPlateforme->setMarchand($config['marchand']);
  59.         $payementInfo $configPlateforme->getPaymentInfos();
  60.         if (isset($payementInfo['oonex']) && ($payementInfo['oonex']['activer'] == 1)) {
  61.             $activeOonex true;
  62.         } else {
  63.             $activeOonex false;
  64.         }
  65.         if (isset($payementInfo['mollie']) && ($payementInfo['mollie']['activer'] == 1)) {
  66.             $activeMollie true;
  67.         } else {
  68.             $activeMollie false;
  69.         }
  70.         if (isset($payementInfo['paypal']) && ($payementInfo['paypal']['activer'] == 1)) {
  71.             $activePaypal true;
  72.         } else {
  73.             $activePaypal false;
  74.         }
  75.         if (isset($payementInfo['mobiyo']) && ($payementInfo['mobiyo']['activer'] == 1)) {
  76.             $activeMobiyo true;
  77.         } else {
  78.             $activeMobiyo false;
  79.         }
  80.         $session->set('activeOonex'$activeOonex);
  81.         $session->set('activeMollie'$activeMollie);
  82.         $session->set('activePaypal'$activePaypal);
  83.         $session->set('activeMobiyo'$activeMobiyo);
  84.         $tarifsPlateforme $callApiServices->tarifsPlateforme($serviceId);
  85.         return $this->render('tarifs/index.html.twig', [
  86.             'tarifsPlateforme' => $tarifsPlateforme,
  87.             'activeOonex' => $activeOonex,
  88.             'activeMollie' => $activeMollie,
  89.             'activePaypal' => $activePaypal,
  90.             'activeMobiyo' => $activeMobiyo,
  91.         ]);
  92.     }
  93.     /**
  94.      * @Route("/payment/{id}", name="app_payment")
  95.      */
  96.     public function payment(CallApiServices $callApiServices$idRequest $request): Response
  97.     {
  98.         $user $this->getUser();
  99.         if ($user instanceof Client) {
  100.             $serviceId $user->getServiceId();
  101.             $code $user->getCode();
  102.             $email $user->getEmail();
  103.             $clientId $user->getClientId();
  104.             $firstName $user->getFirstName();
  105.             $lastName $user->getLastName();
  106.         }
  107.         $tarifsPlateforme $callApiServices->tarifsPlateforme($serviceId);
  108.         $prix $tarifsPlateforme[$id]['prix'];
  109.         $data = array('act' => 'emspay''mnt' => number_format($prix2), 'devise' => '978''ref' => 'REF_' $clientId '_' time());
  110.         $serviceId $this->getParameter('app.serviceId');
  111.         $accountId $this->getParameter('app.accountId');
  112.         $table = [
  113.             'amount' => $prix,
  114.             'reference' => $data['ref'],
  115.             'accountId' => $accountId,
  116.             'serviceId' =>  $serviceId,
  117.             'stamp' => time() + 60,
  118.             'idClient' => $clientId,
  119.             'code' => $code,
  120.             'customREF' => $data['ref']
  121.         ];
  122.         $customTable json_encode($table);
  123.         $table base64_encode($customTable);
  124.         $time = new \DateTime();
  125.         $time $time->format('d/m/Y');
  126.         $session $request->getSession();
  127.         $config $session->get('configPlateforme');
  128.         return $this->render('tarifs/payment.html.twig', [
  129.             'query' => $table,
  130.             'tarif' => $tarifsPlateforme[$id],
  131.             'config' => $config,
  132.         ]);
  133.     }
  134.     /**
  135.      * @Route("/achat", name="app_achat")
  136.      */
  137.     public function achat(CallApiServices $callApiServicesRequest $request): Response
  138.     {
  139.         return $this->redirectToRoute("app_tarifs");
  140.     }
  141.     /**
  142.      * @Route("/achat/{id}", name="app_parrain")
  143.      */
  144.     public function achatParrain(CallApiServices $callApiServices$idRequest $request): Response
  145.     {
  146.         $session $request->getSession();
  147.         $session->set('parrainId'$id);
  148.         return $this->redirectToRoute("app_tarifs");
  149.     }
  150.     /**
  151.      * @Route("/confirm-transaction/{id}", name="app_confirmTransaction")
  152.      */
  153.     public function confirmTransaction(CallApiServices $callApiServices$idRequest $request): Response
  154.     {
  155.         $user $this->getUser();
  156.         $serviceId $this->getParameter('app.serviceId');
  157.         if ($user) {
  158.             $clientId $user->getClientId();
  159.             $client $callApiServices->clientProfileCheck($serviceId$clientId);
  160.             if (isset($client['responseCode'])) {
  161.                 return $this->redirectToRoute('app_logout');
  162.             }
  163.             $user->setSolde($client['solde']);
  164.         }
  165.         $session $request->getSession();
  166.         $config $session->get('configPlateforme');
  167.         // $payementInfo = $config->getPaymentInfos();
  168.         $clientId $user->getClientId();
  169.         $paypalClientID $this->paypalClientID;
  170.         $paypalSecret $this->paypalSecret;
  171.         $activeOonex $session->get('activeOonex');
  172.         $activePaypal $session->get('activePaypal');
  173.         $activeMollie $session->get('activeMollie');
  174.         $activeMobiyo $session->get('activeMobiyo');
  175.         $serviceId $config->getServiceId();
  176.         $tarifsPlateforme $callApiServices->tarifsPlateforme($serviceId);
  177.         $session->set('tarif'$tarifsPlateforme[$id]);
  178.         return $this->render('tarifs/confirmTransaction.html.twig', [
  179.             'tarifsPlateforme' => $tarifsPlateforme,
  180.             'tarif' => $tarifsPlateforme[$id],
  181.             'activeOonex' => $activeOonex,
  182.             'activeMollie' => $activeMollie,
  183.             'activePaypal' => $activePaypal,
  184.             'activeMobiyo' => $activeMobiyo,
  185.             'paypalClientID' => $paypalClientID,
  186.             'paypalSecret' => $paypalSecret,
  187.             'clientId' => $clientId,
  188.             'key' => $id,
  189.         ]);
  190.     }
  191.      /**
  192.      * @Route("/paymentMollie/{id}", name="app_mollie_payment")
  193.      */
  194.     public function mollieApi(CallApiServices $callApiServicesRequest $request$id)
  195.     {
  196.         
  197.         $client $this->getUser();
  198.         $serviceId $this->getParameter('app.serviceId');
  199.         $accountId $this->getParameter('app.accountId');
  200.         $http_host $request->server->get('HTTP_HOST');
  201.         $config $callApiServices->configuratationPlateforme($accountId$serviceId);
  202.         $apikey $config['paymentInfos']['mollie']['apiKey'];
  203.      
  204.         $tarifsPlateforme $callApiServices->tarifsPlateforme($serviceId);
  205.         $montant $tarifsPlateforme[$id]['prix'];
  206.         /** @var Client $client */
  207.         $amount number_format($montant2'.''');
  208.         $orderId 'REF-' $client->getClientId() . '_' time();
  209.         $retour "https://" $http_host "/userOperation";
  210.         $webhooks "https://" $http_host "/mollieWebhook";
  211.        
  212.         $profileArray = [
  213.             'firstName' => $client->getFirstName(),
  214.             'lastName' => $client->getLastName(),
  215.             'emailId' => $client->getEmail(),
  216.             'mobileNo' => $client->getPhoneNumber(),
  217.             'IP' => $client->getAddressIp()
  218.         ];
  219.       
  220.         $customProfile json_encode($profileArray);
  221.         $mollie = new \Mollie\Api\MollieApiClient();
  222.         $mollie->setApiKey($apikey);
  223.     
  224.         try {
  225.             $payment $mollie->payments->create([
  226.                 "amount" => [
  227.                     "currency" => "EUR",
  228.                     "value" => "$amount"
  229.                 ],
  230.                 "description" => "Achat d'unitées sur le site " $http_host,
  231.                 "metadata" => ["order_id" => $orderId"client_id" => $client->getClientId(), "customProfile" => $customProfile],
  232.                 "redirectUrl" => $retour,
  233.                 "webhookUrl"  => $webhooks
  234.             ]);
  235.           
  236.             header("Location: " $payment->getCheckoutUrl(), true303);
  237.             
  238.             die;
  239.             
  240.         } catch (\Mollie\Api\Exceptions\ApiException $e) {
  241.             $error_message "API call failed: " \htmlspecialchars($e->getMessage());
  242.             $this->_helper->FlashMessenger(array('error' => 'Mollie: error validate' $error_message));
  243.             $this->_redirect('/client/crediter');
  244.             return;
  245.         }
  246.         return $payment;
  247.     }
  248.     /**
  249.      * @Route("/mollieWebhook", name="app_mollie", methods={"POST" })
  250.      */
  251.     public function mollieWebhook(CallApiServices $callApiServicesRequest $requestQuestionMailService $questionMailService,): Response
  252.     {
  253.         $sendEmail false;
  254.    
  255.         // cette fonction n'est pas appelée via le navigateur.
  256.         // donc la session précedente n'est plus valide
  257.         // il faut obtenir les infos via les parametre "metadata" de la transaction
  258.         // on ne peut pas utiliser le token obtenu par la connexion, donc il faut prendre le token figé (idem allo-carte)
  259.         // on utilisera donc ce token : ad2762c0071ab6fdbfe9b3591d3822a28ac1373181fa255b650db4561048
  260.         $httpMethod $request->getMethod();
  261.                 // retrieves JSON or POST variables respectively
  262.         if ($request->isMethod('POST') || ('json' === $request->getContentType())) {
  263.             $params $request->request->all();
  264.         } else {
  265.             // retrieves GET variables 
  266.             //$params = $request->attributes->get('_route_params');
  267.             $params $request->query->all();
  268.         }
  269.         $FixedToken "ad2762c0071ab6fdbfe9b3591d3822a28ac1373181fa255b650db4561048";
  270.         $session $request->getSession();
  271.         $session->set('apiToken'$FixedToken);
  272.         $serviceId $this->getParameter('app.serviceId');
  273.         $accountId $this->getParameter('app.accountId');
  274.      
  275.         $config $callApiServices->configuratationPlateforme($accountId$serviceId);
  276.         $apikey $config['paymentInfos']['mollie']['apiKey'];
  277.      
  278.         if (($httpMethod=='POST')||($httpMethod=='GET')) {
  279.             // Initialize the Mollie API library with your API key.
  280.             $mollie = new \Mollie\Api\MollieApiClient();
  281.            
  282.             //'test_CBCbFx5drdcj8FWc6MhfTGFBuAKP7g'
  283.             $mollie->setApiKey($apikey);
  284.           
  285.             // Retrieve the payment's current state.
  286.             $payment $mollie->payments->get($params['id']);
  287.             $dateTrans = new DateTime($payment->createdAt);
  288.             $result_tab = [
  289.                 "accountId" => $accountId,
  290.                 "serviceId" => $serviceId,
  291.                 "clientId" => $payment->metadata->client_id,
  292.                 "operation" => "payment",
  293.                 "statusCode" => $payment->status,
  294.                 "responseCode" => $payment->status,
  295.                 "paymentSystem" => 'MOLLIE',
  296.                 "paymentSystem_info" => "Recharge par CB",
  297.                 "transactionID" =>  $payment->id,
  298.                 "transactionDate" => $dateTrans->format("Y-m-d H:i:s"),
  299.                 "transactionAmount" => number_format($payment->amount->value2),
  300.                 "refClient" => $payment->metadata->order_id,
  301.                 "etat" => ""
  302.             ];
  303.                
  304.             // database_write($orderId, $payment->status);
  305.             if ($payment->isPaid() && !$payment->hasRefunds() && !$payment->hasChargebacks()) {
  306.                 $result_tab['etat'] = 'ok';
  307.                 $sendEmail true;
  308.                 $subject "Confirmation d'une transaction";
  309.                 $__REGLEMENT_STATUS__ ">>> REGLEMENT ACCEPTÉ <<<";
  310.                 
  311.             } elseif ($payment->isOpen()) {
  312.                 //$result_tab['etat'] = 'ouvert';
  313.                 
  314.             } elseif ($payment->isPending()) {
  315.                 $result_tab['etat'] = 'attente';
  316.                 
  317.             } elseif ($payment->isFailed()) {
  318.                 $result_tab['etat'] = 'ko';
  319.                 $sendEmail false;
  320.                 $subject "Echec d'une transaction";
  321.                 $__REGLEMENT_STATUS__ ">>> REGLEMENT REFUSÉ <<<";
  322.                 //$stat_str = " - ". $alloCarte->Description;
  323.                 
  324.             } elseif ($payment->isExpired()) {
  325.                 $result_tab['etat'] = 'expired';
  326.                 
  327.             } elseif ($payment->isCanceled()) {
  328.                 //$result_tab['etat'] = 'annulé';
  329.                 
  330.             }
  331.             
  332.             //On vérifie la présence et la validité de tous les paramètres obligatoires
  333.             if ( $result_tab['clientId'] && $result_tab['transactionID'] &&
  334.                      $result_tab['transactionAmount'] && $result_tab['transactionDate'] && ($result_tab['etat'] != "")  ) 
  335.             {
  336.                 
  337.                 $this->logger->debug("result_tab : "print_r($result_tab,1));
  338.                 
  339.                 // process transaction
  340.                 $ret $callApiServices->cbTransaction($result_tab);
  341.                 if (isset($ret['responseCode']) && ($ret['responseCode']!=200))  {
  342.                     $sendEmail false;
  343.                     $this->logger->debug("transaction CB retour, responseCode: "$ret['responseCode']. '- message:'$ret['message']);
  344.                 } else {
  345.                     $this->logger->debug("transaction CB retour: "print_r($ret,1));
  346.                 }
  347.                 if ($ret['sendEmail']==0){
  348.                     $sendEmail false;
  349.                 }
  350.     
  351.             } else {
  352.                 // debug('Params manquants ou invalides');
  353.             }
  354.             if ($sendEmail == true) {
  355.                 $result_tab['subject'] = $subject;
  356.                 $result_tab['baseURL'] = $this->getParameter('baseURL');
  357.                 /** @var Client $client */
  358.                 $clientArray $callApiServices->clientProfile($result_tab['serviceId'], $result_tab['clientId']);
  359.                 if (isset($clientArray['responseCode']) && ($clientArray['responseCode']!=200))  {
  360.                     $this->logger->debug("clientArray, responseCode: "$ret['responseCode']. '- message:'$ret['message']);
  361.                 } else {
  362.                     $questionMailService->sendMollieEmail($callApiServices$request$clientArray$result_tab);
  363.                 }
  364.             }
  365.         }
  366.         header("HTTP/1.0 200 OK");
  367.         die;
  368.     }
  369.     /**
  370.      * @Route("/api/paypal/", name="paypal_api")
  371.      */
  372.     public function paypalApi(CallApiServices $callApiServiceCallApiTab $callApiTabSerializerInterface $serializerRequest $request,): JsonResponse
  373.     {
  374.         $client $this->getUser();
  375.         $serviceId $this->getParameter('app.serviceId');
  376.         $accountId $this->getParameter('app.accountId');
  377.         $clientId $client->getClientId();
  378.         $apiToken $client->getApiToken();
  379.         $session $request->getSession();
  380.         $tarif $session->get('tarif');
  381.         $data \json_decode($request->getContent(), true); // On récupère les data postées et on les déserialize
  382.         if (empty($content $data)) {
  383.             throw new AccessDeniedHttpException('No data sent');
  384.         }
  385.     
  386.         $message $content;
  387.         if ($tarif['kindOfCredit'] == 0) {
  388.             $value $tarif['minutes'];
  389.         } else {
  390.             $value $content['purchase_units'][0]['amount']['value'];
  391.         }
  392.         $operationData = [
  393.             "accountId" => $accountId,
  394.             "serviceId" => $serviceId,
  395.             "clientId" => $clientId,
  396.             "description" => "Credit via Paypal",
  397.             "typeOperation" => "credit",
  398.             "montant" => $value
  399.         ];
  400.         $this->logger->debug('message=', array($message));
  401.         if ($content['status'] == 'COMPLETED') {
  402.             $this->logger->debug('operationData=', array($operationData));
  403.             $webOperatonEndPoint $this->endpoint['clientsWebOperationAjouter'];
  404.             $webOperatonTab $callApiTab->tab($apiToken$operationData);
  405.             $webOperaton $callApiService->postApi($webOperatonEndPoint$webOperatonTab);
  406.             $this->logger->debug('webOperaton=', array($webOperaton));
  407.         }
  408.         $jsonMessage $serializer->serialize($message'json', [
  409.             'groups' => ['message'// On serialize la réponse avant de la renvoyer
  410.         ]);
  411.         return new JsonResponse// Enfin, on retourne la réponse
  412.             $jsonMessage,
  413.             Response::HTTP_OK,
  414.             [],
  415.             true
  416.         );
  417.     }
  418.               /**
  419.      * @Route("/api/mobiyo/", name="mobiyo_api")
  420.      */
  421.     public function mobiyoApi(CallApiServices $callApiServicesCallApiTab $callApiTabSerializerInterface $serializerRequest $request,): JsonResponse
  422.     {
  423.         $client $this->getUser();
  424.         $serviceId $this->getParameter('app.serviceId');
  425.         $accountId $this->getParameter('app.accountId');
  426.         $clientId $client->getClientId();
  427.         $apiToken $client->getApiToken();
  428.         $session $request->getSession();
  429.         $tarif $session->get('tarif');
  430.         $config $callApiServices->configuratationPlateforme($accountId$serviceId);
  431.        
  432.         if (isset($config["paymentInfos"]["mobiyo"])){
  433.             $mobiyoActiver $config["paymentInfos"]["mobiyo"]["activer"];
  434.             if ($config["paymentInfos"]["mobiyo"]["envKey"] == "DEV"){
  435.                 $mobiyoEnvKey 'PROD';
  436.             }
  437.             $mobiyoApiKey $config["paymentInfos"]["mobiyo"]["apiKey"];
  438.             $mobiyoApiKeySecret $config["paymentInfos"]["mobiyo"]["apiKeySecret"];
  439.             $mobiyoIdSite $config["paymentInfos"]["mobiyo"]["idSite"];
  440.             $mobiyoIdProduit $config["paymentInfos"]["mobiyo"]["idProduit"];
  441.             $mobiyoUrlTransaction $config["paymentInfos"]["mobiyo"]["urlTransaction"];
  442.             $mobiyoUrlPayment $config["paymentInfos"]["mobiyo"]["urlPayment"];
  443.             $mobiyoUrlSuccess $config["paymentInfos"]["mobiyo"]["urlSuccess"];
  444.             $mobiyoUrlFail $config["paymentInfos"]["mobiyo"]["urlFail"];
  445.             $mobiyoUrlCancel $config["paymentInfos"]["mobiyo"]["urlCancel"];
  446.         }
  447.        
  448.         $amount $tarif['prix'];
  449.        
  450.         if ($mobiyoActiver) {
  451.                 
  452.                 $amount number_format($amount2'.''');
  453.                 if (isset($mobiyoUrlPayment)) {
  454.                     $table = [
  455.                         "amount" => $amount,
  456.                         "reference" => 'REF_'.$client->getClientId().'_'time(),
  457.                         "serviceId" => $serviceId,
  458.                         "accountId" => $accountId,
  459.                         "stamp" => time() + 2*60
  460.                         "idClient" => $clientId,
  461.                         "code" => $client->getCode(),
  462.                         "customREF" => 'REF_'.$client->getClientId().'_'time(),        
  463.                     ];
  464.                     
  465.                     $customTable json_encode($table);
  466.                     $QUERY base64_encode($customTable);
  467.                     $url_payment $mobiyoUrlPayment "?tr="$QUERY;
  468.                     
  469.                     header("Location: "$url_payment );
  470.                     die;
  471.                 
  472.             }
  473.         }   
  474.     }
  475. }