src/Controller/OrderController.php line 35

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Service\Api;
  4. use App\Twig\AppExtension;
  5. use Psr\Log\LoggerInterface;
  6. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  7. use Symfony\Component\HttpFoundation\JsonResponse;
  8. use Symfony\Component\HttpFoundation\Request;
  9. use Symfony\Component\Routing\Annotation\Route;
  10. use Symfony\Component\HttpClient\HttpClient;
  11. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  12. class OrderController extends AbstractController
  13. {
  14.     private $appExtension;
  15.     private $apiService;
  16.     private $logger;
  17.     public function __construct(AppExtension $appExtensionApi $apiServiceLoggerInterface $logger)
  18.     {
  19.         $this->appExtension $appExtension;
  20.         $this->apiService $apiService;
  21.         $this->logger $logger;
  22.     }
  23.     /*******************************************************************************************
  24.      * ORDER ROUTES
  25.      *******************************************************************************************/
  26.     /**
  27.      * @Route("/services/{Service}/{SubService}/{IDSN}/{IDGService}/order/{IDService}", name="order_sub_service")
  28.      */
  29.     public function index(Api $apiService$IDSN$IDGService$IDService)
  30.     {
  31.         $data['services'] = $apiService->getAllServices();
  32.         $data['current_service'] = null;
  33.         $data['current_sub_service'] = null;
  34.         $data['current_offer'] = null;
  35.         $data["icons"] = $apiService->getServicesIcons();
  36.         // Get the current service
  37.         foreach ($data['services'] as $key => $service) {
  38.             if ($service['IDSN'] == $IDSN) {
  39.                 $data['current_service'] = $service;
  40.             }
  41.         }
  42.         // Check if the current service does not exists
  43.         if (!$data['current_service']) {
  44.             return $this->render('errors/notFoundService.html.twig'$data);
  45.         }
  46.         // Get the current sub service
  47.         foreach ($data['current_service']['subs'] as $key => $subservice) {
  48.             if ($subservice['IDGService'] == $IDGService) {
  49.                 /* ************************************************************************************
  50.                  TODO:: Demander a Adil de modifier le Process type pour les subservices instagram reels
  51.                  Une fois c'est fait supprimer cette condition
  52.                 ***************************************************************************************/
  53.                 if ($subservice["IDGService"] ==  "ig9" || $subservice["IDGService"] ==  "ig10") {
  54.                     $subservice['ProcessType'] = 'ig_reels';
  55.                 }
  56.                 $data['current_sub_service'] = $subservice;
  57.             }
  58.         }
  59.         // Get the current offer
  60.         foreach ($data['current_sub_service']["offers"] as $key => $offer) {
  61.             if ($offer['IDService'] == $IDService) {
  62.                 $data['current_offer'] = $offer;
  63.             }
  64.         }
  65.         return $this->render('order/order.html.twig'$data);
  66.     }
  67.     /**
  68.      * @Route("/order/add", name="add_order", methods={"POST"})
  69.      */
  70.     public function addOrder(Request $requestUrlGeneratorInterface $urlGenerator)
  71.     {
  72.         // Get the raw JSON data from the request
  73.         $jsonData json_decode($request->getContent(), true);
  74.         $this->logger->info("============================== START addOrder ({$request->getContent()}) ==============================");
  75.         $orderApiUrl $this->getParameter('app.orderApiUrl');
  76.         $orderApiAddPrefix $this->getParameter('app.orderApiAddPrefix');
  77.         $orderApiCheckoutUrlPrefix $this->getParameter('app.orderApiCheckoutUrlPrefix');
  78.         $params[] = 'token=' $this->getParameter('app.orderApiToken');
  79.         $params[] = 'email=' $jsonData['email'];
  80.         $params[] = 'idservice=' $jsonData['IDService'];
  81.         $params[] = 'lang=' $jsonData['lang'];
  82.         $params[] = 'idcountry=' $this->appExtension->getCountry();
  83.         $params[] = 'currency=' $this->appExtension->getOrderCurrency();
  84.         $params[] = 'ip=' $this->appExtension->getIp();
  85.         // Optionnal params
  86.         $params[] = 'username=' . ($jsonData['username'] ?? "");
  87.         $params[] = 'url=' implode("\n"$jsonData['links'] ?? []) ?? "";
  88.         $params[] = 'checkoutlink=' $this->getParameter('app.orderCheckoutUrl');
  89.         // Custom comments data
  90.         if (isset($jsonData['customComments']) && is_array($jsonData['customComments']) && count($jsonData['customComments']) > 0) {
  91.             $arrComments = [];
  92.             foreach($jsonData['customComments'] as $key => $comment) {
  93.                 $arrComments[] = $comment['text'];
  94.             }
  95.             $params[] = 'customcomments=' implode("\n"$arrComments ?? []) ?? "";
  96.         } else {
  97.             $params[] = 'customcomments=';
  98.         }
  99.         // Create an instance of the HttpClient
  100.         $client HttpClient::create();
  101.         // Compose api url to create new order
  102.         $apiUrl $orderApiUrl '/' $orderApiAddPrefix '?' implode("&"$params);
  103.         // Send a GET request to the API URL
  104.         $response $client->request('GET'$apiUrl);
  105.         $this->logger->info('Api order PARAMS : ', [$params]);
  106.         $this->logger->info('Api order URL : ', [$apiUrl]);
  107.         $this->logger->info('Api order Response : ', [$response->getContent()]);
  108.         
  109.         // Get the content of the response
  110.         $orderId substr($response->getContent(), 1, -1) ;
  111.         $this->logger->info('Generated order id : ', [$orderId]);
  112.         $params = [];
  113.         $params[] = 'token=' $this->getParameter('app.orderApiToken');
  114.         $params[] = 'orderid=' $orderId;
  115.         // Compose api payment url
  116.         $apiPaymentUrl $orderApiUrl '/' $orderApiCheckoutUrlPrefix  '?' implode("&"$params);
  117.         // Send a GET request to the API URL
  118.         $response $client->request('GET'$apiPaymentUrl);
  119.         // Get the content of the response
  120.         $orderUrl substr($response->getContent(), 1, -1);
  121.         $this->logger->info('Api payment PARAMS : ', [$params]);
  122.         $this->logger->info('Api payment URL : ', [$apiPaymentUrl]);
  123.         $this->logger->info('Api payment Response : ', [$response->getContent()]);
  124.         // Compose result 
  125.         $result = ["redirect_url" => $orderUrl];
  126.         return new JsonResponse($result);
  127.     }
  128.     /**
  129.      * @Route("/order/relaunch/{order}", name="order_relaunch")
  130.      */
  131.     public function relaunch(Api $apiService$order)
  132.     {
  133.         $content $apiService->relaunchOrder($order);
  134.         if(strtolower(str_replace("\"",'',strtolower($content)))=='error'){
  135.             return $this->render('errors/errorRelaunch.html.twig');
  136.         }
  137.         else{
  138.             return $this->render('order/reluanch.html.twig');
  139.         }
  140.     }
  141.     function printr($data) {
  142.         echo  "<pre>" print_r($data,true) . "</pre>";
  143.     }
  144.     /**
  145.      * @Route("/order/success/{order}", name="order_succeeded")
  146.      */
  147.     public function success(Api $apiService$order)
  148.     {
  149.         $data['services'] = $apiService->getAllServices();
  150.         $data["icons"] = $apiService->getServicesIcons();
  151.         $data["order"] = $apiService->getOrderDetails($order);
  152.         $offers = [];
  153.         $services = [];
  154.         foreach ($data['services'] as $i => $service) {
  155.             foreach ($service['subs'] as $j => $sub) {
  156.                 $services[$sub['IDGService']] = $sub;
  157.                 $services[$sub['IDGService']]['service'] = $service;
  158.                 foreach ($sub['offers'] as $k => $offer) {
  159.                     $offers[$offer['IDService']] = $offer;
  160.                     $offers[$offer['IDService']]['sub'] = $sub;
  161.                     $offers[$offer['IDService']]['sub']['service'] = $service;
  162.                     if ($offer['IDService'] == $data["order"]['idservice']) {
  163.                         $data["order"]['offer'] = $offers[$offer['IDService']];
  164.                     }
  165.                 }
  166.             }
  167.         }
  168.         $data['related_services'] = [];
  169.         if ($data['order']['offer']['sub']['RelatedServiceID1'] != "" && isset($services[$data['order']['offer']['sub']['RelatedServiceID1']])) {
  170.             $data['related_services'][] = $services[$data['order']['offer']['sub']['RelatedServiceID1']];
  171.         }
  172.         if ($data['order']['offer']['sub']['RelatedServiceID2'] != "" && isset($services[$data['order']['offer']['sub']['RelatedServiceID2']])) {
  173.             $data['related_services'][] = $services[$data['order']['offer']['sub']['RelatedServiceID2']];
  174.         }
  175.         if ($data['order']['offer']['sub']['RelatedServiceID3'] != "" && isset($services[$data['order']['offer']['sub']['RelatedServiceID3']])) {
  176.             $data['related_services'][] = $services[$data['order']['offer']['sub']['RelatedServiceID3']];
  177.         }
  178.         $data['order']['id'] = $order;
  179.         $data['order']['arrUrls'] = explode('_'$data["order"]['url']);
  180.         $this->setFacebookPixel($data['order']['offer']['Price'],$data['order']['email']);
  181.         return $this->render('order/success.html.twig'$data);
  182.     }
  183.     public function getCountry(){
  184.         return $_SERVER["HTTP_CF_IPCOUNTRY"];
  185.     }
  186.     function setFacebookPixel($value,$email){
  187.         $accessToken 'EAAIZAHDJ6RdsBO0cS27GKb6sMtmMJqgSZA80KIdBHTcfkYO2irpco10MP7jvNE9QZBbVwSZCUQluJJiq3ZAS28el7f689NdcPQiZBY2Y8c5PRSo01r96DzOowyjnavTBepIRgdZAZB0s6GRImgY7X7TGNFGytoZAbhdVKMB3ODyA6BServwZC9FJHZCJT8VAgZAlOQfZCPAZDZD';
  188.         $pixelId '741206834880599';
  189.         // User data
  190.         $userData = [
  191.             'em' => hash('sha256'$email),
  192.             'country' => hash('sha256'$this->getCountry()),
  193.             'client_user_agent' => hash('sha256',$_SERVER['HTTP_USER_AGENT']),
  194.             'client_ip_address' =>$_SERVER['HTTP_CF_CONNECTING_IP']
  195.         ];
  196.         // Event data
  197.         $eventData = [
  198.             'event_name' => 'Purchase',
  199.             'event_time' => time(),
  200.             'action_source' => 'website',
  201.             'event_source_url' => 'https://wizzsocial.com/order/success',
  202.             'user_data' => $userData,
  203.             'custom_data' => [
  204.                 'currency' => 'USD',
  205.                 'value' => $value  // Set the value here directly
  206.             ]
  207.         ];
  208.         // Conversions API endpoint
  209.         $url "https://graph.facebook.com/v13.0/{$pixelId}/events?access_token={$accessToken}";
  210.         // Prepare data for JSON
  211.         $data = [
  212.             'data' => [$eventData]//,
  213.             //'test_event_code' => 'TEST62299' // Optional, for testing events
  214.         ];
  215.         // Initialize cURL
  216.         $ch curl_init();
  217.         curl_setopt($chCURLOPT_URL$url);
  218.         curl_setopt($chCURLOPT_POSTtrue);
  219.         curl_setopt($chCURLOPT_HTTPHEADER, ['Content-Type: application/json']);
  220.         curl_setopt($chCURLOPT_POSTFIELDSjson_encode($data));
  221.         curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  222.         // Execute and fetch the response
  223.         $response curl_exec($ch);
  224.         // Check for errors
  225.         if (curl_errno($ch)) {
  226.             //echo 'Error: ' . curl_error($ch);
  227.         } else {
  228.             //echo 'Event sent successfully: ' . $response;
  229.         }
  230.         // Close cURL
  231.         curl_close($ch);
  232.     }
  233.     /**
  234.      * @Route("/order/failed/{order}", name="order_failed")
  235.      */
  236.     public function failure(Api $apiService$order)
  237.     {
  238.         $data['services'] = $apiService->getAllServices();
  239.         $data["icons"] = $apiService->getServicesIcons();
  240.         return $this->render('order/failed.html.twig'$data);
  241.     }
  242.     /**
  243.      * @Route("/order/checkout/{order}", name="order_checkout")
  244.      */
  245.     public function checkout(Api $apiService$order)
  246.     {
  247.         $data['services'] = $apiService->getAllServices();
  248.         $data["icons"] = $apiService->getServicesIcons();
  249.         $data["order"] = $apiService->getOrderDetails($order);
  250.         $offers = [];
  251.         $services = [];
  252.         foreach ($data['services'] as $i => $service) {
  253.             foreach ($service['subs'] as $j => $sub) {
  254.                 $services[$sub['IDGService']] = $sub;
  255.                 $services[$sub['IDGService']]['service'] = $service;
  256.                 foreach ($sub['offers'] as $k => $offer) {
  257.                     $offers[$offer['IDService']] = $offer;
  258.                     $offers[$offer['IDService']]['sub'] = $sub;
  259.                     $offers[$offer['IDService']]['sub']['service'] = $service;
  260.                     if ($offer['IDService'] == $data["order"]['idservice']) {
  261.                         $data["order"]['offer'] = $offers[$offer['IDService']];
  262.                     }
  263.                 }
  264.             }
  265.         }
  266.         $data['related_services'] = [];
  267.         if ($data['order']['offer']['sub']['RelatedServiceID1'] != "" && isset($services[$data['order']['offer']['sub']['RelatedServiceID1']])) {
  268.             $data['related_services'][] = $services[$data['order']['offer']['sub']['RelatedServiceID1']];
  269.         }
  270.         if ($data['order']['offer']['sub']['RelatedServiceID2'] != "" && isset($services[$data['order']['offer']['sub']['RelatedServiceID2']])) {
  271.             $data['related_services'][] = $services[$data['order']['offer']['sub']['RelatedServiceID2']];
  272.         }
  273.         if ($data['order']['offer']['sub']['RelatedServiceID3'] != "" && isset($services[$data['order']['offer']['sub']['RelatedServiceID3']])) {
  274.             $data['related_services'][] = $services[$data['order']['offer']['sub']['RelatedServiceID3']];
  275.         }
  276.         $data['order']['id'] = $order;
  277.         $orderApiUrl $this->getParameter('app.orderApiUrl');
  278.         $orderApiCheckoutUrlPrefix $this->getParameter('app.orderApiCheckoutUrlPrefix');
  279.         $params = [];
  280.         $params[] = 'token=' $this->getParameter('app.orderApiToken');
  281.         $params[] = 'orderid=' $data['order']['id'];
  282.         // Compose api payment url
  283.         $apiPaymentUrl $orderApiUrl '/' $orderApiCheckoutUrlPrefix  '?' implode("&"$params);
  284.         
  285.         // Create an instance of the HttpClient
  286.         $client HttpClient::create();
  287.         // Send a GET request to the API URL
  288.         $response $client->request('GET'$apiPaymentUrl);
  289.         // Get the content of the response
  290.         $orderUrl substr($response->getContent(), 1, -1);
  291.         
  292.         $data['order']['paymentUrl'] = $orderUrl;
  293.         $data['order']['arrUrls'] = explode('_'$data["order"]['url']);
  294.         return $this->render('order/checkout.html.twig'$data);
  295.     }
  296.     /*******************************************************************************************
  297.      * INSTAGRAM ROUTES
  298.      *******************************************************************************************/
  299.     /**
  300.      * @Route("/instagram/load-posts", name="load_instagram_posts")
  301.      */
  302.     public function loadInstagramPosts(Request $request): JsonResponse
  303.     {
  304.         // Get instagram infos profile
  305.         $return['profile'] = $this->apiService->executeApiUrls("instagram""infosprofil"$request->query->get("username"),null);
  306.         // Check if the returned profile has media_count property
  307.         if (isset($return['profile']['media_count'])) {
  308.                 // Get instagram posts
  309.                 $return['posts'] = $this->apiService->executeApiUrls("instagram""posts"$request->query->get("username"),$request->query->get("token"));
  310.                 return new JsonResponse($return);
  311.         } else {
  312.             // Return invalid instagram username
  313.             return new JsonResponse(["message" => "Instagram username not found. Please try an existing one."], JsonResponse::HTTP_BAD_REQUEST);
  314.         }
  315.     }
  316. //    /**
  317. //     * @Route("/instagram/load-posts", name="load_instagram_posts")
  318. //     */
  319. //    public function loadInstagramPosts(Request $request): JsonResponse
  320. //    {
  321. //        // Get instagram infos profile
  322. //        $return['profile'] = $this->apiService->executeApiUrls("instagram", "infosprofil", $request->query->get("username"));
  323. //
  324. //        // Check if the returned profile has media_count property
  325. //        if (isset($return['profile']['media_count'])) {
  326. //
  327. //            // Check if returned profile media_count property is greater that 0 (means there is posts for the specified account)
  328. //            if ($return['profile']['media_count'] > 0) {
  329. //
  330. //                // Get instagram posts
  331. //                $return['posts'] = $this->apiService->executeApiUrls("instagram", "posts", $request->query->get("username"));
  332. //
  333. //                if (count($return['posts']) == 0) {
  334. //
  335. //                    //  Return account has no post error
  336. //                    return new JsonResponse(["message" => "No posts found. Please make sur your instagram account contains posts and is not private"], JsonResponse::HTTP_BAD_REQUEST);
  337. //                }
  338. //            } else {
  339. //
  340. //                //  Return account has no post error
  341. //                return new JsonResponse(["message" => "No posts found. Please make sur your instagram account contains posts and is not private"], JsonResponse::HTTP_BAD_REQUEST);
  342. //            }
  343. //        } else {
  344. //
  345. //            // Return invalid instagram username
  346. //            return new JsonResponse(["message" => "Instagram username not found. Please try an existing one."], JsonResponse::HTTP_BAD_REQUEST);
  347. //        }
  348. //
  349. //        return new JsonResponse($return);
  350. //    }
  351.     /**
  352.      * @Route("/instagram/load-profile", name="load_instagram_profile")
  353.      */
  354.     public function loadInstagramProfile(Request $request): JsonResponse
  355.     {
  356.         // Get instagram infos profile
  357.         $return['profile'] = $this->apiService->executeApiUrls("instagram""infosprofil"$request->query->get("username"),null);
  358.         return new JsonResponse($return);
  359.     }
  360.     /**
  361.      * @Route("/instagram/load-reels", name="load_instagram_reel")
  362.      */
  363.     public function loadInstagramReels(Request $request)
  364.     {
  365.         // Get instagram infos profile
  366.         $return['profile'] = $this->apiService->executeApiUrls("instagram""infosprofil"$request->query->get("username"),$request->query->get("token"));
  367.         // Check if the returned profile has media_count property
  368.         if (isset($return['profile']['media_count'])) {
  369.             // Get instagram posts
  370.             $return['posts'] = $this->apiService->executeApiUrls("instagram""reels"$request->query->get("username"),$request->query->get("token"));
  371.             return new JsonResponse($return);
  372.         } else {
  373.             // Return invalid instagram username
  374.             return new JsonResponse(["message" => "Instagram username not found. Please try an existing one."], JsonResponse::HTTP_BAD_REQUEST);
  375.         }
  376.     }
  377. //    /**
  378. //     * @Route("/instagram/load-reels", name="load_instagram_reel")
  379. //     */
  380. //    public function loadInstagramReels(Request $request)
  381. //    {
  382. //        // Get instagram infos profile
  383. //        $return['profile'] = $this->apiService->executeApiUrls("instagram", "infosprofil", $request->query->get("username"));
  384. //
  385. //        // Check if the returned profile has media_count property
  386. //        if (isset($return['profile']['media_count'])) {
  387. //
  388. //            // Check if returned profile media_count property is greater that 0 (means there is posts for the specified account)
  389. //            if ($return['profile']['media_count'] > 0) {
  390. //
  391. //                // Get instagram posts
  392. //                $return['posts'] = $this->apiService->executeApiUrls("instagram", "reels", $request->query->get("username"));
  393. //
  394. //                if (count($return['posts']) == 0) {
  395. //                    //  Return account has no post error
  396. //                    return new JsonResponse(["message" => "No reels found. Please make sur your instagram account contains reels and is not private"], JsonResponse::HTTP_BAD_REQUEST);
  397. //                }
  398. //            } else {
  399. //
  400. //                //  Return account has no post error
  401. //                return new JsonResponse(["message" => "No posts found. Please make sur your instagram account contains posts and is not private"], JsonResponse::HTTP_BAD_REQUEST);
  402. //            }
  403. //        } else {
  404. //
  405. //            // Return invalid instagram username
  406. //            return new JsonResponse(["message" => "Instagram username not found. Please try an existing one."], JsonResponse::HTTP_BAD_REQUEST);
  407. //        }
  408. //
  409. //        return new JsonResponse($return);
  410. //    }
  411.     /*******************************************************************************************
  412.      * TIKTOK ROUTES
  413.      *******************************************************************************************/
  414.     /**
  415.      * @Route("/tiktok/load-posts", name="load_tiktok_posts")
  416.      */
  417.     public function loadTikTokPosts(Request $request)
  418.     {
  419.         // Get tiktok infos profile
  420.         $return['profile'] = $this->apiService->executeApiUrls("tiktok""infosprofil"$request->query->get("username"));
  421.         // Check if the returned profile has videoCount property
  422.         if (isset($return['profile']['videoCount'])) {
  423.             // Check if returned profile videoCount property is greater that 0 (means there is posts for the specified account)
  424.             if ($return['profile']['videoCount'] > 0) {
  425.                 // Get tiktok posts
  426.                 $return['posts'] = $this->apiService->executeApiUrls("tiktok""posts"$request->query->get("username"));
  427.                 $return['posts'] = $return['posts']['media'];
  428.                 if (count($return['posts']) == 0) {
  429.                     
  430.                     //  Return account has no post error
  431.                     return new JsonResponse(["message" => "No posts found. Please make sur your tiktok account contains posts and is not private"], JsonResponse::HTTP_BAD_REQUEST);
  432.                 }
  433.             } else {
  434.                 //  Return account has no post error
  435.                 return new JsonResponse(["message" => "No posts found. Please make sur your tiktok account contains posts and is not private"], JsonResponse::HTTP_BAD_REQUEST);
  436.             }
  437.         } else {
  438.             // Return invalid tiktok username
  439.             return new JsonResponse(["message" => "Tiktok username not found. Please try an existing one."], JsonResponse::HTTP_BAD_REQUEST);
  440.         }
  441.         return new JsonResponse($return);
  442.     }
  443.     /**
  444.      * @Route("/tiktok/load-profile", name="load_tiktok_profile")
  445.      */
  446.     public function loadTikTokProfile(Request $request)
  447.     {
  448.         // Get instagram infos profile
  449.         $return['profile'] = $this->apiService->executeApiUrls("tiktok""infosprofil"$request->query->get("username"));
  450.         // Check if the returned profile doesn't have videoCount property
  451.         if (!isset($return['profile']['videoCount'])) {
  452.             // Return invalid instagram username
  453.             return new JsonResponse(["message" => "TikTok username not found. Please try an existing one."], JsonResponse::HTTP_BAD_REQUEST);
  454.         }
  455.         return new JsonResponse($return);
  456.     }
  457. }