src/Controller/PaymentController.php line 363

Open in your IDE?
  1. <?php
  2. /*
  3.  * The Payment controller contains methods for the following payment gateways:
  4.  * BarclaysSmart Pay - http://www.barclaycard.com/smartpay/documentation/pdf/SmartPay_HPP_IntegrationGuide.pdf
  5.  * Authorize.net - https://developer.authorize.net/guides/DPM/wwhelp/wwhimpl/js/html/wwhelp.htm
  6.  */
  7. namespace App\Controller;
  8. use Doctrine\Persistence\ManagerRegistry;
  9. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
  10. use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
  11. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  12. use Symfony\Bridge\Twig\Mime\WrappedTemplatedEmail;
  13. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  14. use Symfony\Component\HttpFoundation\RedirectResponse;
  15. use Symfony\Component\HttpFoundation\Request;
  16. use Symfony\Component\HttpFoundation\Response;
  17. use Symfony\Component\Mailer\Mailer;
  18. use Symfony\Component\Mailer\MailerInterface;
  19. use Symfony\Component\Mailer\Transport;
  20. use Symfony\Component\Mime\Email;
  21. use Symfony\Component\Routing\Annotation\Route;
  22. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  23. use Symfony\Contracts\Translation\TranslatorInterface;
  24. use Psr\Log\LoggerInterface;
  25. use Twig\Environment;
  26. use App\Entity\Booking as Booking;
  27. class PaymentController extends AbstractController
  28. {
  29.     private $loggedUser;
  30.     
  31.     public function __construct(private ManagerRegistry $doctrine, private LoggerInterface $logger, private TranslatorInterface $trans, private MailerInterface $mailer, private Environment $twig)
  32.     {
  33.         
  34.     }
  35.     #[Route('/customer/booking-confirmation/{ref}'name'bookingLink')]
  36.     public function confirmAction($ref)
  37.     {
  38.         $em $this->doctrine->getManager();
  39.         $booking $this->decodeRef(urldecode($ref));
  40.         $this->loggedUser $this->getUser();
  41.         $this->logger->info('Confirm booking for ref '.$ref);
  42.         
  43.         if ($booking)
  44.         {
  45.             $this->logger->info('Found booking Id: '.$booking->getBookingid());
  46.             $paid false;
  47.             $payment $this->getPayment($em$booking$paid);
  48.             $this->logger->info("paid: ".$paid);
  49.             
  50.             if (!$payment)
  51.             {
  52.                 $payment = new Payment();
  53.                 $payment->setPaymentgateway($booking->getBookingoffice()->getPaymentgateway());
  54.                 $payment->setBooking($booking);
  55.                 $payment->setUpdated( new \DateTime() );
  56.                 $em->persist($payment);
  57.                 $em->flush();
  58.                 $paymentArray $em->getRepository('App\Entity\Payment')->findByBooking($booking->getBookingid());
  59.                 $payment array_pop($paymentArray); 
  60.             }
  61.             else if ($paid)
  62.             {
  63.                 $redirect $this->generateUrl('successPayment', array('payment' => $this->createPaymentRef($payment)), UrlGeneratorInterface::ABSOLUTE_URL);
  64.                 return new RedirectResponse($redirect);
  65.             }
  66.             $paymentTemplate $booking->getBookingoffice()->getPaymentgateway()->getTemplate();
  67.             $this->logger->info('paymentTemplate: '.$paymentTemplate);
  68.             $func 'appendData_'.$paymentTemplate;
  69.             $this->logger->info("Looking for appendData func: ".$func);
  70.             
  71.             if (method_exists($this$func))
  72.                 $data $this->$func($booking$payment);
  73.             else 
  74.                 $data = array();
  75.             
  76.             $this->logger->info('Got payment Id: '.$payment->getPaymentid());
  77.             
  78.             $data['bookingRef'] =     $ref;
  79.             $data['booking']    =    $booking;
  80.             $data['payment']    =    $payment;
  81.             $data['user']        =    $this->loggedUser;
  82.             $data['resURL']        =    $this->generateURL('processBooking', array('gateway' => $payment->getPaymentgateway()->getPaymentgatewayid()), UrlGeneratorInterface::ABSOLUTE_URL);
  83.             $data['paid']        =    $paid;
  84.             $data['footer']     =     'booking.confirmation.footer.'.$paymentTemplate;
  85.             $data['template']    =     $paymentTemplate;
  86.             
  87.             $response             =     $this->render('booking/confirm.html.twig'$data);
  88.             $date                 =     new \DateTime();  // Set expire date to +2 seconds to prevent caching
  89.             $date->modify('+2 seconds');
  90.             $response->setExpires($date);
  91.             
  92.             return $response;
  93.         } 
  94.         else 
  95.             return $this->render('booking/notfound.html.twig', array("user" => $this->loggedUser));
  96.     }
  97.     #[Route('/customer/payment-failure/{payment}'name'failurePayment')]
  98.     public function failureAction($paymentRequest $request)
  99.     {
  100.         $payment $this->decodePaymentRef($payment);
  101.         if ($payment)
  102.         {
  103.             $notificationData explode('\n'$payment->getNotification());
  104.             $this->logger->info('$notificationData: '.end($notificationData));
  105.             $notificationData json_decode(end($notificationData));
  106.             return $this->render('payment/failure.html.twig', array('payment' => $payment'failureReason' => $notificationData->code.': '.$notificationData->status));
  107.         }
  108.         else
  109.             return $this->render('booking/notfound.html.twig', array("user"=>$this->loggedUser ));
  110.     }
  111.     #[Route('/customer/worldpay/getRedirectUrl/{ref}'name'getWorldpayRedirectUrl')]
  112.     public function getWorldpayRedirectUrlAction($ref)
  113.     {
  114.         //BE 190702: this is for Worldpay XML payments only
  115.         $em $this->doctrine->getManager();
  116.         $booking $this->decodeRef(urldecode($ref));
  117.         $this->loggedUser $this->getUser();        
  118.         $this->logger->info("getRedirectUrlAction for ref ".$ref);
  119.         if ($booking)
  120.         {
  121.             $this->logger->info("Found booking Id: ".$booking->getBookingid());
  122.             $paid false;
  123.             $payment $this->getPayment($em$booking$paid);
  124.             $this->logger->info("Found payment Id: ".$payment->getPaymentid());
  125.             $office $booking->getBookingoffice();
  126.             //$data = $this->appendData_worldpay($booking, $payment);
  127.             
  128.             $cost number_format($booking->getTotalprice(), 2'''');
  129.             $currency $booking->getBookingcurrency()->getCode();
  130.             $officeSalt $office->getMerchantsalt();
  131.             $merchantCode $this->decrypt($office->getMerchantcode(), $officeSalt).$currency;
  132.             //$merchantCode = $office->getMerchantcode().$currency;
  133.             $xml '<?xml version="1.0" encoding="UTF-8"?>
  134.             <!DOCTYPE paymentService PUBLIC "-//Worldpay//DTD Worldpay PaymentService v1//EN" "http://dtd.worldpay.com/paymentService_v1.dtd">
  135.             <paymentService version="1.4" merchantCode="'.$merchantCode.'">
  136.                <submit>
  137.                   <order orderCode="'.$payment->getPaymentid().'" installationId="1356990">
  138.                      <description>'.$booking->__toString().'</description>
  139.                      <amount currencyCode="'.$currency.'" exponent="2" value="'.$cost.'" />
  140.                      <orderContent><![CDATA[]]></orderContent>
  141.                      <paymentMethodMask>
  142.                         <include code="ALL" />
  143.                      </paymentMethodMask>
  144.                      <shopper>
  145.                         <shopperEmailAddress>'.$booking->getCustomer()->getEmail().'</shopperEmailAddress>
  146.                      </shopper>
  147.                      <billingAddress>
  148.                         <address>
  149.                            <address1>'.$booking->getCustomer()->getAddress().'</address1>
  150.                            <address2></address2>
  151.                            <address3></address3>
  152.                            <postalCode>'.$booking->getCustomer()->getPostcode().'</postalCode>
  153.                            <city>'.$booking->getCustomer()->getCity().'</city>
  154.                            <state>'.$booking->getCustomer()->getState().'</state>
  155.                            <countryCode>'.$booking->getCustomer()->getCustomercountry()->getCountry2Code().'</countryCode>
  156.                         </address>
  157.                      </billingAddress>
  158.                   </order>
  159.                </submit>
  160.             </paymentService>';
  161.             $this->logger->info("Xml: ".$xml);
  162.             $username $merchantCode;//$this->decrypt($office->getMerchantusername(), $officeSalt);
  163.             $pwd $this->decrypt($office->getMerchantpassword(), $officeSalt);
  164.             $test_mode $this->getParameter('app.worldpayxml_test_mode') == 'TRUE';
  165.             $basicAuth $username ':' $pwd;
  166.             //$this->logger->info("Using Auth: ".$basicAuth);
  167.             $basicAuthBase64 base64_encode($basicAuth);
  168.             $basicAuthUrlEncoded urlencode($username) . ":" urlencode($pwd);
  169.             
  170.             if ($test_mode)
  171.                 $url "https://secure-test.worldpay.com/jsp/merchant/xml/paymentService.jsp";
  172.             else
  173.                 $url "https://secure.worldpay.com/jsp/merchant/xml/paymentService.jsp";
  174.             
  175.             $this->logger->info("Using Url: ".$url);
  176.             //$this->logger->info("Using Url: ".str_replace($basicAuth, "user:pwd", $url));            
  177.             
  178.             $ch curl_init();            
  179.             curl_setopt($chCURLOPT_HTTPAUTHCURLAUTH_BASIC);
  180.             curl_setopt($chCURLOPT_USERPWD,  $basicAuth);
  181.             //curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml', 'Authorization: ' . $basicAuthBase64));
  182.             
  183.             curl_setopt($chCURLOPT_HTTPHEADER, array('Content-Type: text/xml'));            
  184.             curl_setopt($chCURLOPT_URL$url);
  185.             curl_setopt($chCURLOPT_POSTtrue);
  186.             curl_setopt($chCURLOPT_POSTFIELDS$xml);
  187.             curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  188.             curl_setopt($chCURLOPT_CONNECTTIMEOUT300);
  189.             $response curl_exec($ch);
  190.             
  191.             if ($response == false)
  192.             {
  193.                 $this->logger->error('Error code: '.curl_error($ch));
  194.                 $url $this->generateUrl('failurePayment', array('payment'=>$this->createPaymentRef($payment)), UrlGeneratorInterface::ABSOLUTE_URL);
  195.                 $err = array('date' => date('Y-m-d H:i:s'),'code' => 999'status' => 'XML Response empty - contact Support');
  196.                 $payment->setNotification($payment->getNotification().'\n'.json_encode($err));
  197.                 $em->persist($payment);
  198.                 $em->flush();
  199.                     
  200.                 $this->mailSalesFailure($payment);
  201.                 //$this->logger->info("failurePayment: ".$serializedData);
  202.                 return new RedirectResponse($url);
  203.              }
  204.              else
  205.              {
  206.                 $this->logger->info("response: ".$response);
  207.                 $responseXml simplexml_load_string($response);
  208.                 //$this->logger->info("responseXml: ".print_r($responseXml, true));
  209.                 
  210.                 if (property_exists($responseXml->reply'error') || strpos($response'<html') !== false)
  211.                 {
  212.                     $url $this->generateUrl('failurePayment', array('payment'=>$this->createPaymentRef($payment)), UrlGeneratorInterface::ABSOLUTE_URL);
  213.                     if (property_exists($responseXml->reply'error'))
  214.                     {
  215.                         $code = (int)$responseXml->reply->error['code'];
  216.                         $error = (string)$responseXml->reply->error;
  217.                         if ($error == 'Order has already been paid')
  218.                             $status $error;
  219.                         else
  220.                             $status 'There was an unknown problem with the gateway - Contact Support, and give them this info: '.(string)$responseXml->reply->error;
  221.                     }
  222.                     else if (strpos($response'<html') !== false && strpos($response'Status: 401') !== false)
  223.                     {
  224.                         $code '401';
  225.                         $status 'There was an authentication problem with the gateway - contact Support, and give them this info: Status 401: Authentication Problem';
  226.                     }
  227.                     else
  228.                     {
  229.                         $code '?';
  230.                         $status 'There was an unknown problem with the gateway - Contact Support, and give them this info: '.htmlentities($response);
  231.                     }
  232.                     
  233.                     $err = array('date' => date('Y-m-d H:i:s'), 'code' => $code'status' => $status);
  234.                     $payment->setNotification($payment->getNotification().'\n'.json_encode($err));
  235.                     $em->persist($payment);
  236.                     $em->flush();
  237.                     
  238.                     $this->mailSalesFailure($payment);
  239.                     //$this->logger->info("failurePayment: ".$serializedData);
  240.                     return new RedirectResponse($url);
  241.                     
  242.                 }
  243.                 else if (property_exists($responseXml->reply'orderStatus') && property_exists($responseXml->reply->orderStatus'reference'))
  244.                 {
  245.                     $refUrl = (string)$responseXml->reply->orderStatus->reference[0];
  246.                     $this->logger->info("reference: ".$refUrl);
  247.                     //$this->logger->info("reference: ".print_r($refUrl, true));
  248.                     //$this->logger->info("reference type: ".gettype($refUrl));
  249.                     //return $this->redirect($refUrl);
  250.                     
  251.                     $successURL    urlencode($this->generateURL("processWorldpay", array("pid" => $payment->getPaymentID() ), UrlGeneratorInterface::ABSOLUTE_URL));
  252.                     $refUrl .= '&successURL='.$successURL.'&failureURL='.$successURL.'&cancelURL='.$successURL.'&errorURL='.$successURL;
  253.                     $this->logger->info("reference: ".$refUrl);
  254.                     return new RedirectResponse($refUrl);
  255.                 }
  256.             }
  257.             
  258.             curl_close($ch);
  259.         }
  260.         else
  261.             $this->logger->info("No booking found!");
  262.     }
  263.     public function paymentNotificationAction($templateRequest $request)
  264.     {
  265.         $this->logger->info("PaymentController.paymentNotificationAction started template:$template");
  266.         if ($template == "barclays")
  267.         {        
  268.             $dataChk=array();
  269.             $dataChk['live']                =    $request->get("live");  // live or test
  270.             $dataChk["eventCode"]            =    $request->get("eventCode");  // event code - will be AUTHORISATION
  271.             $dataChk["pspReference"]        =    $request->get("pspReference");  // Barclay ref code
  272.             $dataChk["originalReference"]    =    $request->get("originalReference");  // blank
  273.             $dataChk["merchantReference"]    =    $request->get("merchantReference");  // Our ref code
  274.             $dataChk["merchantAccountCode"]    =    $request->get("merchantAccountCode");  // Merchant account code
  275.             $dataChk["success"]                =    $request->get("success");
  276.             $dataChk["paymentMethod"]        =    $request->get("paymentMethod");
  277.             $dataChk["operations"]            =    $request->get("operations");
  278.             $dataChk["reason"]                =    $request->get("reason");
  279.             $dataChk["amount"]                =    $request->get("amount");
  280.             
  281.             $this->logger->info("PaymentController.paymentNotificationAction Request Data: ".print_r($dataChk,true));
  282.                         
  283.             $em $this->doctrine->getManager();
  284.             $payment    =    false;
  285.             
  286.             if ($dataChk["merchantReference"] > 0)
  287.             {
  288.                 $this->logger->info("PaymentController.paymentNotificationAction Retrieving Payment: ".$dataChk['merchantReference']);
  289.                 $payment    =    $em->getRepository('App\Entity\Payment')->find($dataChk["merchantReference"]);
  290.             } else {
  291.                 $this->logger->info("PaymentController.paymentNotificationAction No Asscociated Payment");
  292.             }
  293.             if ($payment)
  294.             {
  295.                 $this->logger->info("PaymentController.paymentNotificationAction Payment Successfully Retreived: ".$dataChk['merchantReference']);
  296.                 $payment->setNotification(serialize($dataChk));
  297.                 $em->persist($payment);
  298.                 $em->flush();
  299.                 if ($dataChk["success"]=='false'
  300.                 {
  301.                     $this->logger->info("PaymentController.paymentNotificationAction Payment Unsuccessful, Mailing Sales Rep: ".$dataChk['merchantReference']);
  302.                     $this->mailSalesFailure($payment);
  303.                 } else 
  304.                 {
  305.                     $this->logger->info("PaymentController.paymentNotificationAction Payment Successful: ".$dataChk['merchantReference']);                    
  306.                 }
  307.             }
  308.             $this->logger->info("PaymentController.paymentNotificationAction Returning 200 Response");                    
  309.             return new Response('[accepted]',200,array('content-type' => 'text/html'));
  310.         }
  311.     }
  312.     
  313.     #[Route('/customer/worldpay/redirect/{pid}'name'processWorldpay')]
  314.     public function processWorldpayAction($pidMailerInterface $mailerRequest $request)
  315.     {
  316.         $em $this->doctrine->getManager();
  317.         $payment =     $this->saveReturnData_worldpay($pid$request);
  318.         $msg 'NONE';
  319.         
  320.         if ($payment)
  321.         {
  322.             $paymentRef $this->createPaymentRef($payment);
  323.             $booking $payment->getBooking();
  324.             if ($payment->getSuccessful() == 1)
  325.             {
  326.                 $redirect $this->generateUrl('successPayment', array("payment"=>$paymentRef), UrlGeneratorInterface::ABSOLUTE_URL);
  327.                 $this->mailCustomerConfirmation($booking$payment);
  328.                 $this->mailSalesConfirmation($booking$payment$request);
  329.                 
  330.                 $booking->setPaid(1);
  331.                 $em->persist($booking);
  332.                 $em->flush();
  333.             } else {
  334.                 $redirect $this->generateUrl('failurePayment', array("payment"=>$paymentRef), UrlGeneratorInterface::ABSOLUTE_URL);
  335.                 $this->mailSalesFailure($payment);
  336.             }
  337.         } else
  338.             $redirect $this->generateUrl('failurePayment', array("payment"=>$paymentRef), UrlGeneratorInterface::ABSOLUTE_URL);
  339.         
  340.         //$redirect             =     $redirect===false ?  $request->get("MC_failure") : $redirect;
  341.         //$params                =    $request->query->all();
  342.         //return $this->render("ACSBundle:Payment:process_worldpay.html.twig", array("redirect"=>$redirect, "payment"=>$payment, 'params'=>$params, 'msg'=>$msg) );
  343.         //return new Response("done");
  344.         return new RedirectResponse($redirect);
  345.     }
  346.     #[Route('/customer/payment-success/{payment}'name'successPayment')]
  347.     public function successAction($payment)
  348.     {
  349.         $payment $this->decodePaymentRef($payment);
  350.         if ($payment)
  351.             return $this->render("payment/success.html.twig", array('payment' => $payment));
  352.         else
  353.             return $this->render("booking/notfound.html.twig", array("user"=>$this->loggedUser ));
  354.     }
  355.     
  356.     public function testAction()
  357.     {
  358.         $test 'MYADMINCODE^MYMERCHANT^T0211010:1400:GBP:AUTHORISED';
  359.         $result hash_hmac('sha256'$test'@p-p1epie');
  360.         return new Response($result);
  361.         /*$em             =     $this->getDoctrine()->getManager();
  362.         $payment        =    $em->getRepository('App\Entity\Payment')->find(57);
  363.         $booking         =     $payment->getBooking();
  364.         $this->mailCustomerConfirmation($booking, $payment);
  365.         
  366.         $customer        =    $booking->getCustomer();
  367.         $user            =    $booking->getCreatedby(); 
  368.         
  369.         $recipient        =    trim($customer->getFirstname()." ".$customer->getSurname());
  370.         $sender            =    trim($user->getFirstname()." ".$user->getSurname());
  371.         
  372.         return $this->render("emails/CustomerConfirmation.html.twig", 
  373.                 array(
  374.                         'recipient' => $recipient,
  375.                         'sender'=> $sender,
  376.                         'booking'=>$booking,
  377.                         'payment'=>$payment,
  378.                 ));*/
  379.     }
  380.     /*** PRIVATE HELPER METHODS ***/
  381.     private function appendData_worldpay($booking$payment)
  382.     {
  383.         // See docs for implementation : https://beta.developer.worldpay.com/docs/wpg/hostedintegration/quickstart
  384.         $test_mode        =    $this->getParameter('app.worldpayxml_test_mode') == 'TRUE';
  385.         
  386.         // MD5 hash params may be chosen from the merchant interface.  Currently set to 
  387.         // md5_secret:instId:currency:amount:paymentid
  388.         $cost            =    number_format($booking->getTotalprice(), 2'.''');
  389.         $currency        =    $booking->getBookingcurrency()->getCode();
  390.         
  391.         $sig_params        =    array();
  392.         $sig_params[]     =    null//$md5_secret;
  393.         $sig_params[]     =    null//$instId;
  394.         $sig_params[]     =    $currency;
  395.         $sig_params[]     =    $cost;
  396.         $sig_params[]     =    $payment->getPaymentid();
  397.         
  398.         $bookingOffice $booking->getBookingoffice();
  399.         $bookingAgentEmail $booking->getCreatedby()->getEmail();
  400.         $bookingAgentName trim($booking->getCreatedby()->getFirstname()." ".$booking->getCreatedby()->getSurname());
  401.         $contactDetails $bookingOffice->getAddress()."<br />".$bookingOffice->getCity()."<br />".$bookingOffice->getZipcode()."<br />".$bookingOffice->getOfficecountry()->getName()."<br />Reg. No.: ".$bookingOffice->getRegnumber()."<br />Phone: ".$bookingOffice->getPhone()."<br />Booking agent: ".$bookingAgentName." - <a href='mailto:".$bookingAgentEmail."'>".$bookingAgentEmail."</a>";
  402.         
  403.         $data            =    array(
  404.                                 "orderId"        =>     $payment->getPaymentid(),
  405.                                 "testMode"        =>    $test_mode,
  406.                                 "orderCurrency" =>     $currency,
  407.                                 "orderAmount"     =>     $cost,
  408.                                 "description"     =>     $booking->__toString(),
  409.                                 "shopperEmail"     =>     $booking->getCustomer()->getEmail(),
  410.                                 "name"            =>     $booking->getCustomer()->getFirstname()." ".$booking->getCustomer()->getSurname(),
  411.                                 "address"        =>     $booking->getCustomer()->getAddress(),
  412.                                 "city"            =>     $booking->getCustomer()->getCity(),
  413.                                 "zip"            =>     $booking->getCustomer()->getPostcode(),
  414.                                 "state"            =>     $booking->getCustomer()->getState(),
  415.                                 "country"        =>     $booking->getCustomer()->getCustomercountry()->getCountry2Code(),
  416.                                 "phone"         =>     preg_replace("/^![0-9]$/","",$booking->getCustomer()->getPhone()),
  417.                                 "successURL"    =>     $this->generateURL("successPayment", array( "payment"=>$payment->getPaymentID() ), UrlGeneratorInterface::ABSOLUTE_URL),
  418.                                 "failureURL"    =>     $this->generateURL("failurePayment", array( "payment"=>$payment->getPaymentID() ), UrlGeneratorInterface::ABSOLUTE_URL),
  419.                                 // Following fields required by VISA for payments in GBP
  420.                                 "shopperAdditionalAccountNumber"     =>     "",
  421.                                 "shopperAdditionalLastName"            =>     "",
  422.                                 "shopperAdditionalBirthDate"        =>     "",
  423.                                 "shopperAdditionalPostalCode"        =>    "",    
  424.                                 "contactDetails"                    => $contactDetails
  425.                             );
  426.         $data['MD5sig']    =    md5(implode(":"$sig_params));
  427.         return $data;
  428.     }
  429.     private function createPaymentRef($payment)
  430.     {
  431.         $booking $payment->getBooking();
  432.         $ref=array();
  433.         $ref[]=$payment->getPaymentid();
  434.         $ref[]=$booking->getBookingid();
  435.         $ref[]=$booking->getCustomer()->getCustomerid();
  436.         $ref[]=$booking->getBookingoffice()->getOfficeid();
  437.         
  438.         /*$finalRef = $ref[0].$ref[1].$ref[2].$ref[3];
  439.         $next = $this->getEverySecondDigit($finalRef);
  440.         $finalRef = $finalRef / $next;
  441.         $next = $this->getEverySecondDigit($finalRef);
  442.         $finalRef = $finalRef / $next;
  443.         $next = $this->getEverySecondDigit($finalRef);
  444.         $finalRef = $finalRef * $next;
  445.         $decimalPos = strrpos($finalRef, '.');
  446.         $finalRef = str_replace('.', '', $finalRef);
  447.         $finalRef .= $decimalPos;
  448.         $this->logger->info('$finalRef: '.$finalRef);
  449.         return urlencode($finalRef);*/
  450.         return urlencode(bin2hex(implode(Booking::URL_SECRET$ref)));
  451.     }
  452.     private function decodePaymentRef($ref)
  453.     {
  454.         $this->logger->info('decodePaymentRef: '.$ref);
  455.         //$decimalPos = (string)$ref[strlen((string)$ref) - 1];
  456.         //$this->logger->info('decimalPos: '.$decimalPos);
  457.         
  458.         $data        =    explode(Booking::URL_SECRETpack("H*"$ref));
  459.         $this->logger->info('Data: '.print_r($datatrue));
  460.         $id            =    array_shift($data);
  461.         $em $this->doctrine->getManager();
  462.         $payment    =    $em->getRepository('App\Entity\Payment')->find($id);
  463.         if ($payment
  464.         {
  465.             $this->logger->info('Got payment: '.$payment->getPaymentid());
  466.             $booking $payment->getBooking();
  467.             if ($booking->getBookingid() == $data[0] && $booking->getCustomer()->getCustomerid() == $data[1] && $booking->getBookingoffice()->getOfficeid() == $data[2])
  468.                 return $payment;
  469.             else {
  470.                 $this->logger->info('Did not match criteria: bid: '.$booking->getBookingid().' $data[0]: '.$data[0].', cid: '.$booking->getCustomer()->getCustomerid().' $data[1]: '.$data[1].', oid: '.$booking->getBookingoffice()->getOfficeid().' $data[2]: '.$data[2]);
  471.                 return false;
  472.             }
  473.         } else {
  474.             $this->logger->info('Could not find payment from id: '.$id);
  475.             return false
  476.         }
  477.     }
  478.     private function decodeRef($ref)
  479.     {
  480.         $data        =    explode(Booking::URL_SECRETpack("H*"$ref));
  481.         //$decimalPos = (string)$ref[(strlen($ref) - 1];
  482.         $id            =    array_shift($data);
  483.         $em $this->doctrine->getManager();
  484.         $booking    =    $em->getRepository('App\Entity\Booking')->find($id);
  485.         if ($booking
  486.         {
  487.             if ($booking->getCustomer()->getCustomerid() == $data[0] && $booking->getBookingoffice()->getOfficeid()==$data[1])
  488.                 return $booking;
  489.             else 
  490.                 return false;
  491.         } else
  492.             return false
  493.     }
  494.     private function decrypt($encrypted$salt) {
  495.         //https://www.the-art-of-web.com/php/two-way-encryption/
  496.         $encKey $this->getParameter('app.worldpayxml_enckey').$salt;
  497.         $method 'AES-256-CTR';
  498.         list($encrypted$encIV) = explode("::"$encrypted);
  499.         $decrypted openssl_decrypt($encrypted$method$encKey0hex2bin($encIV));
  500.         return $decrypted;
  501.     }
  502.     private function encrypt($token$salt) {
  503.         //https://www.the-art-of-web.com/php/two-way-encryption/
  504.         $encKey $this->getParameter('app.worldpayxml_enckey').$salt;
  505.         $method 'AES-256-CTR';
  506.         $encIV openssl_random_pseudo_bytes(openssl_cipher_iv_length($method));
  507.         $encrypted openssl_encrypt($token$method$encKey0$encIV) . "::" bin2hex($encIV);
  508.         return $encrypted;
  509.     }
  510.     public static function getEverySecondDigit($input) {
  511.         //$this->logger = Logger::getLogger(__CLASS__);
  512.         $input = (string)$input;
  513.         $len strlen($input);
  514.         //$this->logger->info('Length of '.$input.' is '.$len);
  515.         $final '';
  516.         for ($x 0$x $len$x++) {
  517.             if ($input[$x] != '.') {
  518.                 if (($x 1) % === 0) {
  519.                     $final .= $input[$x];
  520.                 }
  521.             } else {
  522.                 $final .= '.';
  523.             }
  524.         }
  525.         //$this->logger->info('From $input: '.$input.', calculated: '.$final);
  526.         return $final;
  527.     }
  528.     private function getPayment($em$booking, &$paid)
  529.     {
  530.         $this->logger->info('getPayment for booking: '.$booking->getBookingid());
  531.         $paymentArray    =    $em->getRepository('App\Entity\Payment')->findByBooking($booking->getBookingid());
  532.         $payment        =    false;
  533.         foreach ($paymentArray as $p)
  534.         {
  535.             $this->logger->info('Found payment: '.$p->getPaymentid().', is successful: '.$p->getSuccessful());
  536.             $payment $p;
  537.             if ($p->getSuccessful() == 1)
  538.             {
  539.                 $paid =    true;
  540.                 break;
  541.             }
  542.             //else if ($p->getResulttoken() == null && $p->getAuthcode() == null && $p->getSuccessful() == null) {
  543.             //    $payment = $p;
  544.             //    break;
  545.             //} 
  546.         }
  547.         return $payment;
  548.     }
  549.     private function mailCustomerConfirmation($booking$payment)
  550.     {
  551.         $customer        $booking->getCustomer();
  552.         $user            $booking->getCreatedby();
  553.         $office         $booking->getBookingoffice();
  554.         $recipient        trim($customer->getFirstname().' '.$customer->getSurname());
  555.         $sender            trim($user->getFirstname().' '.$user->getSurname());
  556.         $from           $office->getEmailaddress();
  557.         
  558.         $message = (new TemplatedEmail())
  559.             ->subject('Booking Payment Received')
  560.             ->from($from)
  561.             ->to($customer->getEmail());
  562.         //https://github.com/symfony/symfony/issues/42407#issuecomment-1006995400
  563.         $html $this->render('emails/CustomerConfirmation.html.twig',
  564.         [
  565.             'recipient' => $recipient,
  566.             'sender' => $sender,
  567.             'booking' => $booking,
  568.             'payment' => $payment,
  569.             'email' => new WrappedTemplatedEmail($this->twig$message),                        
  570.         ])
  571.         ->getContent();
  572.         $message->html($html);
  573.         
  574.         $this->mailer = new Mailer(Transport::fromDsn('sendmail://default'));
  575.         $sent $this->mailer->send($message);
  576.         //https://stackoverflow.com/q/71496164/206852
  577.         // if ($sent !== null)
  578.         //     dd($sent->getDebug());
  579.     }
  580.     
  581.     private function mailSalesConfirmation($booking$payment$request) {        
  582.         $customer       $booking->getCustomer();
  583.         $user           $booking->getCreatedby();
  584.         $office         $booking->getBookingoffice();
  585.         
  586.         $recipient        =    trim($user->getFirstname().' '.$user->getSurname());
  587.         $sender            'System';
  588.         $from           $office->getEmailaddress();
  589.         
  590.         $message = (new TemplatedEmail())
  591.             ->subject('Booking Payment Received')
  592.             ->from($from)
  593.             ->to($user->getEmail())
  594.             ->cc($this->getParameter('app.accountsemail'));
  595.         //https://github.com/symfony/symfony/issues/42407#issuecomment-1006995400
  596.         $html $this->render('emails/SalesConfirmation.txt.twig',
  597.         [
  598.             'recipient' => $recipient,
  599.             'sender' => $sender,
  600.             'booking' => $booking,
  601.             'payment' => $payment,
  602.             'cardUsed' => $request->get('cardType'),
  603.             'email' => new WrappedTemplatedEmail($this->twig$message),                        
  604.         ])
  605.         ->getContent();
  606.         $message->html($html);
  607.         
  608.         $this->mailer = new Mailer(Transport::fromDsn('sendmail://default'));
  609.         $sent $this->mailer->send($message);
  610.         //https://stackoverflow.com/q/71496164/206852
  611.         // if ($sent !== null)
  612.         //     dd($sent->getDebug());
  613.     }
  614.     
  615.     private function mailSalesFailure($payment)
  616.     {
  617.         $this->logger->info('mailSalesFailure');
  618.             
  619.         if ($payment)
  620.         {
  621.             $booking        $payment->getBooking();            
  622.             $customer        $booking->getCustomer();
  623.             $user            $booking->getCreatedby();        
  624.             $office         $booking->getBookingoffice();
  625.             $recipient        trim($user->getFirstname().' '.$user->getSurname());
  626.             $sender            'System';
  627.             $name            trim($customer->getFirstname().' '.$customer->getSurname());
  628.             $from           $office->getEmailaddress();
  629.             
  630.             $template         =    $booking->getBookingoffice()->getPaymentgateway()->getTemplate();
  631.             $notificationData explode('\n'$payment->getNotification());
  632.             $notificationData json_decode(end($notificationData));
  633.             
  634.             //$this->logger->info('$payment->getNotification(): '.$payment->getNotification());
  635.             $this->logger->info('$notificationData: '.print_r($notificationDatatrue));
  636.             $this->logger->info('json_last_error: '.json_last_error());
  637.             
  638.             switch ($template)
  639.             {
  640.                 case 'authorize':
  641.                     $reason =    $notificationData->response_reason_text;
  642.                     break;
  643.                 case 'barclays':
  644.                     $reason    =     $notificationData['reason'];
  645.                     break;
  646.                 case 'worldpay':
  647.                     $reason =     'Error code: '.$notificationData->code.', Error message: '.$notificationData->status;
  648.                     break;
  649.             }
  650.             
  651.             $message = (new TemplatedEmail())
  652.                 ->subject('Booking Payment Failed')
  653.                 ->from($from)
  654.                 ->to($user->getEmail());
  655.             
  656.             //https://github.com/symfony/symfony/issues/42407#issuecomment-1006995400
  657.             $html $this->render('emails/Failure.txt.twig',
  658.             [
  659.                 'recipient'     =>     $recipient,
  660.                 'sender'        =>     $sender,
  661.                 'booking'        =>    $booking,
  662.                 'payment'        =>    $payment,
  663.                 'name'            =>    $name,
  664.                 'reason'        =>    $reason,
  665.                 'email' => new WrappedTemplatedEmail($this->twig$message),                        
  666.             ])
  667.             ->getContent();
  668.             $message->html($html);
  669.             
  670.             $this->mailer = new Mailer(Transport::fromDsn('sendmail://default'));
  671.             $sent $this->mailer->send($message);
  672.     
  673.             //https://stackoverflow.com/q/71496164/206852
  674.             // if ($sent !== null)
  675.             //     dd($sen
  676.         }
  677.     }
  678.     private function saveReturnData_worldpay($pidRequest $request)
  679.     {
  680.         $this->logger->info('saveReturnData_worldpay');
  681.         
  682.         $em $this->doctrine->getManager();
  683.         $payment $em->getRepository('App\Entity\Payment')->find($pid);
  684.         
  685.         if ($payment)
  686.         {
  687.             $this->logger->info("Found payment with id ".$pid);
  688.             
  689.             if ($request->query->has('errorRefNumber') && $request->query->has('errors'))
  690.             {
  691.                 $err = array('date' => date('Y-m-d H:i:s'), 'code' => $request->get('errorRefNumber'), 'status' => 'Worldpay error: '.$request->get('errors'));
  692.                 $payment->setNotification($payment->getNotification().'\n'.json_encode($err));        
  693.                 $payment->setSuccessful(0);
  694.                 $em->persist($payment);
  695.                 $em->flush();
  696.                 return $payment;
  697.             }
  698.             
  699.             //AUTHORISED EXAMPLE
  700.             //https://dev.onlinepayments.aircharterservice.com/customer/worldpay/redirect/296?orderKey=AIRCHARTERSERVICES%5EAIRCHARTERUKECOMGBP%5E296&paymentStatus=AUTHORISED&paymentAmount=1234565&paymentCurrency=GBP&mac2=c975417ba3d7b63a29c1457802379b4f6b799a67750d9aab590dd277622ff92e
  701.             //CANCELLED EXAMPLE
  702.             //https://dev.onlinepayments.aircharterservice.com/customer/worldpay/redirect/309?orderKey=AIRCHARTERSERVICES%5EAIRCHARTERUKECOMGBP%5E309&orderAmount=65421&orderCurrency=GBP&mac2=5e3ee235214f9906c3869bb916f49477f126d076cb11c6497472f07b2528fdbf
  703.             //REFUSED EXAMPLE
  704.             //https://dev.onlinepayments.aircharterservice.com/customer/worldpay/redirect/309?orderKey=AIRCHARTERSERVICES%5EAIRCHARTERUKECOMGBP%5E309&paymentStatus=REFUSED&paymentAmount=65421&paymentCurrency=GBP&mac2=8911c0e65ad5d7bbd219db86581c84fe63a532a34023b2ac670e44f0d6e6c677
  705.             //ERROR EXAMPLE
  706.             //https://dev.onlinepayments.aircharterservice.com/customer/worldpay/redirect/309?orderKey=AIRCHARTERSERVICES%5EAIRCHARTERUKECOMGBP%5E309&errorRefNumber=D190710-T154806-M001-43&errors=Gateway+error
  707.             //BE 190708: documentation at https://beta.developer.worldpay.com/docs/wpg/hostedintegration/securingpayments
  708.             $booking $payment->getBooking();
  709.             $office $booking->getBookingoffice();
  710.             $officeSalt $office->getMerchantsalt();
  711.             $macSecret $this->decrypt($office->getMerchantmacsecret(), $officeSalt);
  712.             $test_mode $this->getParameter('app.worldpayxml_test_mode') == 'TRUE';
  713.             $currency $booking->getBookingcurrency()->getCode();
  714.             $merchantCode $this->decrypt($office->getMerchantcode(), $officeSalt).$currency;
  715.             
  716.             // status can be "AUTHORISED" or "REFUSED"
  717.             $status            =    $request->get('paymentStatus');
  718.             
  719.             $sig_params        =    array();
  720.             $sig_params[]     =    $request->get('orderKey');
  721.             $sig_params[]     =    $request->get('paymentAmount');
  722.             $sig_params[]     =    $request->get('paymentCurrency');
  723.             if ($status)
  724.                 $sig_params[] =    $status;
  725.             
  726.             $sig_check        =    array();
  727.             $sig_check[]     =    'AIRCHARTERSERVICES^'.$merchantCode.'^'.$payment->getPaymentId();
  728.             $sig_check[]     =    ltrim((string)number_format($booking->getTotalprice(), 2''''), '0');
  729.             $sig_check[]     =    $currency;
  730.             if ($status)
  731.                 $sig_check[] = $status;
  732.             
  733.             $sigSent implode(":"$sig_params);
  734.             $sigCalculated implode(":"$sig_check);
  735.             $calculated_hash hash_hmac('sha256'$sigCalculated$macSecret);
  736.             //$this->logger->info('Using secret: '.$macSecret);
  737.             $hash_check $calculated_hash == $request->get('mac2');
  738.             $retVal false;
  739.             if ($hash_check)
  740.             {
  741.                 $statusCode 1;
  742.                 if (!$status || $status == 'CANCELLED')
  743.                     $statusCode 3;
  744.                 else if ($status == 'AUTHORISED')
  745.                     $statusCode 1;
  746.                 else if ($status == 'REFUSED')
  747.                     $statusCode 2;
  748.                 else
  749.                     $statusCode 99;
  750.                     
  751.                 $this->logger->info('Hash check succeeded!');
  752.                 $payment->setResulttoken($request->get('mac2'));
  753.                 $payment->setAuthcode($request->get('mac2'));
  754.                 $payment->setSuccessful($statusCode == 1);
  755.                 $payment->setNotification($payment->getNotification().'\n'.json_encode(array('date' => date('Y-m-d H:i:s'), 'code' => $statusCode'status' => $status'params' => $request->query->all())));
  756.                 $retVal $payment;
  757.             }
  758.             else
  759.             {
  760.                 $this->logger->info('Sig params sent: '.$sigSent.', Sig params calculated: '.$sigCalculated.', are equal = '.($sigSent == $sigCalculated));
  761.                 $this->logger->info('Failed Hash Check: Calculated Value: '.$calculated_hash.', Sent Value (mac): '.$request->get('mac').', Sent Value (mac2): '.$request->get('mac2'));
  762.                 $payment->setNotification($payment->getNotification().'\n'.json_encode(array('date' => date('Y-m-d H:i:s'), 'code' => 4'status' => 'Failed Auth Hash Check - contact Support''params' => $request->query->all())));
  763.                 $retVal $payment;
  764.             }
  765.             $em->persist($payment);
  766.             $em->flush();
  767.             return $retVal;
  768.         } else {
  769.             $this->logger->info("Payment with id ".$pid." was NOT found.");
  770.             return false;
  771.         }
  772.     }
  773.     /*** OLD CODE - KEPT FOR REFERENCE IF REQUIRED IN THE FUTURE ***/
  774.     private function appendData_barclays($booking$payment) {
  775.         $hmac_key         =     $this->getParameter('barclays_hmac_key'); 
  776.         $skin_code        =    $this->getParameter('barclays_skin_code'); 
  777.         $merchant_acc    =    $this->getParameter('barclays_merchant_acc');
  778.         
  779.         $time            =    $payment->getUpdated()->format("U") + 60*60*24*30;
  780.         $paymentexpires    =    gmdate("Y-m-d"$time) . 'T' gmdate("H:i:s"$time) ."Z";
  781.         //$paymentexpires=gmdate(DATE_ISO8601,$expTimestamp);
  782.     
  783.         $data = array(
  784.             'paymentAmount'        =>    $booking->getTotalprice()*100,
  785.             'currencyCode'        =>    $booking->getBookingcurrency()->getCode(),
  786.             'shipBeforeDate'    =>    $payment->getUpdated()->format('Y-m-d'),
  787.             'merchantReference'    =>    $payment->getPaymentid(),
  788.             'skinCode'            =>    $skin_code,
  789.             'merchantAccount'    =>    $merchant_acc,
  790.             'sessionValidity'    =>    $paymentexpires,
  791.             'shopperEmail'        =>    $booking->getCustomer()->getEmail(),
  792.             'shopperReference'    =>    $booking->getCustomer()->getCustomerid(),
  793.             'allowedMethods'    =>    '',
  794.             'blockedMethods'    =>    '',
  795.             'shopperStatement'    =>    '',
  796.             'billingAddressType'=>    '',
  797.         );
  798.         $summary                =    implode("",$data);
  799.         
  800.         $merchantSig            =    base64_encode(hash_hmac('sha1',$summary,$hmac_key,true));
  801.         
  802.         $data['orderData']        =    base64_encode($booking->__toString());
  803.         $data['merchantSig']    =    $merchantSig;
  804.         
  805.         return $data;
  806.     }
  807.     
  808.     private function appendData_authorize($booking,$payment) {
  809.         $hmac_key         =     $this->getParameter('authorize_hmac_key'); 
  810.         $api_login        =    $this->getParameter('authorize_api_login');
  811.         
  812.         /*added by vazquel on 2014-02-19*/
  813.         $md5_hash     =     $this->getParameter('authorize_md5_hash'); 
  814.         $gateway = new \Authorizenet_Authorizenet($api_login$md5_hash);
  815.         $response $gateway->AuthorizeSIM;
  816.         $fp_timestamp gmdate("U");
  817.         $fingerprint \AuthorizeNetSIM_Form::getFingerprint($api_login$hmac_key$booking->getTotalprice(), $payment->getPaymentid(), $fp_timestamp$booking->getBookingcurrency()->getCode());
  818.         
  819.         $data['x_login']         =     $api_login;
  820.         $data['x_test_request'] =     $this->getParameter('authorize_test_mode');
  821.         $data['x_fp_sequence']    =     $payment->getPaymentid();
  822.         $data['x_fp_timestamp']    =     $fp_timestamp;
  823.         $data['x_amount']         =     $booking->getTotalprice();
  824.         $data['x_currency_code']=     $booking->getBookingcurrency()->getCode();
  825.         $data['x_fp_hash']        =     $fingerprint;
  826.         $data['x_description']    =     $booking->__toString();
  827.         $data['x_first_name']    =     $booking->getCustomer()->getFirstname();
  828.         $data['x_last_name']    =     $booking->getCustomer()->getSurname();
  829.         $data['x_address']        =     $booking->getCustomer()->getAddress();
  830.         $data['x_city']            =     $booking->getCustomer()->getCity();
  831.         $data['x_zip']            =     $booking->getCustomer()->getPostcode();
  832.         $data['x_state']        =     $booking->getCustomer()->getState();
  833.         $data['x_country']        =     $booking->getCustomer()->getCustomercountry()->getName();
  834.         $data['x_phone']         =     preg_replace("/^![0-9]$/","",$booking->getCustomer()->getPhone());
  835.         $data['x_email']        =     $booking->getCustomer()->getEmail();
  836.         $data['booking']        =    $booking;
  837.         $data['payment']        =    $payment;
  838.         
  839.         return $data;
  840.     }
  841.     
  842.     private function appendData_moneyswap($booking$payment) {
  843.         $moneyswap_aid                 $this->getParameter('moneyswap_aid');
  844.         $moneyswap_md5_signature     $this->getParameter('moneyswap_md5_signature');
  845.     
  846.         $data = array(
  847.             "acqID" => $moneyswap_aid,
  848.             //"acqID" => "04020826",
  849.             "backURL" => $this->generateURL("processBooking", array( "gateway"=>$payment->getPaymentgateway()->getPaymentgatewayid() ), UrlGeneratorInterface::ABSOLUTE_URL),
  850.             "charSet" => "UTF-8",
  851.             "frontURL" => $this->generateURL("processBooking", array( "gateway"=>$payment->getPaymentgateway()->getPaymentgatewayid() ), UrlGeneratorInterface::ABSOLUTE_URL),
  852.             "merID" => "846084045110001",
  853.             "merReserve" => $booking->__toString(),
  854.             "orderAmount" => number_format($booking->getTotalprice(), 2'.'''),
  855.             "orderCurrency" => $booking->getBookingcurrency()->getCode(),
  856.             "orderNum" => $payment->getPaymentid(),
  857.             "paymentSchema" => "UP",
  858.             "transTime" => date("YmdHis"),
  859.             "transType" => "PURC",
  860.             "signType" => "MD5",
  861.             "version" => "VER000000002",
  862.         );
  863.         $signature MoneySwapHelper::createSignature($moneyswap_md5_signature$data);
  864.         $data['signature'] = $signature;
  865.         
  866.         return $data;
  867.     }
  868.     private function getRelayResponseSnippet($redirect_url) {
  869.         return "<html><head><script language=\"javascript\">
  870.                 <!--
  871.                 window.location1=\"{$redirect_url}\";
  872.                 //-->
  873.                 </script>
  874.                 </head><body><noscript><meta http-equiv=\"refresh\" content=\"1;url={$redirect_url}\"></noscript>Test</body></html>";
  875.     }
  876.     #[Route('/customer/process/{gateway}'name'processBooking')]
  877.     public function processAction($gatewayMailerInterface $mailerRequest $request)
  878.     {
  879.         $em             =     $this->getDoctrine()->getManager();
  880.         $paymentGateway    =    $em->getRepository('App\Entity\Paymentgateway')->find($gateway);
  881.         $func            =    "saveReturnData_".$paymentGateway->getTemplate();
  882.         $api_login     =     $this->getParameter('authorize_api_login');
  883.         $md5_hash     =     $this->getParameter('authorize_md5_hash');
  884.         
  885.         $fullDomain      =     ($request->server->get("https") ? "https://" "http://") . $request->getHost();
  886.         
  887.         if (method_exists($this$func))
  888.             $payment    =    $this->$func($request);
  889.         
  890.         if ($payment)
  891.         {
  892.             $booking=$payment->getBooking();
  893.             if ($payment->getSuccessful()==1)
  894.             {
  895.                 if ($gateway == 3) {
  896.                     if (!$booking->getPaid()) {
  897.                         $this->mailCustomerConfirmation($booking,$payment);
  898.                         $this->mailSalesConfirmation($booking,$payment,$request);
  899.                     }
  900.                 } else {
  901.                     $this->mailCustomerConfirmation($booking,$payment);
  902.                     $this->mailSalesConfirmation($booking,$payment,$request);
  903.                 }
  904.                 $booking->setPaid(1);
  905.                 $em->persist($booking);
  906.                 $em->flush();
  907.                 //$this->mailCustomerConfirmation($booking,$payment);
  908.                 //$this->mailSalesConfirmation($booking,$payment);
  909.                 $fail 0;
  910.                 $url $this->generateUrl('successPayment', array("payment"=>$payment->getPaymentid()), UrlGeneratorInterface::ABSOLUTE_URL);
  911.                 if ($gateway == 2)
  912.                 {
  913.                     //added by vazquel on 2014-02-19
  914.                     $auth_controller = new \Authorizenet_Authorizenet($api_login$md5_hash);
  915.                     $response $auth_controller->AuthorizeSIM;
  916.                     
  917.                     //added by vazquel on 2014-02-19 (Redirect to the payment success page)
  918.                     if ($response->isAuthorizeNet())
  919.                         return new Response($this->getRelayResponseSnippet($fullDomain.$url));
  920.                     else
  921.                         return $this->redirect($url);
  922.                 }
  923.                 else
  924.                     return $this->redirect($url);
  925.             } else 
  926.                 $fail=1;
  927.         } else 
  928.             $fail=2;
  929.         
  930.         if ($fail == 1)
  931.         {
  932.             $url $this->generateUrl('failurePayment', array("payment"=>$payment->getPaymentid()), UrlGeneratorInterface::ABSOLUTE_URL);
  933.             if ($gateway == 2)
  934.             {
  935.                 $this->mailSalesFailure($payment); 
  936.                 $auth_controller = new \Authorizenet_Authorizenet($api_login$md5_hash);
  937.                 $response $auth_controller->AuthorizeSIM;
  938.                 
  939.                 if ($response->isAuthorizeNet())
  940.                     return new Response($this->getRelayResponseSnippet($fullDomain.$url));
  941.                 else
  942.                     return $this->redirect($url);
  943.             }
  944.             else 
  945.                 return $this->redirect($url);
  946.         }
  947.     }
  948.     private function saveReturnData_barclays(Request $request) {
  949.         $hmac_key         =     $this->getParameter('barclays_hmac_key'); 
  950.         $em             =     $this->getDoctrine()->getManager();
  951.         $payment        =     $em->getRepository('App\Entity\Payment')->find($request->get("merchantReference"));
  952.         
  953.         if ($payment)
  954.         {
  955.             $booking    =     $payment->getBooking();
  956.             $data        =    $this->appendData_barclays($booking$payment);
  957.             
  958.             $dataChk    =     array();
  959.             $dataChk[]    =    $request->get("authResult");
  960.             $dataChk[]    =    $request->get("pspReference");
  961.             $dataChk[]    =    $request->get("merchantReference");
  962.             $dataChk[]    =    $request->get("skinCode");
  963.             $dataChk[]    =    $request->get("merchantReturnData");
  964.             
  965.             $sig        =     base64_encode(hash_hmac('sha1',implode(""$dataChk),$hmac_key,true));
  966.             
  967.             if ($sig==$request->get("merchantSig"))
  968.             {
  969.                 $payment->setResulttoken($request->get("pspReference"));
  970.                 $payment->setAuthcode($request->get("authResult"));
  971.                 $payment->setSuccessful("AUTHORISED"==$request->get("authResult"));
  972.                 
  973.                 $em->persist($payment);
  974.                 $em->flush();
  975.                 
  976.                 return $payment;                
  977.             }
  978.             else
  979.                 return false;
  980.         } 
  981.         else        
  982.             return false;
  983.     }
  984.     
  985.     private function saveReturnData_authorize(Request $request) {
  986.         $hmac_key     =     $this->getParameter('authorize_hmac_key'); 
  987.         $api_login     =     $this->getParameter('authorize_api_login'); 
  988.         $md5_hash     =     $this->getParameter('authorize_md5_hash'); 
  989.         
  990.         $em $this->doctrine->getManager();
  991.         $payment    =    $em->getRepository('App\Entity\Payment')->find($request->get("x_invoice_num"));
  992.         
  993.         $gateway     =     new \Authorizenet_Authorizenet($api_login$md5_hash);
  994.         $response     =     $gateway->AuthorizeSIM;
  995.         
  996.             if ($response->isAuthorizeNet() && $payment instanceof Payment)
  997.         {
  998.             $payment->setResulttoken($response->authorization_code);
  999.             $payment->setAuthcode($response->response_reason_code);
  1000.             $payment->setSuccessful($response->approved*1);
  1001.             $payment->setNotification(serialize($response));
  1002.             $em->persist($payment);
  1003.             $em->flush();
  1004.                  
  1005.             return $payment;
  1006.         }
  1007.         else
  1008.             die( "Error. Check your MD5 Setting.<br>Received: $response->md5_hash<br>Calculated: ".$response->generateHash());
  1009.     }
  1010.     
  1011.     private function saveReturnData_moneyswap(Request $request) {
  1012.         $moneyswap_aid                 $this->getParameter('moneyswap_aid');
  1013.         $moneyswap_md5_signature     $this->getParameter('moneyswap_md5_signature');
  1014.         $em             =     $this->getDoctrine()->getManager();
  1015.         $payment        =     $em->getRepository('App\Entity\Payment')->find($request->get("orderNum"));
  1016.         
  1017.         if ($payment)
  1018.         {
  1019.             $booking    =     $payment->getBooking();
  1020.             
  1021.             $query "version=".$request->get("version");
  1022.             $query .= "&charSet=".$request->get("charSet");
  1023.             $query .= "&transType=".$request->get("transType");
  1024.             $query .= "&orderNum=".$request->get("orderNum");
  1025.             $query .= "&orderAmount=".$request->get("orderAmount");
  1026.             $query .= "&orderCurrency=".$request->get("orderCurrency");
  1027.             $query .= "&settAmount=".$request->get("settAmount");
  1028.             $query .= "&settCurrency=".$request->get("settCurrency");
  1029.             $query .= "&rate=".$request->get("rate");
  1030.             $query .= "&merReserve=".$request->get("merReserve");
  1031.             $query .= "&transID=".$request->get("transID");
  1032.             $query .= "&merID=".$request->get("merID");
  1033.             $query .= "&acqID=".$request->get("acqID");
  1034.             $query .= "&paymentSchema=".$request->get("paymentSchema");
  1035.             $query .= "&RespCode=".$request->get("RespCode");
  1036.             $query .= "&RespMsg=".$request->get("RespMsg");
  1037.             $query .= "&transTime=".$request->get("transTime");
  1038.             $query .= "&GWTime=".$request->get("GWTime");
  1039.             $query .= "&signType=".$request->get("signType");
  1040.             $query .= "&signature=".$request->get("signature");
  1041.             
  1042.             $isValid MoneySwapHelper::verifySignature($moneyswap_md5_signature$query);
  1043.             
  1044.             if ($isValid)
  1045.             {
  1046.                 $payment->setResulttoken($request->get("RespMsg"));
  1047.                 $payment->setAuthcode($request->get("RespCode"));
  1048.                 $payment->setSuccessful("00"==$request->get("RespCode"));
  1049.                 $payment->setNotification(serialize($query));
  1050.                 
  1051.                 $em->persist($payment);
  1052.                 $em->flush();
  1053.                 
  1054.                 return $payment;                
  1055.             }
  1056.             else
  1057.                 return false;
  1058.         } 
  1059.         else
  1060.             return false;
  1061.     }
  1062. }