src/Controller/AmoCrmController.php line 157

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\AmoAuthIntegration;
  4. use App\Entity\AmoProject;
  5. use App\Entity\AmoStatus;
  6. use App\Entity\Placement;
  7. use App\Entity\User;
  8. use App\Repository\AmoAuthIntegrationRepository;
  9. use App\Repository\AmoPipelineRepository;
  10. use App\Repository\AmoStatusRepository;
  11. use App\Repository\ComplexRepository;
  12. use App\Repository\PlacementRepository;
  13. use App\Repository\PlacementStatusRepository;
  14. use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
  15. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  16. use Symfony\Component\HttpFoundation\JsonResponse;
  17. use Symfony\Component\HttpFoundation\Request;
  18. use Symfony\Component\HttpFoundation\RequestStack;
  19. use Symfony\Component\HttpFoundation\Response;
  20. use Symfony\Component\Routing\Annotation\Route;
  21. use AmoCRM\OAuth2\Client\Provider\AmoCRM;
  22. use Symfony\Component\Security\Core\User\UserInterface;
  23. class AmoCrmController extends AbstractController
  24. {
  25.     private $logPath '/../../logs/';
  26.     /**
  27.      * @Route ("/api/amo-deal-status-change") methods={"POST"}
  28.      * @param PlacementRepository $placementRepository
  29.      * @param AmoStatusRepository $amoStatusRepository
  30.      * @param RequestStack $requestStack
  31.      */
  32.     public function amoDealStatusChange(PlacementRepository $placementRepositoryAmoStatusRepository $amoStatusRepositoryRequestStack $requestStack)
  33.     {
  34.         $postData $requestStack->getCurrentRequest()->request->all();
  35.         if ($postData && isset($postData['leads'], $postData['leads']['status'], $postData['leads']['status'][0]))
  36.         {
  37.             $em $this->getDoctrine()->getManager();
  38.             $amoDealID $postData['leads']['status'][0]['pipeline_id'] . '.' $postData['leads']['status'][0]['id'];
  39.             file_put_contents(__DIR__ $this->logPath 'amoLog.txt'"\n------------------------------------\n"FILE_APPEND);
  40.             file_put_contents(__DIR__ $this->logPath 'amoLog.txt''amoDealID: ' $amoDealID "\n"FILE_APPEND);
  41.             $amoStatusID $postData['leads']['status'][0]['status_id'];
  42.             $amoPipelineId $postData['leads']['status'][0]['pipeline_id'];
  43.             $placements $placementRepository->findAllByAmoDealID($amoDealID);
  44.             file_put_contents(__DIR__ $this->logPath 'amoLog.txt''placements count: ' count($placements) . "\n"FILE_APPEND);
  45.             /**
  46.              * @var $amoStatus AmoStatus
  47.              */
  48.             $amoStatus $amoStatusRepository->findOneBy(['amo_id' => $amoStatusID'amo_pipeline_id' => $amoPipelineId]);
  49.             /**
  50.              * @var $placement Placement
  51.              */
  52.             
  53.             foreach ($placements as $placement)
  54.             {
  55.                 if ($amoStatus->getPlacementStatus() && $amoStatus->getPlacementStatus()->getAmoOnlyOneDealPlacement())
  56.                     $placement->setAmoDeals([$amoDealID]);
  57.                 
  58.                 if ($amoStatus->getPlacementStatus() && $amoStatus->getPlacementStatus()->getAmoUnlinkDealsOfStatusWithLowerPriority())
  59.                 {
  60. //                    foreach ($placement->getAmoDeals() as )
  61. //                    {
  62. //                        
  63. //                    }
  64.                 }
  65.                 file_put_contents(__DIR__ $this->logPath 'amoLog.txt''placement id: ' $placement->getId() . "\n"FILE_APPEND);
  66.                 $placement->setPlacementStatus($amoStatus->getPlacementStatus());
  67.                 $em->persist($placement);
  68.                 $em->flush();
  69.             }
  70.             file_put_contents(__DIR__ $this->logPath 'amoLog.txt''status changed to ' $amoStatus->getPlacementStatus()->getId() . "\n"FILE_APPEND);
  71.         }
  72.         else
  73.         {
  74.             file_put_contents(__DIR__ $this->logPath 'amoLog.txt'"error\n"FILE_APPEND);
  75. //            file_put_contents($this->logPath . 'amoLog.txt', print_r($postData, true));
  76.             exit;
  77.         }
  78.         file_put_contents(__DIR__ $this->logPath 'amoLog.txt'"\n------------------------------------\n"FILE_APPEND);
  79.         die();
  80.     }
  81.     /**
  82.      * @Route("/api/amo-deal-delete")
  83.      * @param PlacementRepository $placementRepository
  84.      * @param RequestStack $requestStack
  85.      * @param PlacementStatusRepository $placementStatusRepository
  86.      */
  87.     public function handleAmoDealDelete(PlacementRepository $placementRepositoryRequestStack $requestStackPlacementStatusRepository $placementStatusRepository)
  88.     {
  89.         $em $this->getDoctrine()->getManager();
  90.         $postData $requestStack->getCurrentRequest()->request->all();
  91.         file_put_contents(__DIR__ $this->logPath 'amoDeleteLog.txt'"\n------------------------------------\n"FILE_APPEND);
  92.         file_put_contents(__DIR__ $this->logPath 'amoDeleteLog.txt'print_r($postDatatrue), FILE_APPEND);
  93.         $findByDeal $postData['leads']['delete'][0]['pipeline_id'] . '.' $postData['leads']['delete'][0]['id'];
  94.         file_put_contents(__DIR__ $this->logPath 'amoDeleteLog.txt''findByDeal: ' $findByDeal "\n"FILE_APPEND);
  95.         $placements $placementRepository->findAllByAmoDealID($findByDeal);
  96.         file_put_contents(__DIR__ $this->logPath 'amoDeleteLog.txt''count placements: ' count($placements) . "\n"FILE_APPEND);
  97.         /**
  98.          * @var $placement Placement
  99.          */
  100.         foreach ($placements as $placementsIndx => $placement)
  101.         {
  102.             $amoDeals $placement->getAmoDeals();
  103.             foreach ($amoDeals as $amoDealsIndx => $amoDeal)
  104.                 if ($amoDeal === $findByDeal)
  105.                 {
  106.                     unset($amoDeals[$amoDealsIndx]);
  107.                 }
  108.             file_put_contents(__DIR__ $this->logPath 'amoDeleteLog.txt'"placement id: {$placement->getId()} \n placement deals to be set:" "\n"FILE_APPEND);
  109.             file_put_contents(__DIR__ $this->logPath 'amoDeleteLog.txt'print_r($amoDealstrue) . "\n"FILE_APPEND);
  110.             $placement->setAmoDeals($amoDeals);
  111.             if (empty($amoDeals))
  112.             {
  113.                 $onZeroDealStatus$placementStatusRepository->findOneBy(['amoStatusOnZeroDeals' => true'complex' => $placement->getComplex()->getId()]);
  114.                 $placement->setPlacementStatus($onZeroDealStatus);
  115.                 file_put_contents(__DIR__ $this->logPath 'on zero deals new status: ' $onZeroDealStatus->getId() . "\n"FILE_APPEND);
  116.             }
  117.             $em->persist($placement);
  118.             $em->flush();
  119.         }
  120.         file_put_contents(__DIR__ $this->logPath 'amoDeleteLog.txt'"\n------------------------------------\n"FILE_APPEND);
  121.         die();
  122.     }
  123.     /**
  124.      * @Route("/api/exchange-amo-token/{email}") methods={"GET"}
  125.      * @param $email
  126.      * @param JWTTokenManagerInterface $jwtManager
  127.      * @param Request $request
  128.      * @return JsonResponse
  129.      */
  130.     public function getTokenUser($emailJWTTokenManagerInterface $jwtManagerRequest $request)
  131.     {
  132. //        header('Access-Control-Allow-Origin: *');
  133.         $user $this->getDoctrine()
  134.             ->getRepository(User::class)
  135.             ->findOneBy(['email' => $email]);
  136.         if ($user)
  137.             return new JsonResponse(['token' => $jwtManager->create($user)]);
  138.         else
  139.             return new JsonResponse(['error' => 'User not found in Flat Show'], 404);
  140.     }
  141.     /**
  142.      * @Route("/api/integration-secrets")  methods={"POST"}
  143.      * @param RequestStack $requestStack
  144.      * @return Response
  145.      */
  146.     public function integrationSecrets(RequestStack $requestStack) {
  147.         die(200);
  148.         file_put_contents(__DIR__ $this->logPath 'amoLogSecrets.txt'"\n------------------------------------\n"FILE_APPEND);
  149.         $requestContent json_decode($requestStack->getCurrentRequest()->getContent(), true);
  150.         if (isset($requestContent['client_id'], $requestContent['client_secret']))
  151.         {
  152.             $em $this->getDoctrine()->getManager();
  153.             $amoAuthIntegration = new AmoAuthIntegration();
  154.             $amoAuthIntegration->setClientID($requestContent['client_id']);
  155.             $amoAuthIntegration->setClientSecret($requestContent['client_secret']);
  156.             $em->persist($amoAuthIntegration);
  157.             $em->flush();
  158.         }
  159.         file_put_contents(__DIR__ $this->logPath 'amoLogSecrets.txt'print_r($requestContenttrue), FILE_APPEND);
  160.         file_put_contents(__DIR__ $this->logPath 'amoLogSecrets.txt'"\n------------------------------------\n"FILE_APPEND);
  161.         exit;
  162.         return new Response();
  163.     }
  164.     /**
  165.      * @Route("/api/integration-redirect-data")  methods={"POST"}
  166.      * @param RequestStack $requestStack
  167.      * @param AmoAuthIntegrationRepository $amoAuthIntegrationRepository
  168.      * @return Response
  169.      */
  170.     public function integrationRedirectData(RequestStack $requestStackAmoAuthIntegrationRepository $amoAuthIntegrationRepository)
  171.     {
  172.         file_put_contents(__DIR__ $this->logPath 'amoLogSecrets.txt'"\n------------------------------------\n"FILE_APPEND);
  173.         file_put_contents(__DIR__ $this->logPath 'amoLogSecrets.txt'"\nintegrationRedirectData:\n"FILE_APPEND);
  174.         $em $this->getDoctrine()->getManager();
  175.         $code $requestStack->getCurrentRequest()->get('code');
  176.         $state $requestStack->getCurrentRequest()->get('state');
  177.         $referer $requestStack->getCurrentRequest()->get('referer');
  178.         $client_id $requestStack->getCurrentRequest()->get('client_id');
  179.         $amoAuthIntegration $amoAuthIntegrationRepository->findOneBy(['clientID' => $client_id]);
  180.         $amoAuthIntegration->setCode($code);
  181.         $amoAuthIntegration->setRefer($referer);
  182.         $em->persist($amoAuthIntegration);
  183.         $em->flush();
  184.         $dataForAmoAuthRequest = [
  185.             "client_id" =>  $amoAuthIntegration->getClientID(),
  186.             "client_secret" =>  $amoAuthIntegration->getClientSecret(),
  187.             "grant_type" =>  "authorization_code",
  188.             "code" =>  $amoAuthIntegration->getCode(),
  189.             "redirect_uri" => "https://pro-api-dev.flat.show/api/integration-redirect-data"
  190.         ];
  191.         $responseData $this->request("POST"$dataForAmoAuthRequest"https://" $amoAuthIntegration->getRefer() . "/oauth2/access_token"nullfalse);
  192.         file_put_contents(__DIR__ $this->logPath 'amoLogSecrets.txt'print_r($responseDatatrue), FILE_APPEND);
  193.         file_put_contents(__DIR__ $this->logPath 'amoLogSecrets.txt',
  194.             $code  ."\n".
  195.             $state      ."\n".
  196.             $referer    ."\n".
  197.             $client_id  ."\n"
  198.         FILE_APPEND);
  199.         file_put_contents(__DIR__ $this->logPath 'amoLogSecrets.txt'"\n------------------------------------\n"FILE_APPEND);
  200.         exit;
  201.         return new Response();
  202.     }
  203.     /**
  204.      * @Route("/api/amo-auth")
  205.      */
  206.     public function testAmo() {
  207.             echo '<div>
  208.                 <script
  209.                   class="amocrm_oauth"
  210.                   charset="utf-8"
  211.                   data-name="Flat Show"
  212.                   data-description="Integration description"
  213.                   data-redirect_uri="https://pro-api-dev.flat.show/api/integration-redirect-data"
  214.                   data-secrets_uri="https://pro-api-dev.flat.show/api/integration-secrets"
  215.                   data-logo="https://example.com/amocrm_logo.png"
  216.                   data-scopes="crm,notifications"
  217.                   data-title="Flat Show Integration"
  218.                   data-compact="false"
  219.                   data-class-name="className"
  220.                   data-color="default"
  221.                   data-state=""
  222.                   data-error-callback="functionName"
  223.                   data-mode="post_message"
  224.                   src="https://www.amocrm.ru/auth/button.min.js"
  225.                 ></script>
  226.         </div>';
  227.         exit;
  228.     }
  229.     /**
  230.      * @Route("/api/create-amo-deal", methods={"POST"})
  231.      * @param Request $request
  232.      * @param ComplexRepository $complexRepository
  233.      * @return JsonResponse
  234.      * @throws \Exception
  235.      */
  236.     public function amoCreateAmoDeal(Request $requestComplexRepository $complexRepository) : JsonResponse
  237.     {
  238.         header('Access-Control-Allow-Origin: *');
  239.         $jsonRequestData json_decode($request->getContent(), true);
  240.         
  241.         print_r($request->getHttpHost());
  242.         exit;
  243.         if (!isset($jsonRequestData['complexId']))
  244.             die("Error");
  245.         if (!isset($jsonRequestData['amoDealData']))
  246.             die("Error");
  247.         $complexdId $jsonRequestData['complexId'];
  248.         $amoCreateDealData $jsonRequestData['amoDealData'];
  249. //        $amoContactData = $jsonRequestData['amoContactData'];
  250.         if ( !($complexEntity $complexRepository->findOneBy(['id' => $complexdId])))
  251.             throw new \Exception("Complex not found by complexId");
  252.         if ( !($amoPipelineEntity $complexEntity->getAmoPipeline()) )
  253.             throw new \Exception("Amo pipeline not set for complex: {$complexdId}");
  254.         if ( !($amoProject $amoPipelineEntity->getAmoProject()) )
  255.             throw new \Exception('Amo pipeline found but have no AmoProject linked relation object');
  256.         $link 'https://' $amoProject->getSubdomain() . '.amocrm.ru/api/v4/leads';
  257.         foreach ($amoCreateDealData as $key => &$value)
  258.         {
  259.             $value['pipeline_id'] = $amoPipelineEntity->getAmoId();
  260.         }
  261. //        echo "<pre>";
  262. //        print_r($amoCreateDealData);
  263. //        exit;
  264.         return new JsonResponse($this->request('POST'$amoCreateDealData$link$amoProject), Response::HTTP_CREATED);
  265.     }
  266.     private function request($requestType$requestData$linkAmoProject $amoProject null$useAccessToken true)
  267.     {
  268.         $curl curl_init(); //Сохраняем дескриптор сеанса cURL
  269.         /** Устанавливаем необходимые опции для сеанса cURL  */
  270.         curl_setopt($curlCURLOPT_SSLVERSIONCURL_SSLVERSION_TLSv1_2);
  271.         curl_setopt($curl,CURLOPT_RETURNTRANSFERtrue);
  272.         curl_setopt($curl,CURLOPT_USERAGENT,'amoCRM-oAuth-client/1.0');
  273.         curl_setopt($curl,CURLOPT_URL$link);
  274.         if ($useAccessToken)
  275.             curl_setopt($curl,CURLOPT_HTTPHEADER,['Content-Type:application/json',  "Authorization: Bearer " $amoProject->getAccessToken()]);
  276.         else
  277.             curl_setopt($curl,CURLOPT_HTTPHEADER,['Content-Type:application/json']);
  278.         curl_setopt($curl,CURLOPT_HEADERfalse);
  279.         curl_setopt($curl,CURLOPT_CUSTOMREQUEST$requestType);
  280.         curl_setopt($curl,CURLOPT_POSTFIELDSjson_encode($requestData));
  281.         curl_setopt($curl,CURLOPT_SSL_VERIFYPEER1);
  282.         curl_setopt($curl,CURLOPT_SSL_VERIFYHOST2);
  283.         $out curl_exec($curl); //Инициируем запрос к API и сохраняем ответ в переменную
  284.         $code curl_getinfo($curlCURLINFO_HTTP_CODE);
  285.         curl_close($curl);
  286.         /** Теперь мы можем обработать ответ, полученный от сервера. Это пример. Вы можете обработать данные своим способом. */
  287.         $code = (int)$code;
  288.         $errors = [
  289.             400 => 'Bad request',
  290.             401 => 'Unauthorized',
  291.             403 => 'Forbidden',
  292.             404 => 'Not found',
  293.             500 => 'Internal server error',
  294.             502 => 'Bad gateway',
  295.             503 => 'Service unavailable',
  296.         ];
  297.         try
  298.         {
  299.             /** Если код ответа не успешный - возвращаем сообщение об ошибке  */
  300.             if ($code 200 || $code 204) {
  301.                 throw new \Exception(isset($errors[$code]) ? $errors[$code] : 'Undefined error'$code);
  302.             }
  303.         }
  304.         catch(\Exception $e)
  305.         {
  306.             if ($e->getCode() == '401')
  307.             {
  308.                 $this->updateAmoAccessToken($amoProject);
  309.                 return $this->request($requestType$requestData$link$amoProjecttrue);
  310.             }
  311.             die('Ошибка: ' $e->getMessage() . PHP_EOL 'Код ошибки: ' $e->getCode());
  312.         }
  313.         return json_decode($outtrue);
  314.     }
  315.     private function updateAmoAccessToken(AmoProject $amoProject)
  316.     {
  317.         $em $this->getDoctrine()->getManager();
  318.         $amoTokens $this->request('POST', [
  319.             'client_id' => $amoProject->getIntegrationId(),
  320.             'client_secret' => $amoProject->getSecretKey(),
  321.             'grant_type' => 'refresh_token',
  322.             'refresh_token' => $amoProject->getRefreshToken(),
  323.             'redirect_uri' => $amoProject->getRedirectUri(),
  324.         ], 'https://' $amoProject->getSubdomain() . '.' 'amocrm.ru' '/oauth2/access_token'$amoProjectfalse);
  325.         $amoProject->setAccessToken($amoTokens['access_token']);
  326.         $amoProject->setRefreshToken($amoTokens['refresh_token']);
  327.         $em->persist($amoProject);
  328.         $em->flush();
  329.         sleep(6);
  330.     }
  331. }