src/Aviatur/GiftVoucherBundle/Controller/DefaultController.php line 41

Open in your IDE?
  1. <?php
  2. namespace Aviatur\GiftVoucherBundle\Controller;
  3. use Aviatur\GeneralBundle\Entity\FormUserInfo;
  4. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  5. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\HttpFoundation\Response;
  8. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  9. use Aviatur\GeneralBundle\Services\AviaturEncoder;
  10. use Aviatur\GeneralBundle\Services\AviaturErrorHandler;
  11. use Aviatur\TwigBundle\Services\TwigFolder;
  12. use Doctrine\Persistence\ManagerRegistry;
  13. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  14. use Symfony\Component\Routing\RouterInterface;
  15. use Aviatur\GeneralBundle\Services\AviaturWebService;
  16. use Aviatur\PaymentBundle\Services\CustomerMethodPaymentService;
  17. use Aviatur\PaymentBundle\Services\TokenizerService;
  18. use Aviatur\GeneralBundle\Controller\OrderController;
  19. use Aviatur\PaymentBundle\Controller\P2PController;
  20. use Aviatur\PaymentBundle\Controller\WorldPayController;
  21. use Aviatur\PaymentBundle\Controller\PSEController;
  22. use Aviatur\PaymentBundle\Controller\CashController;
  23. use Aviatur\PaymentBundle\Controller\SafetypayController;
  24. use Aviatur\GiftVoucherBundle\Services\EmissionWebservice;
  25. use Aviatur\GeneralBundle\Services\AviaturLogSave;
  26. class DefaultController extends AbstractController
  27. {
  28.     public function searchAction()
  29.     {
  30.         return $this->redirect(
  31.             $this->generateUrl(
  32.                             'aviatur_gift_voucher_detail_secure',
  33.                             []
  34.                         )
  35.         );
  36.     }
  37.     public function detailAction(TwigFolder $twigFolderAviaturWebService $aviaturWebServiceAviaturErrorHandler $aviaturErrorHandlerManagerRegistry $registrySessionInterface $sessionParameterBagInterface $parameterBag$value null)
  38.     {
  39.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  40.         $em $registry->getManager();
  41.         $agency $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
  42.         $isFront $session->has('operatorId');
  43.         $giftVoucherConfigObject $em->getRepository(\Aviatur\GiftVoucherBundle\Entity\ConfigGiftVoucherAgency::class)->findParamsByAgency($agency);
  44.         if (null == $giftVoucherConfigObject || (is_countable($giftVoucherConfigObject) ? count($giftVoucherConfigObject) : 0) == 0) {
  45.             return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_general_homepage'), '''No se encontró configuración para esta Agencia.'));
  46.         }
  47.         $giftVoucherConfig json_decode($giftVoucherConfigObject[0]['params'], true);
  48.         if ($agency->getDomainsecure() == $agency->getDomain() && '443' != $agency->getCustomport()) {
  49.             $safeUrl 'https://'.$agency->getDomain();
  50.         } else {
  51.             $safeUrl 'https://'.$agency->getDomainsecure();
  52.         }
  53.         $giftVoucherFares $giftVoucherConfig['fares'];
  54.         $giftVoucherParams = [
  55.             'minValue' => $giftVoucherConfig['minValue'],
  56.             'maxValue' => $giftVoucherConfig['maxValue'],
  57.         ];
  58.         $documentType $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findAll();
  59.         $paymentMethodAgency $em->getRepository(\Aviatur\GeneralBundle\Entity\PaymentMethodAgency::class)->findBy(['agency' => $agency'isactive' => 1]);
  60.         $paymentOptions = [];
  61.         $repositoryDocumentType $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class);
  62.         $queryDocumentType $repositoryDocumentType
  63.                 ->createQueryBuilder('p')
  64.                 ->where('p.paymentcode != :paymentcode')
  65.                 ->setParameter('paymentcode''')
  66.                 ->getQuery();
  67.         $documentPaymentType $queryDocumentType->getResult();
  68.         foreach ($paymentMethodAgency as $payMethod) {
  69.             $paymentCode $payMethod->getPaymentMethod()->getCode();
  70.             if (!in_array($paymentCode$paymentOptions) && 'safety' != $paymentCode) {
  71.                 $paymentOptions[] = $paymentCode;
  72.             }
  73.         }
  74.         $banks = [];
  75.         if (in_array('pse'$paymentOptions)) {
  76.             $banks $em->getRepository(\Aviatur\PaymentBundle\Entity\PseBank::class)->findAll();
  77.         }
  78.         $cybersource = [];
  79.         if (in_array('cybersource'$paymentOptions)) {
  80.             $cybersource['merchant_id'] = $paymentMethodAgency[array_search('cybersource'$paymentOptions)]->getSitecode();
  81.             $cybersource['org_id'] = $paymentMethodAgency[array_search('cybersource'$paymentOptions)]->getTrankey();
  82.         }
  83.         foreach ($paymentOptions as $key => $paymentOption) {
  84.             if ('cybersource' == $paymentOption) {
  85.                 unset($paymentOptions[$key]); // strip from other renderizable payment methods
  86.             }
  87.         }
  88.         $conditions $em->getRepository(\Aviatur\GeneralBundle\Entity\HistoricalInfo::class)->findMessageByAgencyOrNull($agency'reservation_conditions');
  89. //        if ($session->has($transactionId . '[bono][retry]') === true) {
  90. //            echo ' entra retry !!';
  91. //            $detailInfo = json_decode($session->get($transactionId . '[bono][detail_data_bono]'), true);
  92. //            $twig_readonly = true;
  93. //            $passangerInfo = $detailInfo['PI'];
  94. //            $billingData = $detailInfo['BD'];
  95. //            $contactData = $detailInfo['CD'];
  96. //        } else {
  97. //            echo ' Datos nuevos !!';
  98.         $passangerTypes = [];
  99.         $passangerTypes[1]['ADT'] = 1;
  100.         $passangerTypes[1]['CHD'] = 0;
  101.         $passangerTypes[1]['INF'] = 0;
  102.         $transactionIdResponse $aviaturWebService->loginService('SERVICIO_MPT''dummy|http://www.aviatur.com.co/dummy/', []);
  103.         if ('error' == $transactionIdResponse || is_array($transactionIdResponse)) {
  104.             $aviaturErrorHandler->errorRedirect('''Error MPA''No se creo Login!');
  105.             return new Response('Estamos experimentando dificultades técnicas en este momento.');
  106.         }
  107.         $transactionId = (string) $transactionIdResponse;
  108.         $session->set($transactionIdSessionName$transactionId);
  109.         $twig_readonly false;
  110. //        }
  111. //
  112. //        die;
  113.         $detailData = [
  114.             'safeUrl' => $safeUrl,
  115.             'currency' => 'COP',
  116.             'giftValue' => 50000,
  117.             'twig_readonly' => $twig_readonly,
  118.             'passengers' => $passangerInfo ?? null,
  119.             'billingData' => $billingData ?? null,
  120.             'contactData' => $contactData ?? null,
  121.             'payment_doc_type' => $documentPaymentType,
  122.             'doc_type' => $documentType,
  123.             'conditions' => $conditions,
  124.             'paymentOptions' => $paymentOptions,
  125.             'cybersource' => $cybersource,
  126.             'banks' => $banks,
  127.             'cards' => $em->getRepository(\Aviatur\GeneralBundle\Entity\Card::class)->findAll(),
  128.             'payment_type_form_name' => 'paymentForm',
  129.             'services' => $passangerTypes,
  130.             'resumed_data' => true,
  131.             'giftVoucherFares' => $giftVoucherFares,
  132.             'giftVoucherParams' => $giftVoucherParams,
  133.             'pse' => 1,
  134.         ];
  135.         $agencyFolder $twigFolder->twigFlux();
  136.         return $this->render($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/GiftVoucher/Default/detail.html.twig'), $detailData);
  137.     }
  138.     public function prePaymentStep1Action(Request $requestTokenizerService $tokenizerCustomerMethodPaymentService $customerMethodPaymentServiceTokenStorageInterface $tokenStorageAviaturEncoder $aviaturEncoderTwigFolder $twigFolderAviaturWebService $aviaturWebServiceAviaturErrorHandler $aviaturErrorHandlerManagerRegistry $registrySessionInterface $sessionParameterBagInterface $parameterBag)
  139.     {
  140.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  141.         if ($request->isXmlHttpRequest()) {
  142.             $request $request->request;
  143.             $billingData $request->get('BD');
  144.             $em $registry->getManager();
  145.             $postData $request->all();
  146.             $transactionIdResponse $aviaturWebService->loginService('SERVICIO_MPT''dummy|http://www.aviatur.com.co/dummy/', []);
  147.             if ('error' == $transactionIdResponse || is_array($transactionIdResponse)) {
  148.                 $aviaturErrorHandler->errorRedirect('''Error MPA''No se creo Login!');
  149.                 return new Response('Estamos experimentando dificultades técnicas en este momento.');
  150.             }
  151.             $transactionId = (string) $transactionIdResponse;
  152.             $session->set($transactionIdSessionName$transactionId);
  153.             $provider $em->getRepository(\Aviatur\MpaBundle\Entity\Provider::class)->findBy(['name' => 'Bono de regalo']);
  154.             $session->set($transactionId.'[bono][provider]'$provider[0]->getProvideridentifier());
  155.             $publicKey $aviaturEncoder->aviaturRandomKey();
  156.             if (isset($postData['PD']['card_num'])) {
  157.                 $postDataInfo $postData;
  158.                 if (isset($postDataInfo['PD']['cusPOptSelected'])) {
  159.                     $customerLogin $tokenStorage->getToken()->getUser();
  160.                     $infoMethodPaymentByClient $customerMethodPaymentService->getMethodsByCustomer($customerLogintrue);
  161.                     $cardToken $infoMethodPaymentByClient['info'][$postDataInfo['PD']['cusPOptSelected']]['token'];
  162.                     $postDataInfo['PD']['card_num'] = $cardToken;
  163.                     $postData['PD']['card_num'] = $cardToken;
  164.                 } else {
  165.                     $postDataInfo['PD']['card_num'] = $tokenizer->getToken($postData['PD']['card_num']);
  166.                 }
  167.                 $postData['PD']['card_values'] = ['card_num_token' => $postDataInfo['PD']['card_num'], 'card_num' => $postData['PD']['card_num']];
  168.             }
  169.             $encodedInfo $aviaturEncoder->AviaturEncode(json_encode($postDataInfo ?? $postData), $publicKey);
  170.             $formUserInfo = new FormUserInfo();
  171.             $formUserInfo->setInfo($encodedInfo);
  172.             $formUserInfo->setPublicKey($publicKey);
  173.             $em->persist($formUserInfo);
  174.             $em->flush();
  175.             $session->set($transactionId.'[bono][user_info]'$formUserInfo->getId());
  176.             if ((true !== $session->has($transactionId.'[bono][retry]')) || (true !== $session->has($transactionId.'[bono][prepayment_check]'))) {
  177.                 $session->set($transactionId.'[bono][detail_data_bono]'json_encode($postData));
  178.                 $passangersData $request->get('PI');
  179.                 $passangerNames = [];
  180.                 for ($i 1$i <= $passangersData['person_count_1']; ++$i) {
  181.                     $passangerNames[] = mb_strtolower($passangersData['first_name_1_'.$i]);
  182.                     $passangerNames[] = mb_strtolower($passangersData['last_name_1_'.$i]);
  183.                 }
  184.                 $nameWhitelist $em->getRepository(\Aviatur\GeneralBundle\Entity\NameWhitelist::class)->findLikeWhitelist($passangerNames);
  185.                 if (== sizeof($nameWhitelist)) {
  186.                     $nameBlacklist $em->getRepository(\Aviatur\GeneralBundle\Entity\NameBlacklist::class)->findLikeBlacklist($passangerNames);
  187.                     if ((sizeof(preg_grep("/^[a-z- *\.]+$/"$passangerNames)) != (sizeof($passangerNames))) ||
  188.                             (sizeof($nameBlacklist)) ||
  189.                             (sizeof(preg_grep('/(([b-df-hj-np-tv-xz])(?!\2)){4}/'$passangerNames)))) {
  190.                         return $this->json(['error' => 'error''message' => 'nombre inválido']);
  191.                     }
  192.                 }
  193.                 $isFront $session->has('operatorId');
  194.                 if ($isFront) {
  195.                     $customer null;
  196.                     $ordersProduct null;
  197.                 } else {
  198.                     $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($billingData['id']);
  199.                     $ordersProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->getOrderProductsPending($customer);
  200.                 }
  201.                 if (null == $ordersProduct) {
  202.                     $ajaxUrl $this->generateUrl('aviatur_gift_voucher_prepayment_step_2_secure');
  203.                     return $this->json(['ajax_url' => $ajaxUrl]);
  204.                 } else {
  205.                     $booking = [];
  206.                     $cus = [];
  207.                     foreach ($ordersProduct as $orderProduct) {
  208.                         $productResponse $aviaturEncoder->AviaturDecode($orderProduct->getPayResponse(), $orderProduct->getPublicKey());
  209.                         $paymentResponse json_decode($productResponse);
  210.                         array_push($booking'ON'.$orderProduct->getOrder()->getId().'-PN'.$orderProduct->getId());
  211.                         if (isset($paymentResponse->x_approval_code)) {
  212.                             array_push($cus$paymentResponse->x_approval_code);
  213.                         } elseif (isset($paymentResponse->createTransactionResult->trazabilityCode)) {
  214.                             array_push($cus$paymentResponse->createTransactionResult->trazabilityCode);
  215.                         }
  216.                     }
  217.                     return $this->json([
  218.                                 'error' => 'pending payments',
  219.                                 'message' => 'pending_payments',
  220.                                 'booking' => $booking,
  221.                                 'cus' => $cus,
  222.                     ]);
  223.                 }
  224.             } else {
  225.                 $paymentData $request->get('PD');
  226.                 $paymentData json_decode(json_encode($paymentData));
  227.                 $json json_decode($session->get($transactionId.'[bono][order]'));
  228.                 if (!is_null($json)) {
  229.                     $json->ajax_url $this->generateUrl('aviatur_gift_voucher_prepayment_step_2_secure');
  230.                     // reemplazar datos de pago por los nuevos.
  231.                     $oldPostData json_decode($session->get($transactionId.'[bono][detail_data_bono]'));
  232.                     if (isset($paymentData->cusPOptSelected) || isset($paymentData->card_num)) {
  233.                         if (isset($paymentData->cusPOptSelected)) {
  234.                             $customerLogin $tokenStorage->getToken()->getUser();
  235.                             $infoMethodPaymentByClient $customerMethodPaymentService->getMethodsByCustomer($customerLogintrue);
  236.                             $card_num_token $infoMethodPaymentByClient['info'][$paymentData->cusPOptSelected]['token'];
  237.                         } else {
  238.                             $card_num_token $tokenizer->getToken($paymentData->card_num);
  239.                         }
  240.                         $card_values = ['card_num_token' => $card_num_token'card_num' => $paymentData->card_num];
  241.                     }
  242.                     unset($oldPostData->PD);
  243.                     $oldPostData->PD $paymentData;
  244.                     if (isset($card_num_token)) {
  245.                         $oldPostData->PD->card_values $card_values;
  246.                     }
  247.                     $session->set($transactionId.'[bono][detail_data_bono]'json_encode($oldPostData));
  248.                     $response = new Response(json_encode($json));
  249.                     $response->headers->set('Content-Type''application/json');
  250.                     return $response;
  251.                 } else {
  252.                     return $this->json(['error' => 'fatal''message' => $aviaturErrorHandler->errorRedirect($session->get($transactionId.'[availability_url]'), '''No encontramos datos de tu orden, por favor inténtalo nuevamente')]);
  253.                 }
  254.             }
  255.         } else {
  256.             return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''Acceso no autorizado'));
  257.         }
  258.     }
  259.     public function prePaymentStep2Action(Request $requestOrderController $orderControllerTwigFolder $twigFolderAviaturErrorHandler $aviaturErrorHandlerManagerRegistry $registrySessionInterface $sessionParameterBagInterface $parameterBag)
  260.     {
  261.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  262.         $aviaturPaymentRetryTimes $parameterBag->get('aviatur_payment_retry_times');
  263.         $order = [];
  264.         if ($request->isXmlHttpRequest()) {
  265.             $request $request->request;
  266.             $em $registry->getManager();
  267.             $agency $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
  268.             $billingData $request->get('BD');
  269.             $transactionId $session->get($transactionIdSessionName);
  270.             $session->set($transactionId.'[bono][prepayment_check]'true);
  271.             if (true !== $session->has($transactionId.'[bono][order]')) {
  272.                 $isFront $session->has('operatorId');
  273.                 if ($isFront) {
  274.                     $customer $billingData;
  275.                     $customer['isFront'] = true;
  276.                     $status 'B2T';
  277.                 } else {
  278.                     $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($billingData['id']);
  279.                     $status 'waiting';
  280.                 }
  281.                 if (isset($agency)) {
  282.                     $productType $em->getRepository(\Aviatur\MpaBundle\Entity\ProductType::class)->findByCode('BONO');
  283. //                    $orderIdentifier = $this->generateRamdonCode();
  284.                     $orderIdentifier '{order_product_num}';
  285.                     $order $orderController->createAction($agency$customer$productType$orderIdentifier$status);
  286.                     $orderId str_replace('ON'''$order['order']);
  287.                     $orderEntity $em->getRepository(\Aviatur\GeneralBundle\Entity\Order::class)->find($orderId);
  288.                     $formUserInfo $em->getRepository(\Aviatur\GeneralBundle\Entity\FormUserInfo::class)->find($session->get($transactionId.'[bono][user_info]'));
  289.                     $formUserInfo->setOrder($orderEntity);
  290.                     $em->persist($formUserInfo);
  291.                     $em->flush();
  292.                     if ($isFront) {
  293.                         //    $this->outputFront();
  294.                         $order['url'] = $this->generateUrl('aviatur_gift_voucher_generar_bono');
  295.                     } else {
  296.                         $session->set($transactionId.'[bono][retry]'$aviaturPaymentRetryTimes);
  297.                         $order['url'] = $this->generateUrl('aviatur_gift_voucher_payment_secure');
  298.                     }
  299.                     return $this->json($order);
  300.                 } else {
  301.                     return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''No se encontró la agencia con el dominio: '.$request->getHost()));
  302.                     // redireccionar al home y enviar mensaje modal
  303.                 }
  304.             } else {
  305.                 $order['url'] = $this->generateUrl('aviatur_gift_voucher_payment_secure');
  306.                 return $this->json($order);
  307.             }
  308.         } else {
  309.             return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''Acceso no autorizado'));
  310.         }
  311.     }
  312.     public function paymentAction(Request $request, \Swift_Mailer $mailerCashController $cashPaymentControllerRouterInterface $routerSafetypayController $safetyPayControllerWorldPayController $worldPaymentControllerP2PController $p2pPaymentControllerPSEController $psePaymentControllerTwigFolder $twigFolderAviaturErrorHandler $aviaturErrorHandlerManagerRegistry $registrySessionInterface $sessionParameterBagInterface $parameterBagTokenizerService $tokenizerCustomerMethodPaymentService $customerMethodPaymentServiceAviaturLogSave $logSave)
  313.     {
  314.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  315.         $emailNotification $parameterBag->get('email_notification');
  316.         $orderProduct = [];
  317.         $paymentResponse null;
  318.         $return null;
  319.         $emissionData = [];
  320.         $response null;
  321.         $array = [];
  322.         $em $registry->getManager();
  323.         $transactionId $session->get($transactionIdSessionName);
  324.         $fullRequest $request;
  325.         $domain $fullRequest->getHost();
  326.         $parametersJson $session->get($domain.'[parameters]');
  327.         $parameters json_decode($parametersJson);
  328.         $agency $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
  329.         $postData json_decode($session->get($transactionId.'[bono][detail_data_bono]'));
  330.         $orderInfo json_decode($session->get($transactionId.'[bono][order]'));
  331.         $productId str_replace('PN'''$orderInfo->products);
  332.         $orderProduct[] = $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  333.         $orderProduct[0]->setProductIdAviatur('ServiceOffLine');
  334.         $orderProduct[0]->setPaymentidaviatur('ServiceOffLine');
  335.         $em->persist($orderProduct[0]);
  336.         $em->flush();
  337.         $paymentData $postData->PD;
  338.         $recipientData $postData->PI;
  339.         $giftArray explode(','base64_decode($postData->GV->giftSelected));
  340.         $giftVoucherValue 0;
  341.         $codeGift base64_decode($giftArray[1]);
  342.         $giftVoucherConfigObject $em->getRepository(\Aviatur\GiftVoucherBundle\Entity\ConfigGiftVoucherAgency::class)->findParamsByAgency($agency);
  343.         if (null == $giftVoucherConfigObject || (is_countable($giftVoucherConfigObject) ? count($giftVoucherConfigObject) : 0) == 0) {
  344.             return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_general_homepage'), '''No se encontró configuración para esta Agencia.'));
  345.         }
  346.         $giftVoucherConfig json_decode($giftVoucherConfigObject[0]['params'], true);
  347.         foreach ($giftVoucherConfig['fares'] as $giftVoucherFares) {
  348.             if ($giftVoucherFares['code'] == $codeGift) {
  349.                 $giftVoucherValue $giftVoucherFares['value'];
  350.             }
  351.         }
  352.         if (== $giftVoucherValue) {
  353.             $valueGift round(((int) (substr($giftArray[0], -3)) * 9) / 3);
  354.             if ($valueGift == $codeGift) {
  355.                 $giftVoucherValue = (int) substr($giftArray[0], 0, -3) - (int) $valueGift;
  356.             } else {
  357.                 return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_general_homepage'), '''1 No se encontro informacion del producto solicitado '));
  358.             }
  359.         }
  360.         $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($postData->BD->id);
  361.         $x_amount_total $giftVoucherValue;
  362.         $x_amount_base round((float) $x_amount_total / (+ (float) $parameters->aviatur_payment_iva));
  363.         $x_amount_tax round((float) $x_amount_total * (- (/ (+ (float) $parameters->aviatur_payment_iva))));
  364.         $description 'Bono de Regalo - $'.$x_amount_total;
  365.         if ('p2p' == $paymentData->type || 'world' == $paymentData->type) {
  366.             if (false !== strpos($paymentData->address'***')) {
  367.                 $paymentData->address $customer->getAddress();
  368.             }
  369.             if (false !== strpos($paymentData->phone'***')) {
  370.                 $paymentData->phone $customer->getPhone();
  371.             }
  372.             if (false !== strpos($paymentData->email'***')) {
  373.                 $paymentData->email $customer->getEmail();
  374.             }
  375.             $array = [
  376.                 'x_currency_code' => (string) 'COP',
  377.                 'x_amount' => number_format(round((float) ($x_amount_total)), 0'.'''),
  378.                 'x_tax' => number_format(round((float) ($x_amount_tax)), 2'.'''),
  379.                 'x_amount_base' => number_format(round((float) ($x_amount_base)), 2'.'''),
  380.                 'x_invoice_num' => $orderInfo->order.'-'.$orderInfo->products,
  381.                 'x_first_name' => $paymentData->first_name,
  382.                 'x_last_name' => $paymentData->last_name,
  383.                 'x_description' => $description,
  384.                 'x_cust_id' => $customer->getDocumentType()->getPaymentcode().' '.$customer->getDocumentnumber(),
  385.                 'x_address' => $paymentData->address,
  386.                 'x_phone' => $paymentData->phone,
  387.                 'x_email' => $paymentData->email,
  388.                 'x_card_num' => $paymentData->card_num,
  389.                 'x_exp_date' => $paymentData->exp_month.$paymentData->exp_year,
  390.                 'x_card_code' => $paymentData->card_code,
  391.                 'x_differed' => $paymentData->differed,
  392.                 'x_client_id' => $postData->BD->id,
  393.                 'product_type' => 'bono',
  394.             ];
  395.             if (isset($paymentData->card_values)) {
  396.                 $array['card_values'] = (array) $paymentData->card_values;
  397.             }
  398.             if ('p2p' == $paymentData->type) {
  399.                 if (isset($paymentData->cusPOptSelected)) {
  400.                     $array['isToken'] = (string) $paymentData->card_values->card_num_token;
  401.                 }
  402.                 if (isset($postData->PD->savePaymProc)) {
  403.                     $array['x_provider_id'] = 1;
  404.                 } elseif (isset($paymentData->cusPOptSelected)) {
  405.                     if (isset($paymentData->cusPOptSelectedStatus)) {
  406.                         if ('NOTVERIFIED' == $paymentData->cusPOptSelectedStatus) {
  407.                             $array['x_provider_id'] = 1;
  408.                         } else {
  409.                             $array['x_provider_id'] = 2;
  410.                         }
  411.                     } else {
  412.                         $array['x_provider_id'] = 2;
  413.                     }
  414.                 }
  415.             }
  416.             if ('p2p' == $paymentData->type) {
  417.                 $paymentResponse $p2pPaymentController->placetopayAction($parameterBag$tokenizer$customerMethodPaymentService$mailer$logSave$array);
  418.                 $return $this->redirect($this->generateUrl('aviatur_gift_voucher_payment_p2p_return_url_secure', [], true));
  419.             } elseif ('world' == $paymentData->type) {
  420.                 $array['city'] = $customer->getCity()->getIatacode();
  421.                 $array['countryCode'] = $customer->getCity()->getCountry()->getIatacode();
  422.                 $paymentResponse $worldPaymentController->worldAction($array);
  423.                 $return $this->redirect($this->generateUrl('aviatur_gift_voucher_payment_world_return_url_secure', [], true));
  424.             }
  425.             unset($array['x_client_id']);
  426.             if (null != $paymentResponse) {
  427.                 return $return;
  428.             } else {
  429.                 $orderProduct[0]->setStatus('pending');
  430.                 $em->persist($orderProduct[0]);
  431.                 $em->flush();
  432.                 return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_gift_voucher_retry_secure'), '''No hay respuesta por parte del servicio de pago, por favor intenta nuevamente o comunícate con nosotros para finalizar tu transacción'));
  433.             }
  434.         } elseif ('pse' == $paymentData->type) {
  435.             $array = ['x_doc_num' => $customer->getDocumentnumber(),
  436.                 'x_doc_type' => $customer->getDocumentType()->getPaymentcode(),
  437.                 'x_first_name' => $customer->getFirstname(),
  438.                 'x_last_name' => $customer->getLastname(),
  439.                 'x_company' => 'Aviatur',
  440.                 'x_email' => $customer->getEmail(),
  441.                 'x_address' => $customer->getAddress(),
  442.                 'x_city' => $customer->getCity()->getDescription(),
  443.                 'x_province' => $customer->getCity()->getDescription(),
  444.                 'x_country' => $customer->getCountry()->getDescription(),
  445.                 'x_phone' => $customer->getPhone(),
  446.                 'x_mobile' => $customer->getCellphone(),
  447.                 'x_bank' => $postData->PD->pse_bank,
  448.                 'x_type' => $postData->PD->pse_type,
  449.                 'x_response_url' => $this->generateUrl('aviatur_gift_voucher_payment_pse_return_url_secure', [], true),
  450.                 'x_reference' => $orderInfo->order.'-'.$orderInfo->products,
  451.                 'x_description' => $description,
  452.                 'x_currency' => 'COP',
  453.                 'x_total_amount' => $x_amount_total,
  454.                 'x_tax_amount' => number_format(round($x_amount_tax), 2'.'''),
  455.                 'x_devolution_base' => number_format(round($x_amount_base), 2'.'''),
  456.                 'x_tip_amount' => number_format(round(0), 2'.'''),
  457.                 'product_type' => 'bono',
  458.             ];
  459.             $paymentResponse $psePaymentController->sendPaymentAction($array$orderProduct);
  460.             if (!isset($paymentResponse->error)) {
  461.                 switch ($paymentResponse->createTransactionResult->returnCode) {
  462.                     case 'SUCCESS':
  463.                         return $this->redirect($paymentResponse->createTransactionResult->bankURL);
  464.                     case 'FAIL_EXCEEDEDLIMIT':
  465.                         return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''Tu reserva fue realizada exitosamente, sin embargo, el monto excede los límites establecidos, comuníate con nosotros a  los teléfonos 57 1 5879640 o 57 1 3821616 o  vía e-mail al correo soportepagoelectronico@aviatur.com.co para completar tu transacción.'));
  466.                     case 'FAIL_BANKUNREACHEABLE':
  467.                         return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_gift_voucher_retry_secure'), '''Tu entidad financiera no pudo ser contactada para iniciar la transacción, por favor inténtalo nuevamente'));
  468.                     default:
  469.                         return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_gift_voucher_retry_secure'), '''No se pudo crear la transacción con tu banco, por favor inténtalo nuevamente'));
  470.                 }
  471.             } else {
  472.                 return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_gift_voucher_retry_secure'), 'Error al procesar el pago''Ocurrió un problema al intentar crear tu transacción, '.$paymentResponse->error));
  473.             }
  474.         } elseif ('safety' == $paymentData->type) {
  475.             $orderProductCode json_decode($session->get($transactionId.'[bono][order]'));
  476.             $transactionUrl $this->generateUrl('aviatur_payment_safetypay', [], true);
  477.             $productId str_replace('PN'''$orderProductCode->products);
  478.             $Product $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  479.             $array = ['x_doc_num' => $customer->getDocumentnumber(),
  480.                 'x_doc_type' => $customer->getDocumentType()->getPaymentcode(),
  481.                 'x_first_name' => $customer->getFirstname(),
  482.                 'x_last_name' => $customer->getLastname(),
  483.                 'x_company' => 'Aviatur',
  484.                 'x_email' => $customer->getEmail(),
  485.                 'x_address' => $customer->getAddress(),
  486.                 'x_city' => $customer->getCity()->getDescription(),
  487.                 'x_province' => $customer->getCity()->getDescription(),
  488.                 'x_country' => $customer->getCountry()->getDescription(),
  489.                 'x_phone' => $customer->getPhone(),
  490.                 'x_mobile' => $customer->getCellphone(),
  491.                 'x_reference' => $orderInfo->products,
  492.                 'x_booking' => $Product->getBooking(),
  493.                 'x_description' => $description,
  494.                 'x_currency' => 'COP',
  495.                 'x_total_amount' => $x_amount_total,
  496.                 'x_tax_amount' => number_format(round($x_amount_tax), 2'.'''),
  497.                 'x_devolution_base' => number_format(round($x_amount_base), 2'.'''),
  498.                 'x_tip_amount' => number_format(round(0), 2'.'''),
  499.                 'x_payment_data' => $paymentData->type,
  500.                 'x_type_description' => $orderProduct[0]->getDescription(),
  501.             ];
  502.             $parametMerchant = [
  503.                 'MerchantSalesID' => $array['x_reference'],
  504.                 'Amount' => $array['x_total_amount'],
  505.                 'transactionUrl' => $transactionUrl,
  506.                 'dataTrans' => $array,
  507.             ];
  508.             $safeTyPay $safetyPayController->safetyAction($router$parameterBag$mailer$parametMerchant$array);
  509.             if ('ok' == $safeTyPay['status']) {
  510.                 if ('baloto' == $paymentData->type) {
  511.                     $cash '&CountryId=COL&ChannelId=CASH';
  512.                     $session->set($transactionId.'[bono][retry]'0);
  513.                     return $this->redirect($safeTyPay['response'].$cash);
  514.                 } else {
  515.                     return $this->redirect($safeTyPay['response']);
  516.                 }
  517.             } else {
  518.                 $emissionData->x_booking $array['x_booking'];
  519.                 $emissionData->x_first_name $array['x_first_name'];
  520.                 $emissionData->x_last_name $array['x_last_name'];
  521.                 $emissionData->x_doc_num $array['x_doc_num'];
  522.                 $emissionData->x_reference $array['x_reference'];
  523.                 $emissionData->x_description $array['x_description'];
  524.                 $emissionData->x_total_amount $array['x_total_amount'];
  525.                 $emissionData->x_email $array['x_email'];
  526.                 $emissionData->x_address $array['x_address'];
  527.                 $emissionData->x_phone $array['x_phone'];
  528.                 $emissionData->x_type_description $array['x_type_description'];
  529.                 $emissionData->x_resultSafetyPay $safeTyPay;
  530.                 $mailInfo print_r($emissionDatatrue).'<br>'.print_r($responsetrue);
  531.                 $message = (new \Swift_Message())
  532.                         ->setContentType('text/html')
  533.                         ->setFrom($session->get('emailNoReply'))
  534.                         ->setTo('errores.prod.web@aviatur.com')
  535.                         ->setSubject('Error Creación Token SafetyPay'.$emissionData->x_reference)
  536.                         ->setBody($mailInfo);
  537.                 $mailer->send($message);
  538.                 return $this->redirect($this->generateUrl('aviatur_gift_voucher_payment_rejected_secure'));
  539.             }
  540.         } elseif ('cash' == $paymentData->type) {
  541.             $agency $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
  542.             $agencyName $agency->getOfficeId();
  543.             $array['x_officeId'] = $agencyName;
  544.             $array['x_doc_num'] = $customer->getDocumentnumber();
  545.             $array['x_doc_type'] = $customer->getDocumentType()->getPaymentcode();
  546.             $array['x_first_name'] = $customer->getFirstname();
  547.             $array['x_last_name'] = $customer->getLastname();
  548.             $array['x_company'] = 'Aviatur';
  549.             $array['x_email'] = $customer->getEmail();
  550.             $array['x_address'] = $customer->getAddress();
  551.             $array['x_city'] = $customer->getCity()->getDescription();
  552.             $array['x_province'] = $customer->getCity()->getDescription();
  553.             $array['x_country'] = $customer->getCountry()->getDescription();
  554.             $array['x_phone'] = $customer->getPhone();
  555.             $array['x_mobile'] = $customer->getCellphone();
  556.             $array['x_payment_data'] = $paymentData->type;
  557.             $array['x_type_description'] = $orderProduct[0]->getDescription();
  558.             $array['x_reference'] = $orderInfo->products;
  559.             $array['x_total_amount'] = $x_amount_total;
  560.             $array['x_currency'] = 'COP';
  561.             $array['x_description'] = $description;
  562.             $array['x_booking'] = $orderProduct[0]->getBooking();
  563.             $fecha $orderProduct[0]->getCreationDate()->format('Y-m-d H:i:s');
  564.             $fechalimite $orderProduct[0]->getCreationDate()->format('Y-m-d 23:40:00');
  565.             $nuevafecha strtotime('+5 hour'strtotime($fecha));
  566.             $fechavigencia date('Y-m-d H:i:s'$nuevafecha);
  567.             if (strcmp($fechavigencia$fechalimite) > 0) {
  568.                 $fechavigencia $fechalimite;
  569.             }
  570.             $array['x_fechavigencia'] = $fechavigencia;
  571.             $array['x_transactionId'] = $transactionId;
  572.             $retryCount = (int) $session->get($transactionId.'[bono][retry]');
  573.             $route $router->match(str_replace($request->getSchemeAndHttpHost(), ''$request->getUri()));
  574.             $isMulti false !== strpos($route['_route'], 'multi') ? true false;
  575.             if ($isMulti) {
  576.                 return $this->json($array);
  577.             } elseif ($session->has($transactionId.'[bono][detail_cash]')) {
  578.                 $detail_cash json_decode($session->get($transactionId.'[bono][detail_cash]'));
  579.                 if ('error' == $detail_cash->status) {
  580.                     $cashPay $cashPaymentController->cashAction($array);
  581.                 } else {
  582.                     $cashPay json_decode($session->get($transactionId.'[bono][detail_cash]'));
  583.                 }
  584.             } else {
  585.                 $cashPay $cashPaymentController->cashAction($array);
  586.                 $session->set($transactionId.'[bono][detail_cash]'json_encode($cashPay));
  587.             }
  588.             $bookingId $this->generateRamdonCode();
  589.             $voucherData = [
  590.                 'empresaId' => '10',
  591.                 'productId' => $productId,
  592.                 'bonoId' => $bookingId,
  593.                 'ammount' => $x_amount_total,
  594.                 'currency' => 'COP',
  595.                 'documentNumber' => $orderProduct[0]->getOrder()->getCustomer()->getDocumentnumber(),
  596.                 'status' => 'EMT',
  597.                 'documentType' => $orderProduct[0]->getOrder()->getCustomer()->getDocumentType()->getExternalcode(),
  598.                 'name' => $orderProduct[0]->getOrder()->getCustomer()->getFirstname().' '.$orderProduct[0]->getOrder()->getCustomer()->getLastname(),
  599.                 'email' => $orderProduct[0]->getOrder()->getCustomer()->getEmail(),
  600.                 'phone' => $orderProduct[0]->getOrder()->getCustomer()->getPhone(),
  601.                 'recipient_name' => $recipientData->first_name_1_1.' '.$recipientData->last_name_1_1,
  602.                 'recipient_mail' => $recipientData->email_1_1,
  603.                 'recipient_phone' => $postData->CD->phone,
  604.                 'recipient_document' => $recipientData->doc_num_1_1,
  605.             ];
  606.             $outputInfo $this->prepareOutputInfo();
  607.             $orderProduct[0]->setResume(json_encode($outputInfo));
  608.             $orderProduct[0]->setEmissiondata($bookingId);
  609.             $orderProduct[0]->setEmail(json_encode($voucherData));
  610.             $em->persist($orderProduct[0]);
  611.             $em->flush();
  612.             if ('ok' == $cashPay->status) {
  613.                 $session->set($transactionId.'[bono][cash_result]'json_encode($cashPay));
  614.                 return $this->redirect($this->generateUrl('aviatur_gift_voucher_confirmation_success_secure'));
  615.             } else {
  616.                 $emissionData['x_first_name'] = $array['x_first_name'];
  617.                 $emissionData['x_last_name'] = $array['x_last_name'];
  618.                 $emissionData['x_doc_num'] = $array['x_doc_num'];
  619.                 $emissionData['x_reference'] = $array['x_reference'];
  620.                 $emissionData['x_description'] = $array['x_description'];
  621.                 $emissionData['x_total_amount'] = $array['x_total_amount'];
  622.                 $emissionData['x_email'] = $array['x_email'];
  623.                 $emissionData['x_address'] = $array['x_address'];
  624.                 $emissionData['x_phone'] = $array['x_phone'];
  625.                 $emissionData['x_type_description'] = $array['x_type_description'];
  626.                 $emissionData['x_error'] = $cashPay->status;
  627.                 $mailInfo print_r($emissionDatatrue).'<br>'.print_r($cashPaytrue);
  628.                 $toEmails = ['soportepagoelectronico@aviatur.com.co''soptepagelectronic@aviatur.com''errores.prod.web@aviatur.com'];
  629.                 $message = (new \Swift_Message())
  630.                         ->setContentType('text/html')
  631.                         ->setFrom($session->get('emailNoReply'))
  632.                         ->setTo($toEmails)
  633.                         ->setBcc($emailNotification)
  634.                         ->setSubject('Error Creación Transacción Efectivo'.$emissionData['x_reference'])
  635.                         ->setBody($mailInfo);
  636.                 $mailer->send($message);
  637.                 $session->set($transactionId.'[bono][retry]'$retryCount 1);
  638.                 return $this->redirect($this->generateUrl('aviatur_gift_voucher_payment_rejected_secure'));
  639.             }
  640.         } else {
  641.             return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_gift_voucher_retry_secure'), '''El tipo de pago es invalido'));
  642.         }
  643.     }
  644.     public function p2pCallbackAction(ManagerRegistry $registryCustomerMethodPaymentService $customerMethodPaymentServiceOrderController $orderControllerTokenStorageInterface $tokenStorageAviaturEncoder $aviaturEncoderAviaturErrorHandler $aviaturErrorHandlerSessionInterface $sessionParameterBagInterface $parameterBagEmissionWebservice $emmisionWebService)
  645.     {
  646.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  647.         $em $registry->getManager();
  648.         $transactionId $session->get($transactionIdSessionName);
  649.         $detailInfo json_decode($session->get($transactionId.'[bono][detail_data_bono]'));
  650.         $orderProductCode $session->get($transactionId.'[bono][order]');
  651.         $productId str_replace('PN'''json_decode($orderProductCode)->products);
  652.         $orderProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  653.         $bookingId $this->generateRamdonCode();
  654.         $decodedRequest json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayrequest(), $orderProduct->getPublicKey()));
  655.         $decodedResponse json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayresponse(), $orderProduct->getPublicKey()));
  656.         if (null != $decodedResponse) {
  657.             $orderController->updatePaymentAction($orderProduct);
  658.             $twig '';
  659.             $retryCount = (int) $session->get($transactionId.'[bono][retry]');
  660.             $voucherData = [
  661.                 'empresaId' => '10',
  662.                 'productId' => $productId,
  663.                 'bonoId' => $bookingId,
  664.                 'ammount' => $decodedRequest->x_amount,
  665.                 'currency' => 'COP',
  666.                 'documentNumber' => $orderProduct->getOrder()->getCustomer()->getDocumentnumber(),
  667.                 'status' => 'EMT',
  668.                 'documentType' => $orderProduct->getOrder()->getCustomer()->getDocumentType()->getExternalcode(),
  669.                 'name' => $orderProduct->getOrder()->getCustomer()->getFirstname().' '.$orderProduct->getOrder()->getCustomer()->getLastname(),
  670.                 'email' => $orderProduct->getOrder()->getCustomer()->getEmail(),
  671.                 'phone' => $orderProduct->getOrder()->getCustomer()->getPhone(),
  672.                 'recipient_name' => $detailInfo->PI->first_name_1_1.' '.$detailInfo->PI->last_name_1_1,
  673.                 'recipient_mail' => $detailInfo->PI->email_1_1,
  674.                 'recipient_phone' => $detailInfo->CD->phone,
  675.                 'recipient_document' => $detailInfo->PI->doc_num_1_1,
  676.             ];
  677.             switch ($decodedResponse->x_response_code) {
  678.                 case isset($decodedResponse->x_response_code_cyber) && (== $decodedResponse->x_response_code_cyber):
  679.                     //rechazado cybersource
  680.                     $parameters $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneByName('aviatur_switch_rechazada_cyber');
  681.                     if ($parameters) {
  682.                         if (== $parameters->getValue()) {
  683.                             if (== $decodedResponse->x_response_code) {
  684.                                 $postData json_decode($session->get($transactionId.'[bono][detail_data_bono]'));
  685.                                 if (isset($postData->PD->cusPOptSelected)) {
  686.                                     if (isset($postData->PD->cusPOptSelectedStatus)) {
  687.                                         if ('NOTVERIFIED' == $postData->PD->cusPOptSelectedStatus) {
  688.                                             $postData->PD->cusPOptSelectedStatus 'ACTIVE';
  689.                                             $customerLogin $tokenStorage->getToken()->getUser();
  690.                                             $customerMethodPaymentService->setMethodsByCustomer($customerLoginjson_decode(json_encode($postData), true));
  691.                                         }
  692.                                     }
  693.                                 }
  694.                                 if (isset($postData->PD->savePaymProc)) {
  695.                                     $customerLogin $tokenStorage->getToken()->getUser();
  696.                                     $customerMethodPaymentService->setMethodsByCustomer($customerLoginjson_decode(json_encode($postData), true));
  697.                                 }
  698.                             }
  699.                         }
  700.                     }
  701.                     $orderProduct $this->emitirBono($emmisionWebService$session$orderProduct$voucherData$productId$transactionId$bookingId);
  702.                     $twig 'aviatur_gift_voucher_payment_rejected_secure';
  703.                     break;
  704.                 case 3:// pendiente p2p
  705.                     $twig '' != $twig $twig 'aviatur_gift_voucher_payment_pending_secure';
  706.                     $orderProduct->setEmissiondata($bookingId);
  707.                     $orderProduct->setEmail(json_encode($voucherData));
  708.                     $orderProduct->setUpdatingdate(new \DateTime());
  709.                     $outputInfo $this->prepareOutputInfo();
  710.                     $orderProduct->setResume(json_encode($outputInfo));
  711.                     $retryCount 1;
  712.                     break;
  713.                 case 0:// error p2p
  714.                     $twig 'aviatur_gift_voucher_payment_error_secure';
  715.                     // no break
  716.                 case 2:// rechazada p2p
  717.                     $twig '' != $twig $twig 'aviatur_gift_voucher_payment_rejected_secure';
  718.                     break;
  719.                 case 1:// aprobado p2p
  720.                     $postData json_decode($session->get($transactionId.'[bono][detail_data_bono]'));
  721.                     if (isset($postData->PD->cusPOptSelected)) {
  722.                         if (isset($postData->PD->cusPOptSelectedStatus)) {
  723.                             if ('NOTVERIFIED' == $postData->PD->cusPOptSelectedStatus) {
  724.                                 $postData->PD->cusPOptSelectedStatus 'ACTIVE';
  725.                                 $customerLogin $tokenStorage->getToken()->getUser();
  726.                                 $customerMethodPaymentService->setMethodsByCustomer($customerLoginjson_decode(json_encode($postData), true));
  727.                             }
  728.                         }
  729.                     }
  730.                     if (isset($postData->PD->savePaymProc)) {
  731.                         $customerLogin $tokenStorage->getToken()->getUser();
  732.                         $customerMethodPaymentService->setMethodsByCustomer($customerLoginjson_decode(json_encode($postData), true));
  733.                     }
  734.                     $twig 'aviatur_gift_voucher_payment_success_secure';
  735.                     $orderProduct $this->emitirBono($emmisionWebService$session$orderProduct$voucherData$productId$transactionId$bookingId);
  736.                     break;
  737.             }
  738.             $em->persist($orderProduct);
  739.             $em->flush();
  740.             $session->set($transactionId.'[bono][retry]'$retryCount 1);
  741.             return $this->redirect($this->generateUrl($twig));
  742.         } else {
  743.             $orderProduct->setStatus('pending');
  744.             $em->persist($orderProduct);
  745.             $em->flush();
  746.             return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_gift_voucher_retry_secure'), '''No hay respuesta por parte del servicio de pago'));
  747.         }
  748.     }
  749.     public function generarBonofrontAction(ManagerRegistry $registryAviaturErrorHandler $aviaturErrorHandlerSessionInterface $sessionParameterBagInterface $parameterBagEmissionWebservice $emmisionWebService)
  750.     {
  751.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  752.         $em $registry->getManager();
  753.         $transactionId $session->get($transactionIdSessionName);
  754.         $detailInfo json_decode($session->get($transactionId.'[bono][detail_data_bono]'));
  755.         $orderProductCode $session->get($transactionId.'[bono][order]');
  756.         $productId str_replace('PN'''json_decode($orderProductCode)->products);
  757.         $orderProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  758.         $bookingId $this->generateRamdonCode();
  759.         $agency $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
  760.         $isFront $session->has('operatorId');
  761.         $additionalUserFront simplexml_load_string($session->get('front_user_additionals'));
  762.         $giftArray explode(','base64_decode($detailInfo->GV->giftSelected));
  763.         $giftVoucherValue 0;
  764.         $codeGift base64_decode($giftArray[1]);
  765.         $giftVoucherConfigObject $em->getRepository(\Aviatur\GiftVoucherBundle\Entity\ConfigGiftVoucherAgency::class)->findParamsByAgency($agency);
  766.         if (null == $giftVoucherConfigObject || (is_countable($giftVoucherConfigObject) ? count($giftVoucherConfigObject) : 0) == 0) {
  767.             return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_general_homepage'), '''No se encontró configuración para esta Agencia.'));
  768.         }
  769.         $giftVoucherConfig json_decode($giftVoucherConfigObject[0]['params'], true);
  770.         foreach ($giftVoucherConfig['fares'] as $giftVoucherFares) {
  771.             if ($giftVoucherFares['code'] == $codeGift) {
  772.                 $giftVoucherValue $giftVoucherFares['value'];
  773.             }
  774.         }
  775.         if (== $giftVoucherValue) {
  776.             $valueGift round(((int) (substr($giftArray[0], -3)) * 9) / 3);
  777.             if ($valueGift == $codeGift) {
  778.                 $giftVoucherValue = (int) substr($giftArray[0], 0, -3) - (int) $valueGift;
  779.             } else {
  780.                 return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_general_homepage'), '''1 No se encontro informacion del producto solicitado '));
  781.             }
  782.         }
  783.         $voucherData = [
  784.             'empresaId' => '10',
  785.             'productId' => $productId,
  786.             'bonoId' => $bookingId,
  787.             'ammount' => (float) $giftVoucherValue,
  788.             'currency' => 'COP',
  789.             'documentNumber' => $detailInfo->BD->doc_num,
  790.             'status' => 'EMT',
  791.             'documentType' => $detailInfo->BD->doc_type,
  792.             'name' => $detailInfo->BD->first_name.' '.$detailInfo->BD->last_name,
  793.             'email' => $additionalUserFront->CORREO_ELECTRONICO,
  794.             'phone' => $detailInfo->BD->phone,
  795.             'recipient_name' => $detailInfo->PI->first_name_1_1.' '.$detailInfo->PI->last_name_1_1,
  796.             'recipient_mail' => $detailInfo->PI->email_1_1,
  797.             'recipient_phone' => $detailInfo->CD->phone,
  798.             'recipient_document' => $detailInfo->PI->doc_num_1_1,
  799.         ];
  800.         $twig 'aviatur_gift_voucher_payment_success_secure';
  801.         $orderProduct $this->emitirBono($emmisionWebService$session$orderProduct$voucherData$productId$transactionId$bookingId);
  802.         $em->persist($orderProduct);
  803.         $em->flush();
  804.         return $this->redirect($this->generateUrl($twig));
  805.     }
  806.     public function pseCallbackAction(ManagerRegistry $registryPSEController $psePaymentControllerOrderController $orderControllerAviaturEncoder $aviaturEncoderTwigFolder $twigFolderAviaturErrorHandler $aviaturErrorHandlerSessionInterface $sessionParameterBagInterface $parameterBagEmissionWebservice $emmisionWebService)
  807.     {
  808.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  809.         $status null;
  810.         $twig null;
  811.         $em $registry->getManager();
  812.         if (true === $session->has($transactionIdSessionName)) {
  813.             $transactionId $session->get($transactionIdSessionName);
  814.             if (true === $session->has($transactionId.'[bono][order]')) {
  815.                 $orderProductCode $session->get($transactionId.'[bono][order]');
  816.                 $productId str_replace('PN'''json_decode($orderProductCode)->products);
  817.                 $orderProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  818.                 $agency $orderProduct->getOrder()->getAgency();
  819.                 $decodedRequest json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayrequest(), $orderProduct->getPublicKey()));
  820.                 $decodedResponse json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayresponse(), $orderProduct->getPublicKey()));
  821.                 $detailInfo json_decode($session->get($transactionId.'[bono][detail_data_bono]'));
  822.                 $bookingId $this->generateRamdonCode();
  823.                 $voucherData = [
  824.                     'empresaId' => '10',
  825.                     'productId' => $productId,
  826.                     'bonoId' => $bookingId,
  827.                     'ammount' => $decodedRequest->totalAmount,
  828.                     'currency' => 'COP',
  829.                     'documentNumber' => $orderProduct->getOrder()->getCustomer()->getDocumentnumber(),
  830.                     'status' => 'EMT',
  831.                     'documentType' => $orderProduct->getOrder()->getCustomer()->getDocumentType()->getExternalcode(),
  832.                     'name' => $orderProduct->getOrder()->getCustomer()->getFirstname().' '.$orderProduct->getOrder()->getCustomer()->getLastname(),
  833.                     'email' => $orderProduct->getOrder()->getCustomer()->getEmail(),
  834.                     'phone' => $orderProduct->getOrder()->getCustomer()->getPhone(),
  835.                     'recipient_name' => $detailInfo->PI->first_name_1_1.' '.$detailInfo->PI->last_name_1_1,
  836.                     'recipient_mail' => $detailInfo->PI->email_1_1,
  837.                     'recipient_phone' => $detailInfo->CD->phone,
  838.                     'recipient_document' => $detailInfo->PI->doc_num_1_1,
  839.                 ];
  840.                 $orderController->updatePaymentAction($orderProduct);
  841.                 if (isset($decodedResponse->createTransactionResult)) {
  842.                     $pseTransactionId $decodedResponse->createTransactionResult->transactionID;
  843.                     $paymentResponse $psePaymentController->pseCallbackAction($pseTransactionId);
  844.                     if (!isset($paymentResponse->error)) {
  845.                         $decodedResponse->getTransactionInformationResult $paymentResponse->getTransactionInformationResult;
  846.                         $orderProduct->setPayresponse($aviaturEncoder->AviaturEncode(json_encode($decodedResponse), $orderProduct->getPublicKey()));
  847.                         $orderProduct->setUpdatingdate(new \DateTime());
  848.                         $em->persist($orderProduct);
  849.                         $em->flush();
  850.                         $retryCount = (int) $session->get($transactionId.'[bono][retry]');
  851.                         if ('SUCCESS' == (string) $paymentResponse->getTransactionInformationResult->returnCode) {
  852.                             switch ((string) $paymentResponse->getTransactionInformationResult->transactionState) {
  853.                                 case 'OK':
  854.                                     $twig 'aviatur_gift_voucher_payment_success_secure';
  855.                                     $status 'approved';
  856.                                     break;
  857.                                 case 'PENDING':
  858.                                     $twig 'aviatur_gift_voucher_payment_pending_secure';
  859.                                     $status 'pending';
  860.                                     $orderProduct->setEmissiondata($bookingId);
  861.                                     $orderProduct->setEmail(json_encode($voucherData));
  862.                                     $outputInfo $this->prepareOutputInfo();
  863.                                     $orderProduct->setResume(json_encode($outputInfo));
  864.                                     break;
  865.                                 case 'NOT_AUTHORIZED':
  866.                                     $twig 'aviatur_gift_voucher_payment_error_secure';
  867.                                     $status 'rejected';
  868.                                     break;
  869.                                 case 'FAILED':
  870.                                     $twig 'aviatur_gift_voucher_payment_error_secure';
  871.                                     $status 'failed';
  872.                                     break;
  873.                             }
  874.                             $orderProduct->setStatus($status);
  875.                             $orderProduct->getOrder()->setStatus($status);
  876.                             $orderProduct->setUpdatingdate(new \DateTime());
  877.                             $orderProduct->getOrder()->setUpdatingdate(new \DateTime());
  878.                             $em->persist($orderProduct);
  879.                             $em->flush();
  880.                             if ('approved' == $status) {
  881.                                 $orderProduct $this->emitirBono($emmisionWebService$session$orderProduct$voucherData$productId$transactionId$bookingId);
  882.                             }
  883.                         } elseif ('FAIL_INVALIDTRAZABILITYCODE' == (string) $paymentResponse->getTransactionInformationResult->returnCode || 'FAIL_ACCESSDENIED' == $paymentResponse->getTransactionInformationResult->returnCode || 'FAIL_TIMEOUT' == $paymentResponse->getTransactionInformationResult->returnCode) {
  884.                             echo 'En este momento su #<referencia de factura> presenta un proceso de pago cuya transacción se encuentra
  885.         PENDIENTE de recibir información por parte de su entidad financiera, por favor espere
  886.         unos minutos y vuelva a consultar mas tarde para verificar sí su pago fue confirmado de
  887.         forma exitosa. Si desea mayor información sobre el estado actual de su operación puede
  888.         comunicarse a nuestras líneas de atención al cliente al teléfono XXXXXX o enviar
  889.         inquietudes al email mispagos@micomercio.com y pregunte por el estado de la
  890.         transacción <#CUS> .';
  891.                             $orderProduct->setEmissiondata('error');
  892.                             $orderProduct->setUpdatingdate(new \DateTime());
  893.                             $em->persist($orderProduct);
  894.                             $em->flush();
  895.                             $twig 'aviatur_gift_voucher_payment_error_secure';
  896.                         }
  897.                         $session->set($transactionId.'[bono][retry]'$retryCount 1);
  898.                         return $this->redirect($this->generateUrl($twig));
  899.                     } else {
  900.                         $decodedResponse->getTransactionInformationResult $paymentResponse;
  901.                         $orderProduct->setPayresponse($aviaturEncoder->AviaturEncode(json_encode($decodedResponse), $orderProduct->getPublicKey()));
  902.                         $orderProduct->setUpdatingdate(new \DateTime());
  903.                         $em->persist($orderProduct);
  904.                         $em->flush();
  905.                         return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''Ocurrió un error al consultar el estado de la transacción'));
  906.                     }
  907.                 } else {
  908.                     return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''No se encontró información de la transacción'));
  909.                 }
  910.             } else {
  911.                 return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''No se encontró orden asociada a este pago'));
  912.             }
  913.         } else {
  914.             return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''No se encontro identificador de la transacción'));
  915.         }
  916.     }
  917.     public function paymentOutputAction(ManagerRegistry $registry, \Swift_Mailer $mailerTwigFolder $twigFolderSessionInterface $sessionParameterBagInterface $parameterBag)
  918.     {
  919.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  920.         $em $registry->getManager();
  921.         $transactionId $session->get($transactionIdSessionName);
  922.         $orderProductCode $session->get($transactionId.'[bono][order]');
  923.         $productId str_replace('PN'''json_decode($orderProductCode)->products);
  924.         $orderProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  925.         $agencyFolder $twigFolder->twigFlux();
  926.         $isFront $session->has('operatorId');
  927.         $outputInfo $this->prepareOutputInfo();
  928.         $emailCustomerBody $outputInfo['emailCustomerBody'];
  929.         $resumeData $outputInfo['resumeData'];
  930.         $paymentResume $resumeData['transactionPayments'][0];
  931.         $giftVoucherConfigObject $em->getRepository(\Aviatur\GiftVoucherBundle\Entity\ConfigGiftVoucherAgency::class)->findBy(['agency' => $orderProduct->getOrder()->getAgency()]);
  932.         $urlResume $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/GiftVoucher/Default/resume.html.twig');
  933.         if ($isFront) {
  934.             $paymentResume['transaction_state'] = 1;
  935.         }
  936.         $resumeMessage $this->render($urlResume$resumeData);
  937.         if (== $paymentResume['transaction_state']) {
  938.             $emailCustomMessage $this->renderView($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/GiftVoucher/Default/email_giftVoucher.html.twig'), ['emailBodyContent' => $emailCustomerBody]);
  939.             $orderProduct->setEmail($emailCustomMessage);
  940.             $toAdminMails explode(';'$giftVoucherConfigObject[0]->getMails());
  941.             $rejectAlertText '';
  942.             if (== $paymentResume['transaction_state_cyber']) {//In case Rejected Cybersource send mail to administratos Aviatur
  943.                 $sendVoucherTo $toAdminMails;
  944.                 $emailCustomerBody['cyberReject'] = '<STRONG>ATENCIÓN!!!<STRONG> El Pago fué exitoso pero la transacción fué Rechazada por Cybersource. Por favor confirmar con el Departamento de Control Pago Electrónico la validez de la misma y en caso positivo realizar envío del Bono de Regalo al cliente.';
  945.                 $rejectAlertText ' - **RECHAZO CYBERSOURCE**';
  946.             } else {
  947.                 $sendVoucherTo $emailCustomerBody['customerContact']['email'];
  948.             }
  949.             $message = (new \Swift_Message())
  950.                     ->setContentType('text/html')
  951.                     ->setFrom($session->get('emailNoReply'))
  952.                     ->setTo($sendVoucherTo)
  953.                     ->setBCC('notificacionessitioweb@aviatur.com')
  954.                     ->setSubject($session->get('agencyShortName').' - Bono de Regalo')
  955.                     ->setBody($emailCustomMessage);
  956.             $mailer->send($message);
  957.             $emailCustomerBody['admin'] = true;
  958.             $emailCustomerBody['pn_id'] = 'PN'.$productId;
  959.             $emailCustomerBody['messageText'] = 'Se ha realizado una compra de un bono de regalo virtual con los siguientes datos,<br>
  960.                                                 favor hacer las verificaciones correspondientes en sus respectivos departamentos.';
  961.             $emailAdminMessage $this->renderView($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/GiftVoucher/Default/email_giftVoucher.html.twig'), ['emailBodyContent' => $emailCustomerBody]);
  962.             $messageAdmin = (new \Swift_Message())
  963.                     ->setContentType('text/html')
  964.                     ->setFrom($session->get('emailNoReply'))
  965.                     ->setTo($toAdminMails)
  966.                     ->setBCC(['notificacionessitioweb@aviatur.com''i_orduela@aviatur.com'])
  967.                     ->setSubject($session->get('agencyShortName').' - Se ha generado un Bono de Regalo'.$rejectAlertText)
  968.                     ->setBody($emailAdminMessage);
  969.             $mailer->send($messageAdmin);
  970.             $orderProduct->setResume($resumeMessage);
  971.             $em->persist($orderProduct);
  972.             $em->flush();
  973.         }
  974.         return $resumeMessage;
  975.     }
  976.     private function prepareOutputInfo(ManagerRegistry $registryTwigFolder $twigFolderAviaturEncoder $aviaturEncoderAviaturErrorHandler $aviaturErrorHandlerSessionInterface $sessionParameterBagInterface $parameterBag)
  977.     {
  978.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  979.         $clientFranquice = [];
  980.         $paymentResume = [];
  981.         $infos = [];
  982.         $em $registry->getManager();
  983.         $agency $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
  984.         $transactionId $session->get($transactionIdSessionName);
  985.         $detailInfo json_decode($session->get($transactionId.'[bono][detail_data_bono]'));
  986.         $orderProductCode $session->get($transactionId.'[bono][order]');
  987.         $productId str_replace('PN'''json_decode($orderProductCode)->products);
  988.         $orderProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  989.         $isFront $session->has('operatorId');
  990.         $opRequestInitial json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayrequest(), $orderProduct->getPublicKey()));
  991.         $opRequest $opRequestInitial->multi_transaction_hotel ?? $opRequestInitial;
  992.         $opResponse json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayResponse(), $orderProduct->getPublicKey()));
  993.         if (isset($opResponse->x_franchise) && ('' != $opResponse->x_franchise)) {
  994.             $franquiceCode str_replace(['CR_''RM_''CDNSA'], ['''''CS'], $opResponse->x_franchise);
  995.             $clientFranquice $em->getRepository(\Aviatur\GeneralBundle\Entity\Card::class)->findOneByPaymentgatewaycode($franquiceCode);
  996.         } else {
  997.             $clientFranquice['description'] = 'error';
  998.         }
  999.         $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($detailInfo->BD->id);
  1000.         if ((null != $opRequest) && (null != $opResponse)) {
  1001.             if (isset($opResponse->x_description)) {
  1002.                 $paymentResume = [
  1003.                     'transaction_state' => $opResponse->x_response_code,
  1004.                     'ta_transaction_state' => $opResponse->x_ta_response_code,
  1005.                     'id' => $orderProduct->getBooking(),
  1006.                     'id_context' => $opRequest->x_invoice_num,
  1007.                     'total_amount' => $opResponse->x_amount,
  1008.                     'currency' => $opResponse->x_bank_currency,
  1009.                     'amount' => != $opRequest->x_amount_base $opRequest->x_amount_base $opResponse->x_amount,
  1010.                     'iva' => $opRequest->x_tax,
  1011.                     'ip_address' => $opRequest->x_customer_ip,
  1012.                     'bank_name' => $opResponse->x_bank_name,
  1013.                     'client_franquice' => ['description' => (is_object($clientFranquice) ? $clientFranquice->getDescription() : $clientFranquice['description'])],
  1014.                     'cuotas' => $opRequest->x_differed,
  1015.                     'card_num' => '************'.substr($opRequest->x_card_numstrlen($opRequest->x_card_num) - 4),
  1016.                     'reference' => $opResponse->x_transaction_id,
  1017.                     'auth' => $opResponse->x_approval_code,
  1018.                     'transaction_date' => $opResponse->x_transaction_date,
  1019.                     'description' => $opResponse->x_description,
  1020.                     'reason_code' => $opResponse->x_response_reason_code,
  1021.                     'reason_description' => $opResponse->x_response_reason_text,
  1022.                     'client_names' => $opResponse->x_first_name.' '.$opResponse->x_last_name,
  1023.                     'client_email' => $opResponse->x_email,
  1024.                 ];
  1025.             } elseif (isset($opRequest->dataTransf)) {
  1026.                 if (isset($opRequest->notificationRequest->{'urn:OperationActivityNotifiedRequest'})):
  1027.                     $state $opRequest->notificationRequest->{'urn:OperationActivityNotifiedRequest'}->{'urn:ListOfOperationsActivityNotified'}->{'urn1:ConfirmOperation'}->{'urn1:OperationStatus'};
  1028.                 if (102 == $state):
  1029.                         $state 1;
  1030.                 $reason_description 'SafetyPay recibe la confirmación del pago de un Banco Asociado'; elseif (101 == $state):
  1031.                         $state 2;
  1032.                 $reason_description 'Transacción creada';
  1033.                 endif;
  1034.                 $paymentResume = [
  1035.                         'transaction_state' => $state,
  1036.                         'id' => $orderProduct->getBooking(),
  1037.                         'currency' => $opRequest->dataTransf->x_currency,
  1038.                         'total_amount' => $opRequest->tokenRequest->{'urn:ExpressTokenRequest'}->{'urn:Amount'},
  1039.                         'amount' => null,
  1040.                         'iva' => null,
  1041.                         'ip_address' => $opRequest->dataTransf->dirIp,
  1042.                         'airport_tax' => null,
  1043.                         'reference' => $opRequest->tokenRequest->{'urn:ExpressTokenRequest'}->{'urn:MerchantSalesID'},
  1044.                         'auth' => $opRequest->notificationRequest->{'urn:OperationActivityNotifiedRequest'}->{'urn:ListOfOperationsActivityNotified'}->{'urn1:ConfirmOperation'}->{'urn1:OperationID'},
  1045.                         'transaction_date' => $opResponse->payResponse->OperationResponse->ResponseDateTime,
  1046.                         'description' => $opRequest->dataTransf->x_description,
  1047.                         'reason_code' => $opRequest->notificationRequest->{'urn:OperationActivityNotifiedRequest'}->{'urn:ListOfOperationsActivityNotified'}->{'urn1:ConfirmOperation'}->{'urn1:OperationStatus'},
  1048.                         'reason_description' => $reason_description,
  1049.                         'client_names' => $opRequest->dataTransf->x_first_name.' '.$opRequest->dataTransf->x_last_name,
  1050.                         'client_email' => $opRequest->dataTransf->x_email,
  1051.                         'x_payment_data' => $opRequest->dataTransf->x_payment_data,
  1052.                         'client_franquice' => ['description' => 'SafetyPay'],
  1053.                     ]; else:
  1054.                     $paymentResume = [
  1055.                         'transaction_state' => 2,
  1056.                         'id' => $orderProduct->getBooking(),
  1057.                         'currency' => $opRequest->dataTransf->x_currency,
  1058.                         'total_amount' => $opRequest->dataTransf->x_total_amount,
  1059.                         'amount' => null,
  1060.                         'iva' => null,
  1061.                         'ip_address' => $opRequest->dataTransf->dirIp,
  1062.                         'airport_tax' => null,
  1063.                         'reference' => $opRequest->dataTransf->x_reference,
  1064.                         'auth' => null,
  1065.                         'transaction_date' => $opRequest->tokenRequest->{'urn:ExpressTokenRequest'}->{'urn:RequestDateTime'},
  1066.                         'description' => $opRequest->dataTransf->x_description,
  1067.                         'reason_code' => 101,
  1068.                         'reason_description' => 'Transacción creada',
  1069.                         'x_payment_data' => $opRequest->dataTransf->x_payment_data,
  1070.                         'client_names' => $opRequest->dataTransf->x_first_name.' '.$opRequest->dataTransf->x_last_name,
  1071.                         'client_email' => $opRequest->dataTransf->x_email,
  1072.                     ];
  1073.                 endif;
  1074.                 if ('baloto' == $opRequest->dataTransf->x_payment_data) {
  1075.                     $paymentResume['transaction_state'] = 3;
  1076.                 }
  1077.             } elseif (isset($opRequest->infoCash)) {
  1078.                 $paymentResume = [
  1079.                     'transaction_state' => 2,
  1080.                     'id' => $orderProduct->getBooking(),
  1081.                     'id_context' => $opRequest->infoCash->x_reference,
  1082.                     'currency' => $opRequest->infoCash->x_currency,
  1083.                     'total_amount' => $opRequest->infoCash->x_total_amount,
  1084.                     'client_franquice' => ['description' => 'Efectivo'],
  1085.                     'amount' => null,
  1086.                     'iva' => null,
  1087.                     'ip_address' => $opRequest->infoCash->dirIp,
  1088.                     'airport_tax' => null,
  1089.                     'reference' => $opRequest->infoCash->x_reference,
  1090.                     'auth' => null,
  1091.                     'transaction_date' => $opRequest->infoCash->x_fechavigencia,
  1092.                     'description' => $opRequest->infoCash->x_description,
  1093.                     'reason_code' => 101,
  1094.                     'reason_description' => 'Transacción creada',
  1095.                     'client_names' => $opRequest->infoCash->x_first_name.' '.$opRequest->infoCash->x_last_name,
  1096.                     'client_email' => $opRequest->infoCash->x_email,
  1097.                     'fecha_vigencia' => $opRequest->infoCash->x_fechavigencia,
  1098.                 ];
  1099.                 $cash_result json_decode($session->get($transactionId.'[bono][cash_result]'));
  1100.                 $paymentResume['transaction_state'] = 3;
  1101.                 if ('' == $cash_result) {
  1102.                     $paymentResume['transaction_state'] = 2;
  1103.                 }
  1104.             } else {
  1105.                 $bank_info $em->getRepository(\Aviatur\PaymentBundle\Entity\PseBank::class)->findOneByCode($opRequest->bankCode);
  1106.                 $bank_name $bank_info->getName();
  1107.                 $clientFranquice['description'] = 'PSE';
  1108.                 $paymentResume = [
  1109.                     'transaction_state' => $opResponse->getTransactionInformationResult->responseCode,
  1110.                     'id' => $orderProduct->getBooking(),
  1111.                     'id_context' => $opRequest->reference,
  1112.                     'currency' => $opRequest->currency,
  1113.                     'total_amount' => $opRequest->totalAmount,
  1114.                     'amount' => $opRequest->devolutionBase,
  1115.                     'iva' => $opRequest->taxAmount,
  1116.                     'ip_address' => $opRequest->ipAddress,
  1117.                     'bank_name' => $bank_name,
  1118.                     'client_franquice' => $clientFranquice,
  1119.                     'reference' => $opResponse->createTransactionResult->transactionID,
  1120.                     'auth' => $opResponse->getTransactionInformationResult->trazabilityCode,
  1121.                     'transaction_date' => $opResponse->getTransactionInformationResult->bankProcessDate,
  1122.                     'description' => $opRequest->description,
  1123.                     'reason_code' => $opResponse->getTransactionInformationResult->responseReasonCode,
  1124.                     'reason_description' => $opResponse->getTransactionInformationResult->responseReasonText,
  1125.                     'client_names' => $opRequest->payer->firstName.' '.$opRequest->payer->lastName,
  1126.                     'client_email' => $opRequest->payer->emailAddress,
  1127.                 ];
  1128.             }
  1129.         } else {
  1130.             $customer null;
  1131.             $paymentResume['id'] = $orderProduct->getBooking();
  1132.         }
  1133.         $paymentResume['transaction_state_cyber'] = $opResponse->x_response_code_cyber ?? '1';
  1134.         $passengerData $detailInfo->PI;
  1135.         if (false !== strpos($detailInfo->BD->first_name'***')) {
  1136.             $facturationResume = [
  1137.                 'customer_names' => $customer->getFirstname().' '.$customer->getLastname(),
  1138.                 'customer_address' => $customer->getAddress(),
  1139.                 'customer_doc_num' => $customer->getDocumentnumber(),
  1140.                 'customer_phone' => $customer->getPhone(),
  1141.                 'customer_email' => $customer->getEmail(),
  1142.             ];
  1143.         } else {
  1144.             $facturationResume = [
  1145.                 'customer_names' => $detailInfo->BD->first_name.' '.$detailInfo->BD->last_name,
  1146.                 'customer_address' => $detailInfo->BD->address ?? null,
  1147.                 'customer_doc_num' => $detailInfo->BD->doc_num,
  1148.                 'customer_phone' => $detailInfo->BD->phone,
  1149.                 'customer_email' => $detailInfo->BD->email ?? null,
  1150.             ];
  1151.         }
  1152.         if (false !== strpos($passengerData->first_name_1_1'***')) {
  1153.             $passengerData->first_name_1_1 $customer->getFirstname();
  1154.             $passengerData->last_name_1_1 $customer->getLastname();
  1155.         }
  1156.         $clientFranquice '';
  1157.         $retryCount = (int) $session->get($transactionId.'[bono][retry]');
  1158.         $travelers = [];
  1159.         for ($i 1$i <= $passengerData->person_count_1; ++$i) {
  1160.             $first_name 'first_name_1_'.$i;
  1161.             $last_name 'last_name_1_'.$i;
  1162.             $type 'passanger_type_1_'.$i;
  1163.             $mail 'email_1_'.$i;
  1164.             $document_type 'doc_type_1_'.$i;
  1165.             $document_number 'doc_num_1_'.$i;
  1166.             $travelers[] = [
  1167.                 'typeCode' => $passengerData->$type,
  1168.                 'GivenName' => $passengerData->$first_name,
  1169.                 'Surname' => $passengerData->$last_name,
  1170.                 'Email' => $passengerData->$mail,
  1171.                 'Phone' => $detailInfo->CD->phone,
  1172.                 'Doc_type' => $passengerData->$document_type,
  1173.                 'Doc_number' => $passengerData->$document_number,
  1174.             ];
  1175.         }
  1176.         $infos[0] = [
  1177.             'travelers' => $travelers,
  1178.             'BookingCode' => $orderProduct->getBooking(),
  1179.         ];
  1180.         $agencyData = [
  1181.             'agency_name' => $agency->getName(),
  1182.             'agency_nit' => $agency->getNit(),
  1183.             'agency_phone' => $agency->getPhone(),
  1184.             'agency_email' => $agency->getMailContact(),
  1185.         ];
  1186.         $resumeData = [
  1187.             'retryCount' => $retryCount,
  1188.             'transactionPayments' => ['0' => $paymentResume],
  1189.             'transactionInfo' => ['facturationResume' => $facturationResume],
  1190.             'agencyData' => $agencyData,
  1191.             'backDetail' => $this->generateUrl('aviatur_gift_voucher_retry_secure'),
  1192.             'infos' => $infos,
  1193.         ];
  1194.         if ($session->has($transactionId.'[bono][emission][error]')) {
  1195.             $resumeData['emission_error'] = true;
  1196.         }
  1197. //        $emailData = array(
  1198. //            'paymentResume' => $paymentResume,
  1199. //            'travelers' => $travelers,
  1200. //            'agencyData' => $agencyData
  1201. //        );
  1202.         $customerContact = [
  1203.             'fullName' => $travelers[0]['GivenName'].' '.$travelers[0]['Surname'],
  1204.             'email' => mb_strtolower($travelers[0]['Email']),
  1205.             'phone' => $travelers[0]['Phone'],
  1206.             'document' => $travelers[0]['Doc_type'].' '.$travelers[0]['Doc_number'],
  1207.         ];
  1208.         $sponsor_info = [
  1209.             'name' => $facturationResume['customer_names'],
  1210.             'document' => $facturationResume['customer_doc_num'],
  1211.         ];
  1212.         if ($isFront) {
  1213.             $giftArray explode(','base64_decode($detailInfo->GV->giftSelected));
  1214.             $giftVoucherValue 0;
  1215.             $codeGift base64_decode($giftArray[1]);
  1216.             $giftVoucherConfigObject $em->getRepository(\Aviatur\GiftVoucherBundle\Entity\ConfigGiftVoucherAgency::class)->findParamsByAgency($agency);
  1217.             if (null == $giftVoucherConfigObject || (is_countable($giftVoucherConfigObject) ? count($giftVoucherConfigObject) : 0) == 0) {
  1218.                 return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_general_homepage'), '''No se encontró configuración para esta Agencia.'));
  1219.             }
  1220.             $giftVoucherConfig json_decode($giftVoucherConfigObject[0]['params'], true);
  1221.             foreach ($giftVoucherConfig['fares'] as $giftVoucherFares) {
  1222.                 if ($giftVoucherFares['code'] == $codeGift) {
  1223.                     $giftVoucherValue $giftVoucherFares['value'];
  1224.                 }
  1225.             }
  1226.             if (== $giftVoucherValue) {
  1227.                 $valueGift round(((int) (substr($giftArray[0], -3)) * 9) / 3);
  1228.                 if ($valueGift == $codeGift) {
  1229.                     $giftVoucherValue = (int) substr($giftArray[0], 0, -3) - (int) $valueGift;
  1230.                 } else {
  1231.                     return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_general_homepage'), '''1 No se encontro informacion del producto solicitado '));
  1232.                 }
  1233.             }
  1234.             $paymentResume['total_amount'] = $giftVoucherValue;
  1235.         }
  1236.         $emailCustomerBody = [
  1237.             'title' => 'BONO DE REGALO',
  1238.             'voucherCode' => $orderProduct->getBooking(),
  1239.             'voucherAmount' => $paymentResume['total_amount'],
  1240.             'sponsor' => $sponsor_info,
  1241.             'customerContact' => $customerContact,
  1242.             'messageText' => 'Acércate a cualquier oficina de Aviatur en el país y redime el valor total o parcial cargado en el Bono de Regalo en tiquetes, hoteles, planes turísticos y demás servicios ofrecidos por Aviatur.
  1243.                 ',
  1244.             'mainImage' => $twigFolder->absoluteAssetsUrl($agency->getAssetsFolder()).'img/header/aviatur_logo.png',
  1245.         ];
  1246.         return [
  1247.             'emailCustomerBody' => $emailCustomerBody,
  1248.             'resumeData' => $resumeData,
  1249.         ];
  1250.     }
  1251.     public function emitirBono(EmissionWebservice $emissionWebserviceSessionInterface $session$orderProduct$voucherData$productId$transactionId$bookingId)
  1252.     {
  1253.         $sendVoucherStatus $emissionWebservice->callServiceEmission('purchaseBonus'$voucherData$productId);
  1254.         if (isset($sendVoucherStatus['error'])) {
  1255.             $session->set($transactionId.'[bono][emission][error]'true);
  1256.             $orderProduct->setEmissiondata($bookingId.'-EmissionError');
  1257.         } else {
  1258.             $orderProduct->setEmissiondata($bookingId.'-'.$sendVoucherStatus->purchaseBonusResult);
  1259.         }
  1260.         $orderProduct->setBooking($bookingId);
  1261.         return $orderProduct;
  1262.     }
  1263.     public function generateRamdonCode($length 10)
  1264.     {
  1265.         $characters '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  1266.         $charactersLength strlen($characters);
  1267.         $randomString '';
  1268.         for ($i 0$i $length; ++$i) {
  1269.             $randomString .= $characters[random_int(0$charactersLength 1)];
  1270.         }
  1271.         $randomCRC crc32(date('Y-m-d H:i:s'));
  1272.         $randomCode substr($randomString05).substr($randomCRC15);
  1273.         return $randomCode;
  1274.     }
  1275. }