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

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