src/Controller/StoresController.php line 72

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Event\LoggerServiceEvent;
  4. use App\Event\Store\StoreEvent;
  5. use App\Service\LoggerHelper;
  6. use App\Service\TiendaNubeApi;
  7. use App\Service\Helper;
  8. use App\Service\DBManager;
  9. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  10. use Symfony\Component\HttpClient\Exception\RedirectionException;
  11. use Symfony\Component\HttpClient\Exception\ServerException;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  14. use Symfony\Component\HttpClient\Exception\ClientException;
  15. use Symfony\Component\HttpFoundation\Response;
  16. use Symfony\Component\HttpClient\HttpClient;
  17. use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
  18. /**
  19.  * Handles store management
  20.  */
  21. class StoresController extends AbstractController
  22. {
  23.     private $helper$dbm$TNApi;
  24.     /**
  25.      * @var string
  26.      */
  27.     private $tn_app_id;
  28.     /**
  29.      * @var string
  30.      */
  31.     private $tn_shipping_carrier_name;
  32.     /**
  33.      * @var LoggerHelper
  34.      */
  35.     private $loggerHelper;
  36.     /**
  37.      * @var EventDispatcherInterface
  38.      */
  39.     private $dispatcher;
  40.     /**
  41.      * @param Helper $helper
  42.      * @param DBManager $dbm
  43.      * @param TiendaNubeApi $TNApi
  44.      * @param string $tn_app_id
  45.      * @param string $tn_shipping_carrier_name
  46.      * @param LoggerHelper $loggerHelper
  47.      * @param EventDispatcherInterface $dispatcher
  48.      */
  49.     public function __construct(Helper $helperDBManager $dbmTiendaNubeApi $TNApistring $tn_app_idstring $tn_shipping_carrier_nameLoggerHelper $loggerHelperEventDispatcherInterface $dispatcher)
  50.     {
  51.         $this->helper $helper;
  52.         $this->dbm $dbm;
  53.         $this->TNApi $TNApi;
  54.         $this->tn_app_id $tn_app_id;
  55.         $this->tn_shipping_carrier_name $tn_shipping_carrier_name;
  56.         $this->loggerHelper $loggerHelper;
  57.         $this->dispatcher $dispatcher;
  58.     }
  59.     /**
  60.      * Route for /
  61.      *
  62.      * @return Response
  63.      */
  64.     public function index(): Response
  65.     {
  66.         $this->loggerHelper->saveMessage('Ingreso''Inicio''Registro de inicio'200);
  67.         return $this->helper->print_json([]);
  68.     }
  69.     /**
  70.      * Authorizes the APP inside TN and create all the requirements for the APP to work
  71.      *
  72.      * @param Request $req
  73.      * @return Response
  74.      */
  75.     public function auth(Request $req): Response
  76.     {
  77.         $res = [];
  78.         $code $req->query->get('code'false);
  79.         if (!$code) {
  80.             $req->getUri();
  81.             $event = new StoreEvent([['error' => 'No llegó code de identificación.'], '400']);
  82.             $event->setUrl($req->getUri());
  83.             $this->dispatcher->dispatch($eventStoreEvent::STORE_AUTH);
  84.             return $this->helper->render_message('Petición inválida. Por favor volvé a instalar la aplicación.');
  85.         }
  86.         try {
  87.             // 1. Auth
  88.             $res $this->TNApi->authenticate($code);
  89.             if (empty($res['access_token']) || empty($res['user_id'])) {
  90.                 $event = new StoreEvent([['error' => 'No se pudo obtener el access token. El code es inválido .'], '400']);
  91.                 $event->setUrl($req->getUri());
  92.                 $this->dispatcher->dispatch($eventStoreEvent::STORE_AUTH);
  93.                 return $this->helper->render_message(
  94.                     'No se pudo obtener el access token. Por favor vuelva a instalar la aplicación.'
  95.                 );
  96.             }
  97.             $this->dbm->update_access_token($res);
  98.             $store_id $res['user_id'];
  99.             $access_token $res['access_token'];
  100.         } catch (\Exception $e) {
  101.             $event = new StoreEvent([['error' => $e->getMessage()], $e->getCode()]);
  102.             $event->setUrl($req->getUri());
  103.             $this->dispatcher->dispatch($eventStoreEvent::STORE_EVENT);
  104.             return $this->helper->render_message($e->getMessage());
  105.         } catch (TransportExceptionInterface $e) {
  106.             $event = new StoreEvent([['error' => $e->getMessage()], $e->getCode()]);
  107.             $event->setUrl($req->getUri());
  108.             $this->dispatcher->dispatch($eventStoreEvent::STORE_EVENT);
  109.             return $this->helper->render_message($e->getMessage());
  110.         }
  111.         try {
  112.             // 2. Create shipping carrier
  113.             $shipping_carrier_id $this->TNApi->create_shipping_carrier($store_id);
  114.             $this->dbm->update_shipping_carrier_id($store_id$shipping_carrier_id);
  115.             // 3. Create Shipping carrier options
  116.             $options = array("standard"=>"Envío Normal""priority"=>"Envío Prioritario""express"=>"Envío Express");
  117.             foreach ($options as $code => $name) {
  118.                 $res $this->TNApi->create_shipping_carrier_options($store_id$shipping_carrier_id$code$name);
  119.             }
  120.             // 4. Create webhooks
  121.             $existing_webhooks $this->TNApi->get_existing_webhooks($store_id);
  122.             if (!$existing_webhooks['order_created'])
  123.                 $res $this->TNApi->create_order_created_webhook($store_id);
  124.             if (!$existing_webhooks['order_updated'])
  125.                 $res $this->TNApi->create_order_updated_webhook($store_id);
  126.             if (!$existing_webhooks['app_uninstalled'])
  127.                 $res $this->TNApi->create_app_uninstalled_webhook($store_id);
  128.             if (!$existing_webhooks['app_suspended'])
  129.                 $res $this->TNApi->create_app_suspended_webhook($store_id);
  130.             if (!$existing_webhooks['app_resumed'])
  131.                 $res $this->TNApi->create_app_resumed_webhook($store_id);
  132.             return $this->render_auth_form($store_id$access_token);
  133.         } catch (ClientException ServerException RedirectionException $e) {
  134.             $event = new StoreEvent([['error' => $e->getResponse()->getContent(false)], 400]);
  135.             $event->setUrl($req->getUri());
  136.             $this->dispatcher->dispatch($eventStoreEvent::STORE_EVENT);
  137.             return $this->helper->print_json(['error' => $e->getResponse()->getContent(false)], 400);
  138.         } catch (\Exception $e) {
  139.             $event = new LoggerServiceEvent([['error' => $e->getMessage()], 500]);
  140.             $event->setUrl($req->getUri());
  141.             $this->dispatcher->dispatch($eventStoreEvent::STORE_EVENT);
  142.             return $this->helper->render_message($e->getMessage());
  143.         } catch (TransportExceptionInterface $e) {
  144.             $event = new StoreEvent([['error' => $e->getMessage()], $e->getCode()]);
  145.             $event->setUrl($req->getUri());
  146.             $this->dispatcher->dispatch($eventStoreEvent::STORE_EVENT);
  147.             return $this->helper->render_message($e->getMessage());
  148.         }
  149.     }
  150.     /**
  151.      * Handles the uninstallation of the APP
  152.      *
  153.      * @param Request $req
  154.      * @return Response
  155.      */
  156.     public function uninstall_app(Request $req): Response
  157.     {
  158.         $webhook_content $req->getContent();
  159.         $hmac_header $req->headers->get('X-Linkedstore-HMAC-SHA256');
  160.         $data_received json_decode($webhook_contenttrue);
  161.         if (!$this->TNApi->verify_webhook($webhook_content$hmac_header)){
  162.             $this->procesaEvent(['error' => 'Couldn\'t verify webhook'], Response::HTTP_BAD_REQUEST$req->getUri());
  163.             return $this->helper->print_json(['error' => 'Couldn\'t verify webhook'], Response::HTTP_BAD_REQUEST);
  164.         }
  165.         if (!$data_received){
  166.             $this->procesaEvent(['error' => 'Invalid JSON received'], Response::HTTP_BAD_REQUEST$req->getUri());
  167.             return $this->helper->print_json(['error' => 'Invalid JSON received']);
  168.         }
  169.         if ((string)$data_received['id'] !== (string)$this->tn_app_id) {
  170.             $this->procesaEvent(['error' => 'App ID Invalid'], Response::HTTP_BAD_REQUEST$req->getUri());
  171.             return $this->helper->print_json(['error' => 'App ID Invalid']);
  172.         }
  173.         $store_id filter_var($data_received['store_id'], FILTER_SANITIZE_NUMBER_INT);
  174.         try {
  175.             $this->dbm->remove_options($store_id);
  176.         } catch (\Exception $e) {
  177.             $this->procesaEvent(['error' => $e->getMessage()], $e->getCode(), $req->getUri());
  178.             return $this->helper->print_json(['error' => $e->getMessage()]);
  179.         }
  180.         return $this->helper->print_json(['message' => 'App uninstalled succesfully']);
  181.     }
  182.     /**
  183.      * Sets the APP "paused"
  184.      *
  185.      * @param Request $req
  186.      * @return Response
  187.      */
  188.     public function suspend_app(Request $req): Response
  189.     {
  190.         $webhook_content $req->getContent();
  191.         $hmac_header $req->headers->get('X-Linkedstore-HMAC-SHA256');
  192.         $data_received json_decode($webhook_contenttrue);
  193.         if (!$this->TNApi->verify_webhook($webhook_content$hmac_header)){
  194.             $this->procesaEvent(['error' => 'Couldn\'t verify webhook'], Response::HTTP_BAD_REQUEST$req->getUri());
  195.             return $this->helper->print_json(['error' => 'Couldn\'t verify webhook'], Response::HTTP_BAD_REQUEST);
  196.         }
  197.         if (!$data_received){
  198.             $this->procesaEvent(['error' => 'Invalid JSON received'], Response::HTTP_BAD_REQUEST$req->getUri());
  199.             return $this->helper->print_json(['error' => 'Invalid JSON received']);
  200.         }
  201.         $store_id filter_var($data_received['store_id'], FILTER_SANITIZE_NUMBER_INT);
  202.         try {
  203.             $this->dbm->pause_store($store_id);
  204.         } catch (\Exception $e) {
  205.             $this->procesaEvent(['error' => '$e->getMessage()'], $e->getCode(), $req->getUri());
  206.             return $this->helper->print_json(['error' => $e->getMessage()]);
  207.         }
  208.         return $this->helper->print_json(['message' => 'App paused succesfully']);
  209.     }
  210.     /**
  211.      * Resumes the APP, making it possible to work again
  212.      *
  213.      * @param Request $req
  214.      * @return Response
  215.      */
  216.     public function resume_app(Request $req): Response
  217.     {
  218.         $webhook_content $req->getContent();
  219.         $hmac_header $req->headers->get('X-Linkedstore-HMAC-SHA256');
  220.         $data_received json_decode($webhook_contenttrue);
  221.         if (!$this->TNApi->verify_webhook($webhook_content$hmac_header)){
  222.             $this->procesaEvent(['error' => 'Couldn\'t verify webhook'], Response::HTTP_BAD_REQUEST$req->getUri());
  223.             return $this->helper->print_json(['error' => 'Couldn\'t verify webhook'], Response::HTTP_BAD_REQUEST);
  224.         }
  225.         if (!$data_received) {
  226.             $this->procesaEvent(['error' => 'Invalid JSON received'], Response::HTTP_BAD_REQUEST$req->getUri());
  227.             return $this->helper->print_json(['error' => 'Invalid JSON received']);
  228.         }
  229.         $store_id filter_var($data_received['store_id'], FILTER_SANITIZE_NUMBER_INT);
  230.         try {
  231.             $this->dbm->resume_store($store_id);
  232.         } catch (\Exception $e) {
  233.             $this->procesaEvent(['error' => $e->getMessage()], $e->getCode(), $req->getUri());
  234.             return $this->helper->print_json(['error' => $e->getMessage()]);
  235.         }
  236.         return $this->helper->print_json(['message' => 'App resumed succesfully']);
  237.     }
  238.     private function render_auth_form($store_id$access_token): Response
  239.     {
  240.         $app_name $this->tn_shipping_carrier_name;
  241.         return $this->render(
  242.             'auth-form.html.twig',
  243.             [
  244.                 'store_id' => $store_id,
  245.                 'access_token' => $access_token,
  246.                 'appname' => $app_name
  247.             ]
  248.         );
  249.     }
  250.     /**
  251.      * @param array $message
  252.      * @param string $code
  253.      * @param string $url
  254.      * @return void
  255.      */
  256.     private function procesaEvent(array $messagestring $codestring $url){
  257.         $event = new StoreEvent([$message$code]);
  258.         $event->setUrl($url);
  259.         $this->dispatcher->dispatch($eventStoreEvent::STORE_EVENT);
  260.     }
  261. }