public function __construct($applicationprofileid, $merchantprofileid, $workflowid, $isTestAccount, $identitytoken = null, $sessiontoken = null)
 {
     $this->connection = VelocityConnection::instance();
     // VelocityConnection class object store in private data member $connection.
     self::$identitytoken = $identitytoken;
     self::$applicationprofileid = $applicationprofileid;
     self::$merchantprofileid = $merchantprofileid;
     self::$workflowid = $workflowid;
     self::$isTestAccount = $isTestAccount;
     if (empty($sessiontoken) && !empty($identitytoken)) {
         $this->sessionToken = $this->connection->signOn();
     } else {
         $this->sessionToken = $sessiontoken;
     }
 }
 $db->setQuery($q2);
 $vcred = $db->loadResult();
 $vcred = explode('"', $vcred);
 $identitytoken = $vcred[1];
 $workflowid = $vcred[3];
 $applicationprofileid = $vcred[5];
 $merchantprofileid = $vcred[7];
 $payment_mode = $vcred[9];
 include_once 'sdk' . DS . 'Velocity.php';
 if ($payment_mode) {
     $isTestAccount = TRUE;
 } else {
     $isTestAccount = FALSE;
 }
 try {
     $velocityProcessor = new VelocityProcessor($applicationprofileid, $merchantprofileid, $workflowid, $isTestAccount, $identitytoken);
 } catch (Exception $e) {
     echo $e->getMessage();
     exit;
 }
 try {
     // request for refund
     $response = $velocityProcessor->returnById(array('amount' => $total_refund, 'TransactionId' => $txtid));
     $xml = VelocityXmlCreator::returnByIdXML(number_format($total_refund, 2, '.', ''), $txtid);
     // got ReturnById xml object.
     $req = $xml->saveXML();
     if (is_array($response) && !empty($response) && isset($response['Status']) && $response['Status'] == 'Successful') {
         $date = JFactory::getDate();
         // for current datetime
         /* save the returnbyid response into 'velocity transactions' custom table.*/
         $queryR = $db->getQuery(true);
     } else {
         // some error
         echo '<pre>';
         print_r($response);
         echo '</pre>';
     }
 } catch (Exception $e) {
     echo $e->getMessage();
 }
 /******************************************************CaptureAll******************************************************************************** */
 $identitytoken = "PHNhbWw6QXNzZXJ0aW9uIE1ham9yVmVyc2lvbj0iMSIgTWlub3JWZXJzaW9uPSIxIiBBc3NlcnRpb25JRD0iXzQ2ZTdkZDAzLTIwYzctNGJlZS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15464;
 $merchantprofileid = "GlobalEastTCEBT";
 $workflowid = "A39DF00001";
 try {
     $velocityProcessorcap = new VelocityProcessor($applicationprofileid, $merchantprofileid, $workflowid, $isTestAccount, $identitytoken);
 } catch (Exception $e) {
     echo $e->getMessage();
 }
 try {
     $response = $velocityProcessorcap->captureAll();
     if (isset($response['ArrayOfResponse']['Response']['Status']) && $response['ArrayOfResponse']['Response']['Status'] == 'Successful') {
         echo 'CaptureAll Successful!</br>';
         echo 'TransactionState: ' . $response['ArrayOfResponse']['Response']['StatusMessage'] . '</br>';
         echo 'CaptureState: ' . $response['ArrayOfResponse']['Response']['CaptureState'] . '</br>';
         echo 'TransactionState: ' . $response['ArrayOfResponse']['Response']['TransactionState'] . '</br>';
         echo 'TransactionId: ' . $response['ArrayOfResponse']['Response']['TransactionId'] . '</br></br>';
     } else {
         // some error
         echo '<pre>';
         print_r($response);
 /**
  * Refund
  *
  * @param \XLite\Model\Payment\BackendTransaction $transaction Backend transaction
  *
  * @return boolean
  */
 protected function doRefund(\XLite\Model\Payment\BackendTransaction $transaction)
 {
     $this->includeVelocityLibrary();
     $backendTransactionStatus = $transaction::STATUS_FAILED;
     $errorData = '';
     if ($this->getSetting('mode') == 'test') {
         $isTestAccount = true;
     } else {
         $isTestAccount = false;
     }
     try {
         $velocityProcessor = new \VelocityProcessor(self::$applicationprofileid, self::$merchantprofileid, self::$workflowid, $isTestAccount, self::$identitytoken);
     } catch (Exception $e) {
         $transaction->setDataCell('error_message', $e->getMessage(), 'Velocity error message');
         $errorData .= $e->getMessage();
     }
     $refund_amount = $transaction->getValue();
     $txnid = $transaction->getPaymentTransaction()->getDataCell('velocity_payment_id')->getValue();
     try {
         // request for refund
         $response = $velocityProcessor->returnById(array('amount' => $refund_amount, 'TransactionId' => $txnid));
         $xml = \VelocityXmlCreator::returnByIdXML($refund_amount, $txnid);
         // got ReturnById xml object.
         $req = $xml->saveXML();
         $obj_req = serialize($req);
         if (is_array($response) && !empty($response) && isset($response['Status']) && $response['Status'] == 'Successful') {
             $backendTransactionStatus = $transaction::STATUS_SUCCESS;
             $transaction->setDataCell('velocity_refund_id', $response['TransactionId'], 'Velocity Refund ID');
             $transaction->setDataCell('approval_code', $response['ApprovalCode'], 'Velocity Approval Code');
             $transaction->setDataCell('request_refund_object', $obj_req, 'Velocity Request Refund Object');
             $transaction->setDataCell('response_refund_object', serialize($response), 'Velocity Response Refund Object');
             $transaction->setDataCell('refund_status', $response['TransactionState'], 'Refund Transaction Status');
             $transaction->setStatus($backendTransactionStatus);
             \XLite\Core\Database::getEM()->flush();
         } else {
             if (is_array($response) && !empty($response)) {
                 $transaction->setDataCell('error_message', $response['StatusMessage'], 'Velocity error message');
                 $errorData .= $response['StatusMessage'];
             } else {
                 if (is_string($response)) {
                     $transaction->setDataCell('error_message', $response, 'Velocity error message');
                     $errorData .= $response;
                 } else {
                     $transaction->setDataCell('error_message', 'Unknown Error please contact the site admin', 'Velocity error message');
                     $errorData .= 'Unknown Error please contact the site admin';
                 }
             }
         }
     } catch (Exception $e) {
         $transaction->setDataCell('error_message', $e->getMessage(), 'Velocity error message');
         $errorData .= $e->getMessage();
     }
     if (\XLite\Model\Payment\BackendTransaction::STATUS_SUCCESS == $backendTransactionStatus) {
         $order = $transaction->getPaymentTransaction()->getOrder();
         $paymentTransactionSums = $order->getRawPaymentTransactionSums();
         $refunded = $paymentTransactionSums['refunded'];
         $status = $refunded < $transaction->getPaymentTransaction()->getValue() ? \XLite\Model\Order\Status\Payment::STATUS_PART_PAID : \XLite\Model\Order\Status\Payment::STATUS_REFUNDED;
         $order->setPaymentStatus($status);
         \XLite\Core\TopMessage::getInstance()->addInfo('Payment has been refunded successfully');
     } else {
         $msg = 'Transaction failure';
         if (!empty($errorData)) {
             $msg .= '-' . $errorData;
         }
         \XLite\Core\TopMessage::getInstance()->addError($msg);
     }
     return \XLite\Model\Payment\BackendTransaction::STATUS_SUCCESS == $backendTransactionStatus;
 }
 /**
  * Reimplementation of vmPaymentPlugin::plgVmOnConfirmedOrder()
  *
  * @link http://nabvelocity.com/
  * Credit Cards Test Numbers
  * Visa Test Account           4007000000027
  * Amex Test Account           370000000000002
  * Master Card Test Account    6011000000000012
  * Discover Test Account       5424000000000015
  * @author Velocity Team
  */
 function plgVmConfirmedOrder(VirtueMartCart $cart, $order)
 {
     if (!($this->_currentMethod = $this->getVmPluginMethod($order['details']['BT']->virtuemart_paymentmethod_id))) {
         return NULL;
         // Another method was selected, do nothing
     }
     if (!$this->selectedThisElement($this->_currentMethod->payment_element)) {
         return FALSE;
     }
     $this->setInConfirmOrder($cart);
     $usrBT = $order['details']['BT'];
     $usrST = isset($order['details']['ST']) ? $order['details']['ST'] : '';
     $session = JFactory::getSession();
     $return_context = $session->getId();
     $payment_currency_id = shopFunctions::getCurrencyIDByName(self::VELOCITY_DEFAULT_PAYMENT_CURRENCY);
     $totalInPaymentCurrency = vmPSPlugin::getAmountInCurrency($order['details']['BT']->order_total, $payment_currency_id);
     $cd = CurrencyDisplay::getInstance($cart->pricesCurrency);
     if (!class_exists('ShopFunctions')) {
         require VMPATH_ADMIN . DS . 'helpers' . DS . 'shopfunctions.php';
     }
     $statecode = self::get2cStateByID($usrBT->virtuemart_state_id);
     $countrycode = self::get3cCountryByID($usrBT->virtuemart_country_id) == 'USA' ? self::get3cCountryByID($usrBT->virtuemart_country_id) : 'USA';
     $avsData = array('Street' => $usrBT->address_1 . ' ' . $usrBT->address_2, 'City' => $usrBT->city, 'StateProvince' => $statecode, 'PostalCode' => $usrBT->zip, 'Country' => $countrycode);
     $cardData = array('cardtype' => str_replace(' ', '', $this->_cc_type), 'pan' => $this->_cc_number, 'expire' => sprintf("%02d", $this->_cc_expire_month) . substr($this->_cc_expire_year, -2), 'cvv' => $this->_cc_cvv, 'track1data' => '', 'track2data' => '');
     $identitytoken = $this->_vmpCtable->identitytoken;
     $workflowid = $this->_vmpCtable->workflowid;
     $applicationprofileid = $this->_vmpCtable->applicationprofileid;
     $merchantprofileid = $this->_vmpCtable->merchantprofileid;
     if ($this->_vmpCtable->payment_mode) {
         $isTestAccount = TRUE;
     } else {
         $isTestAccount = FALSE;
     }
     include_once 'sdk' . DS . 'configuration.php';
     include_once 'sdk' . DS . 'Velocity.php';
     // Prepare data that should be stored in the database
     $dbValues['order_number'] = $order['details']['BT']->order_number;
     $dbValues['virtuemart_order_id'] = $order['details']['BT']->virtuemart_order_id;
     $dbValues['payment_method_id'] = $order['details']['BT']->virtuemart_paymentmethod_id;
     $dbValues['return_context'] = $return_context;
     $dbValues['payment_name'] = parent::renderPluginName($this->_currentMethod);
     $dbValues['cost_per_transaction'] = $this->_currentMethod->cost_per_transaction;
     $dbValues['cost_percent_total'] = $this->_currentMethod->cost_percent_total;
     $dbValues['payment_order_total'] = $totalInPaymentCurrency['value'];
     $dbValues['payment_currency'] = $payment_currency_id;
     $this->debugLog("before store", "plgVmConfirmedOrder", 'debug');
     $this->storePSPluginInternalData($dbValues);
     $errMsg = '';
     try {
         $velocityProcessor = new VelocityProcessor($applicationprofileid, $merchantprofileid, $workflowid, $isTestAccount, $identitytoken);
     } catch (Exception $e) {
         $this->error = TRUE;
         $errMsg .= '<br>' . vmText::_($e->getMessage());
     }
     /* Request for the verify avsdata and card data*/
     try {
         $response = $velocityProcessor->verify(array('amount' => $totalInPaymentCurrency['value'], 'avsdata' => $avsData, 'carddata' => $cardData, 'entry_mode' => 'Keyed', 'IndustryType' => 'Ecommerce', 'Reference' => 'xyz', 'EmployeeId' => '11'));
     } catch (Exception $e) {
         $this->error = TRUE;
         $errMsg .= '<br>' . vmText::_($e->getMessage());
     }
     if (is_array($response) && isset($response['Status']) && $response['Status'] == 'Successful') {
         /* Request for the authrizeandcapture transaction */
         try {
             $xml = VelocityXmlCreator::authorizeandcaptureXML(array('amount' => $totalInPaymentCurrency['value'], 'avsdata' => $avsData, 'token' => $response['PaymentAccountDataToken'], 'order_id' => $order['details']['BT']->order_number, 'entry_mode' => 'Keyed', 'IndustryType' => 'Ecommerce', 'Reference' => 'xyz', 'EmployeeId' => '11'));
             // got authorizeandcapture xml object.
             $req = $xml->saveXML();
             $obj_req = serialize($req);
             $cap_response = $velocityProcessor->authorizeAndCapture(array('amount' => $totalInPaymentCurrency['value'], 'avsdata' => $avsData, 'token' => $response['PaymentAccountDataToken'], 'order_id' => $order['details']['BT']->order_number, 'entry_mode' => 'Keyed', 'IndustryType' => 'Ecommerce', 'Reference' => 'xyz', 'EmployeeId' => '11'));
             if (is_array($cap_response) && !empty($cap_response) && isset($cap_response['Status']) && $cap_response['Status'] == 'Successful') {
                 /* save the authandcap response into 'virtuemart_payment_plg_velocity' custom table.*/
                 $response_fields['transaction_id'] = $cap_response['TransactionId'];
                 $response_fields['transaction_status'] = $cap_response['TransactionState'];
                 $response_fields['virtuemart_order_id'] = $order['details']['BT']->virtuemart_order_id;
                 $response_fields['request_obj'] = $obj_req;
                 $response_fields['response_obj'] = serialize($cap_response);
                 $this->storePSPluginInternalData($response_fields, 'virtuemart_order_id', TRUE);
                 $html = '<table class="adminlist table">' . "\n";
                 $html .= $this->getHtmlRow('VELOCITY_PAYMENT_NAME', $this->_vmpCtable->payment_name);
                 $html .= $this->getHtmlRow('VELOCITY_ORDER_NUMBER', $order['details']['BT']->order_number);
                 $html .= $this->getHtmlRow('VELOCITY_AMOUNT', $cap_response['Amount']);
                 $html .= $this->getHtmlRow('VMPAYMENT_VELOCITY_APPROVAL_CODE', $cap_response['ApprovalCode']);
                 if ($cap_response['TransactionId']) {
                     $html .= $this->getHtmlRow('VELOCITY_RESPONSE_TRANSACTION_ID', $cap_response['TransactionId']);
                 }
                 $html .= '</table>' . "\n";
                 $this->debugLog(vmText::_('VMPAYMENT_VELOCITY_ORDER_NUMBER') . " " . $order['details']['BT']->order_number . ' payment approved', '_handleResponse', 'debug');
                 $comment = 'ApprovalCode: ' . $cap_response['ApprovalCode'] . '<br>Transaction_Id: ' . $cap_response['TransactionId'];
                 $this->_clearVelocitySession();
                 $new_status = 'U';
             } else {
                 if (is_array($cap_response) && !empty($cap_response)) {
                     $this->error = TRUE;
                     $errMsg .= vmText::_($cap_response['StatusMessage']);
                 } else {
                     if (is_string($cap_response)) {
                         $this->error = TRUE;
                         $errMsg .= '<br>' . vmText::_($cap_response);
                     } else {
                         $this->error = TRUE;
                         $errMsg .= '<br>' . vmText::_('VMPAYMENT_VELOCITY_UNKNOWN_ERROR');
                     }
                 }
             }
         } catch (Exception $e) {
             $errMsg .= '<br>' . vmText::_($e->getMessage());
         }
     } else {
         if (is_array($response) && (isset($response['Status']) && $response['Status'] != 'Successful')) {
             $this->error = TRUE;
             $errMsg .= '<br>' . vmText::_($response['StatusMessage']);
         } else {
             if (is_string($response)) {
                 $this->error = TRUE;
                 $errMsg .= '<br>' . vmText::_($response);
             } else {
                 $this->error = TRUE;
                 $errMsg .= '<br>' . vmText::_('VMPAYMENT_VELOCITY_UNKNOWN_ERROR');
             }
         }
     }
     $this->debugLog($response, "plgVmConfirmedOrder", 'debug');
     $modelOrder = VmModel::getModel('orders');
     if ($this->error) {
         $this->debugLog($errMsg, 'getOrderIdByOrderNumber', 'message');
         $this->_handlePaymentCancel($order['details']['BT']->virtuemart_order_id, $errMsg);
         return;
     }
     $order['order_status'] = $new_status;
     $order['customer_notified'] = 1;
     $order['comments'] = $comment;
     $modelOrder->updateStatusForOneOrder($order['details']['BT']->virtuemart_order_id, $order, TRUE);
     //We delete the old stuff
     $cart->emptyCart();
     vRequest::setVar('html', $html);
 }
 $txnid = $db->Execute("SELECT `transaction_id` FROM " . TABLE_PAYMENT_VELOCITY_TRANSACTIONS . " WHERE `order_id` =" . $refundD['oID']);
 if (is_numeric($refund_am) && isset($txnid->fields['transaction_id'])) {
     $refund_ship = isset($_POST['shippingamount']) ? $_POST['shippingamount'] : 0;
     $refund_amount = (double) $refund_am + (double) $refund_ship;
     include 'Velocity.php';
     $identitytoken = MODULE_PAYMENT_VELOCITY_IDENTITYTOKEN;
     $workflowid = MODULE_PAYMENT_VELOCITY_WORKFLOWID;
     $applicationprofileid = MODULE_PAYMENT_VELOCITY_APPLICATIONPROFILEID;
     $merchantprofileid = MODULE_PAYMENT_VELOCITY_MERCHANTPROFILEID;
     if (MODULE_PAYMENT_VELOCITY_TESTMODE == 'Test') {
         $isTestAccount = TRUE;
     } else {
         $isTestAccount = FALSE;
     }
     try {
         $velocityProcessor = new VelocityProcessor($applicationprofileid, $merchantprofileid, $workflowid, $isTestAccount, $identitytoken);
     } catch (Exception $e) {
         $messageStack->add_session($e->getMessage(), 'error');
         zen_redirect(zen_href_link('velocityRefund'));
     }
     if ($refund_amount <= $order->info['total']) {
         try {
             // request for refund
             $response = $velocityProcessor->returnById(array('amount' => $refund_amount, 'TransactionId' => $txnid->fields['transaction_id']));
             $xml = VelocityXmlCreator::returnByIdXML(number_format($refund_amount, 2, '.', ''), $txnid->fields['transaction_id']);
             // got ReturnById xml object.
             $req = $xml->saveXML();
             $myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
             $txt = print_r($response, 1);
             fwrite($myfile, $txt);
             fclose($myfile);
 /**
  * Post-processing activities for send detail to velocity gateway for the verify the detail and process the payment 
  * Trought velocity gateway and return response.
  * 
  * @return boolean
  */
 function after_process()
 {
     include_once 'includes/sdk/Velocity.php';
     global $order, $insert_id, $db, $messageStack;
     $identitytoken = MODULE_PAYMENT_VELOCITY_IDENTITYTOKEN;
     $workflowid = MODULE_PAYMENT_VELOCITY_WORKFLOWID;
     $applicationprofileid = MODULE_PAYMENT_VELOCITY_APPLICATIONPROFILEID;
     $merchantprofileid = MODULE_PAYMENT_VELOCITY_MERCHANTPROFILEID;
     if (MODULE_PAYMENT_VELOCITY_TESTMODE == 'Test') {
         $isTestAccount = TRUE;
     } else {
         $isTestAccount = FALSE;
     }
     try {
         $velocityProcessor = new VelocityProcessor($applicationprofileid, $merchantprofileid, $workflowid, $isTestAccount, $identitytoken);
     } catch (Exception $e) {
         $_SESSION['error'] = $e->getMessage();
         $messageStack->add_session(FILENAME_CHECKOUT_FAILURE, $e->getMessage() . '<!-- [' . $this->code . '] -->', 'error');
         zen_redirect(zen_href_link(FILENAME_CHECKOUT_FAILURE, '', 'SSL', true, false));
     }
     $avsData = unserialize(base64_decode($_SESSION['avsdata']));
     $cardData = unserialize(base64_decode($_SESSION['carddata']));
     /* Request for the verify avsdata and card data*/
     try {
         $response = $velocityProcessor->verify(array('amount' => $order->info['total'], 'avsdata' => $avsData, 'carddata' => $cardData, 'entry_mode' => 'Keyed', 'IndustryType' => 'Ecommerce', 'Reference' => 'xyz', 'EmployeeId' => '11'));
     } catch (Exception $e) {
         $_SESSION['error'] = $e->getMessage();
         $messageStack->add_session(FILENAME_CHECKOUT_FAILURE, $e->getMessage() . '<!-- [' . $this->code . '] -->', 'error');
         zen_redirect(zen_href_link(FILENAME_CHECKOUT_FAILURE, '', 'SSL', true, false));
     }
     $errors = '';
     if (is_array($response) && isset($response['Status']) && $response['Status'] == 'Successful') {
         /* Request for the authrizeandcapture transaction */
         try {
             $cap_response = $velocityProcessor->authorizeAndCapture(array('amount' => $order->info['total'], 'avsdata' => $avsData, 'token' => $response['PaymentAccountDataToken'], 'order_id' => $insert_id, 'entry_mode' => 'Keyed', 'IndustryType' => 'Ecommerce', 'Reference' => 'xyz', 'EmployeeId' => '11'));
             $xml = VelocityXmlCreator::authorizeandcaptureXML(array('amount' => $order->info['total'], 'avsdata' => $avsData, 'token' => $response['PaymentAccountDataToken'], 'order_id' => $insert_id, 'entry_mode' => 'Keyed', 'IndustryType' => 'Ecommerce', 'Reference' => 'xyz', 'EmployeeId' => '11'));
             // got authorizeandcapture xml object.
             $req = $xml->saveXML();
             if (is_array($cap_response) && !empty($cap_response) && isset($cap_response['Status']) && $cap_response['Status'] == 'Successful') {
                 /* save the transaction detail with that order.*/
                 $sql = "insert into " . TABLE_ORDERS_STATUS_HISTORY . " (comments, orders_id, orders_status_id, customer_notified, date_added) values (:orderComments, :orderID, :orderStatus, 1, now() )";
                 $sql = $db->bindVars($sql, ':orderComments', 'Credit Card - Velocity payment.  ApprovalCode: ' . $cap_response['ApprovalCode'] . '. TransID: ' . $cap_response['TransactionId'] . '.', 'string');
                 $sql = $db->bindVars($sql, ':orderID', $insert_id, 'integer');
                 $sql = $db->bindVars($sql, ':orderStatus', 2, 'integer');
                 $db->Execute($sql);
                 /* save the authandcap response into 'zen_velocity_transactions' custom table.*/
                 $sql = "insert into " . TABLE_PAYMENT_VELOCITY_TRANSACTIONS . " (transaction_id, transaction_status, order_id, request_obj, response_obj) values (:transactionId, :transactionStatus, :orderID, :requestOBJ, :responseOBJ)";
                 $sql = $db->bindVars($sql, ':transactionId', $cap_response['TransactionId'], 'string');
                 $sql = $db->bindVars($sql, ':transactionStatus', $cap_response['Status'], 'string');
                 $sql = $db->bindVars($sql, ':orderID', $insert_id, 'string');
                 $sql = $db->bindVars($sql, ':requestOBJ', serialize($req), 'string');
                 $sql = $db->bindVars($sql, ':responseOBJ', serialize($cap_response), 'string');
                 $db->Execute($sql);
                 /* for update the order status */
                 $db->Execute("update " . TABLE_ORDERS . " set orders_status = 2 where orders_id='" . $insert_id . "'");
             } else {
                 if (is_array($cap_response) && !empty($cap_response)) {
                     $errors .= $cap_response['StatusMessage'];
                 } else {
                     if (is_string($cap_response)) {
                         $errors .= $cap_response;
                     } else {
                         $errors .= 'Unknown Error in authandcap process please contact the site admin';
                     }
                 }
             }
         } catch (Exception $e) {
             $errors .= $e->getMessage();
         }
     } else {
         if (is_array($response) && (isset($response['Status']) && $response['Status'] != 'Successful')) {
             $errors .= $response['StatusMessage'];
         } else {
             if (is_string($response)) {
                 $errors .= $response;
             } else {
                 $errors .= 'Unknown Error in verification process please contact the site admin';
             }
         }
     }
     if ($errors != '') {
         $_SESSION['error'] = $errors;
         $messageStack->add_session(FILENAME_CHECKOUT_FAILURE, $errors . '<!-- [' . $this->code . '] -->', 'error');
         zen_redirect(zen_href_link(FILENAME_CHECKOUT_FAILURE, '', 'SSL', true, false));
     }
     return true;
 }
 public function send()
 {
     if ($this->request->post['cc_owner'] == '') {
         $json['error'] = 'Card Qwner name is required.';
     } else {
         if (!preg_match('/^[a-zA-Z ]+$/', $this->request->post['cc_owner'])) {
             $json['error'] = 'Card Qwner name is like john dev.';
         } else {
             if (!preg_match('/^[0-9]*$/', $this->request->post['cc_number'])) {
                 $json['error'] = 'Credit card number is required digits only';
             } else {
                 if (!(strlen($this->request->post['cc_number']) >= 12 && strlen($this->request->post['cc_number']) <= 16)) {
                     $json['error'] = 'Credit card number is must be 12 to 16 digit only';
                 } else {
                     if (!preg_match('/^[0-9]*$/', $this->request->post['cc_cvv2'])) {
                         $json['error'] = 'CVV number is required digits only';
                     } else {
                         if (!(strlen($this->request->post['cc_cvv2']) >= 3 && strlen($this->request->post['cc_cvv2']) <= 4)) {
                             $json['error'] = 'CVV number is must be 3 to 4 digit only';
                         }
                     }
                 }
             }
         }
     }
     if (!isset($json['error'])) {
         include_once 'sdk/Velocity.php';
         $identitytoken = $this->config->get('velocitycreditcard_identitytoken');
         $workflowid = $this->config->get('velocitycreditcard_workflowid');
         $applicationprofileid = $this->config->get('velocitycreditcard_applicationprofileid');
         $merchantprofileid = $this->config->get('velocitycreditcard_merchantprofileid');
         if ($this->config->get('velocitycreditcard_test')) {
             $isTestAccount = TRUE;
         } else {
             $isTestAccount = FALSE;
         }
         try {
             $velocityProcessor = new VelocityProcessor($applicationprofileid, $merchantprofileid, $workflowid, $isTestAccount, $identitytoken);
         } catch (Exception $e) {
             $json['error'] = $e->getMessage();
         }
         if (!isset($json['error'])) {
             $this->load->model('checkout/order');
             $order_info = $this->model_checkout_order->getOrder($this->session->data['order_id']);
             $avsData = array('Street' => $order_info['payment_address_1'] . ' ' . $order_info['payment_address_2'], 'City' => $order_info['payment_city'], 'StateProvince' => $order_info['payment_zone_code'], 'PostalCode' => $order_info['payment_postcode'], 'Country' => $order_info['payment_iso_code_3']);
             $cardData = array('cardtype' => str_replace(' ', '', $this->request->post['cc_type']), 'pan' => $this->request->post['cc_number'], 'expire' => $this->request->post['cc_expire_date_month'] . substr($this->request->post['cc_expire_date_year'], -2), 'cvv' => $this->request->post['cc_cvv2'], 'track1data' => '', 'track2data' => '');
             /* Request for the verify avsdata and card data*/
             try {
                 $response = $velocityProcessor->verify(array('amount' => $order_info['total'], 'avsdata' => $avsData, 'carddata' => $cardData, 'entry_mode' => 'Keyed', 'IndustryType' => 'Ecommerce', 'Reference' => 'xyz', 'EmployeeId' => '11'));
             } catch (Exception $e) {
                 $json['error'] = $e->getMessage();
             }
             if (is_array($response) && isset($response['Status']) && $response['Status'] == 'Successful') {
                 /* Request for the authrizeandcapture transaction */
                 try {
                     $cap_response = $velocityProcessor->authorizeAndCapture(array('amount' => $order_info['total'], 'avsdata' => $avsData, 'token' => $response['PaymentAccountDataToken'], 'order_id' => $order_info['order_id'], 'entry_mode' => 'Keyed', 'IndustryType' => 'Ecommerce', 'Reference' => 'xyz', 'EmployeeId' => '11'));
                     $xml = VelocityXmlCreator::authorizeandcaptureXML(array('amount' => $order_info['total'], 'avsdata' => $avsData, 'token' => $response['PaymentAccountDataToken'], 'order_id' => $order_info['order_id'], 'entry_mode' => 'Keyed', 'IndustryType' => 'Ecommerce', 'Reference' => 'xyz', 'EmployeeId' => '11'));
                     // got authorizeandcapture xml object.
                     $req = $xml->saveXML();
                     $obj_req = serialize($req);
                     if (is_array($cap_response) && !empty($cap_response) && isset($cap_response['Status']) && $cap_response['Status'] == 'Successful') {
                         $log = 'Payment has been successfully done Transaction Id is ' . $cap_response['TransactionId'];
                         /* save the transaction detail with that order.*/
                         $this->db->query("INSERT INTO `" . DB_PREFIX . "velocity_transactions`\n                                SET transaction_id = '" . $cap_response['TransactionId'] . "',\n                                transaction_status = '" . $cap_response['CaptureState'] . "',\n                                order_id = '" . $this->db->escape($order_info['order_id']) . "',\n                                request_obj = '" . $obj_req . "',    \n                                response_obj = '" . serialize($cap_response) . "'");
                         /* save the authandcap response into 'zen_velocity_transactions' custom table.*/
                         if ($this->session->data['payment_method']['code'] == 'velocitycreditcard') {
                             $this->load->model('checkout/order');
                             //order status pending code is 1
                             $this->model_checkout_order->addOrderHistory($this->session->data['order_id'], 1, "Velocity Txn id" . $cap_response['TransactionId'] . "<br>Txn status is " . $cap_response['CaptureState'] . " <br> Approval code is " . $cap_response['ApprovalCode']);
                         }
                         $this->log->write($log);
                         $json['redirect'] = $this->url->link('checkout/success', $cap_response['TransactionId'], 'SSL');
                     } else {
                         if (is_array($cap_response) && !empty($cap_response)) {
                             $json['error'] = $cap_response['StatusMessage'];
                             $json['redirect'] = $this->url->link('checkout/failure', $json['error'], 'SSL');
                         } else {
                             if (is_string($cap_response)) {
                                 $json['error'] = $cap_response;
                                 $json['redirect'] = $this->url->link('checkout/failure', $json['error'], 'SSL');
                             } else {
                                 $json['error'] = 'Unknown Error in authandcap process please contact the site admin';
                                 $json['redirect'] = $this->url->link('checkout/failure', $json['error'], 'SSL');
                             }
                         }
                     }
                 } catch (Exception $e) {
                     $json['redirect'] = $this->url->link('checkout/failure', $e->getMessage(), 'SSL');
                 }
             } else {
                 if (is_array($response) && (isset($response['Status']) && $response['Status'] != 'Successful')) {
                     $json['error'] = $response['StatusMessage'];
                 } else {
                     if (is_string($response)) {
                         $json['error'] = $response;
                     } else {
                         $json['error'] = 'Unknown Error in verification process please contact the site admin';
                     }
                 }
             }
         }
     }
     if (isset($json['error'])) {
         $this->log->write($json['error']);
         if ($this->session->data['payment_method']['code'] == 'velocitycreditcard') {
             $this->load->model('checkout/order');
             //order status failed code is 10
             $this->model_checkout_order->addOrderHistory($this->session->data['order_id'], 10);
         }
     }
     $this->response->addHeader('Content-Type: application/json');
     $this->response->setOutput(json_encode($json));
 }
 public function refund()
 {
     $this->load->model('payment/velocitycreditcard');
     require_once '././../sdk/Velocity.php';
     $json['error'] = '';
     $json['success'] = '';
     $identitytoken = $this->config->get('velocitycreditcard_identitytoken');
     $workflowid = $this->config->get('velocitycreditcard_workflowid');
     $applicationprofileid = $this->config->get('velocitycreditcard_applicationprofileid');
     $merchantprofileid = $this->config->get('velocitycreditcard_merchantprofileid');
     if ($this->config->get('velocitycreditcard_test')) {
         $isTestAccount = TRUE;
     } else {
         $isTestAccount = FALSE;
     }
     try {
         $velocityProcessor = new VelocityProcessor($applicationprofileid, $merchantprofileid, $workflowid, $isTestAccount, $identitytoken);
     } catch (Exception $e) {
         echo $e->getMessage();
         $json['error'] .= $e->getMessage();
     }
     $this->load->model('sale/order');
     $order_info = $this->model_sale_order->getOrder($this->request->post['order_id']);
     $order_shipping = $this->model_payment_velocitycreditcard->getShipping($this->request->post['order_id']);
     $sub_total = $this->currency->format($order_info['total'], $order_info['currency_code'], $order_info['currency_value'], false) - $this->currency->format($order_shipping, $order_info['currency_code'], $order_info['currency_value'], false);
     if ((double) $sub_total >= (double) $this->request->post['amount']) {
         try {
             $query = $this->db->query("select transaction_id from " . DB_PREFIX . "velocity_transactions where order_id =" . $this->request->post['order_id']);
             if (!isset($query->row['transaction_id'])) {
                 throw new Exception('Transaction id not found for the Order', '500');
             }
             $transaction_id = $query->row['transaction_id'];
             $refund_amount = $this->request->post['shipping'] === 'true' ? $this->request->post['amount'] + $order_shipping : $this->request->post['amount'];
             // request for refund
             $response = $velocityProcessor->returnById(array('amount' => $refund_amount, 'TransactionId' => $transaction_id));
             if (is_array($response) && !empty($response) && isset($response['Status']) && $response['Status'] == 'Successful') {
                 $xml = VelocityXmlCreator::returnByIdXML(number_format($refund_amount, 2, '.', ''), $transaction_id);
                 // got ReturnById xml object.
                 $req = $xml->saveXML();
                 /* save the returnbyid response into 'zen_velocity_transactions' custom table.*/
                 $this->db->query("insert into " . DB_PREFIX . "velocity_transactions (transaction_id, transaction_status, order_id, request_obj, response_obj) values('" . $response['TransactionId'] . "', '" . $response['TransactionState'] . "', '" . $this->request->post['order_id'] . "', '" . serialize($req) . "', '" . serialize($response) . "')");
                 $json['success'] .= 'Refund has been done successfully, txnid : ' . $response['TransactionId'];
                 //order status pending code is 1
                 $this->model_payment_velocitycreditcard->addOrderHistory($this->request->post['order_id'], 11, "Velocity Txn id" . $response['TransactionId'] . "<br>Txn status is " . $response['TransactionState'] . " <br> Amount is " . $refund_amount);
             } else {
                 if (is_array($response) && !empty($response)) {
                     $json['error'] .= $response['StatusMessage'];
                 } else {
                     if (is_string($response)) {
                         $json['error'] .= $response;
                     } else {
                         $json['error'] .= 'Unknown Error please contact the site admin';
                     }
                 }
             }
         } catch (Exception $e) {
             $json['error'] .= $e->getMessage();
         }
     } else {
         $json['error'] .= 'Refund amount can not be greater than ' . $sub_total . '  + shipping.';
     }
     $this->response->setOutput(json_encode($json));
 }