Example #1
0
 public static function returnUnlinkedXML($data)
 {
     $xml = new DOMDocument("1.0");
     $root = $xml->createElement("ReturnTransaction");
     $xml->appendChild($root);
     $root->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:i', 'http://www.w3.org/2001/XMLSchema-instance');
     $root->setAttribute('xmlns', 'http://schemas.ipcommerce.com/CWS/v2.0/Transactions/Rest');
     $root->setAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'i:type', 'ReturnTransaction');
     return VelocityXmlCreator::transaction_XML($xml, $root, $data);
 }
 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);
         $columns = array('transaction_id', 'transaction_status', 'virtuemart_order_id', 'request_obj', 'response_obj', 'created_on', 'created_by', 'modified_on', 'modified_by');
         $values = array($db->quote($response['TransactionId']), $db->quote($response['TransactionState']), (int) $_POST['orderid'], $db->quote(serialize($req)), $db->quote(serialize($response)), $db->quote($date->format(JDate::$format)), (int) $_POST['userid'], $db->quote($date->format(JDate::$format)), (int) $_POST['userid']);
         $queryR->insert($db->quoteName('#__virtuemart_payment_plg_velocity'))->columns($db->quoteName($columns))->values(implode(',', $values));
         $db->setQuery($queryR);
         $flagR = $db->execute();
         /* Update the refund detail into comment table at admin order detail..*/
         $comment = 'ApprovalCode: ' . $response['ApprovalCode'] . '<br>Refund Transaction_Id: ' . $response['TransactionId'] . '<br> Order Total: ' . round($order_total, 2) . ' ' . $_POST['currency'] . '<br>Refunded Amount:' . $response['Amount'] . ' ' . $_POST['currency'];
         $queryH = $db->getQuery(true);
Example #3
0
 /**
  * 
  * @param Varien_Object $payment
  * @param type $amount
  * @return of type Velocity_CreditCard_Model_Payment class $this object.
  */
 public function refund(Varien_Object $payment, $amount)
 {
     Mage::log($amount, 1);
     try {
         $this->_callVelocityGateway();
         $response = $this->velocityProcessor->returnById(array('amount' => $amount, 'TransactionId' => $payment->_data['last_trans_id']));
         $xml = VelocityXmlCreator::returnByIdXML(number_format($amount, 2, '.', ''), $payment->_data['last_trans_id']);
         // got ReturnById xml object.
         $req = $xml->saveXML();
         $obj_req = serialize($req);
         Mage::log(print_r($response, 1));
         if (is_array($response) && !empty($response) && isset($response['Status']) && $response['Status'] == 'Successful') {
             $payment->setTransactionId($response['TransactionId']);
             $payment->setIsTransactionClosed(1);
             $insertData = array('transaction_id' => $response['TransactionId'], 'transaction_status' => $response['Status'], 'order_id' => $response['OrderId'], 'request_obj' => $obj_req, 'response_obj' => json_encode($response));
             $collectionSet = Mage::getModel('creditcard/card');
             $collectionSet->setData($insertData)->save();
         } else {
             if (is_array($response) && !empty($response)) {
                 $errorMsg = $this->_getHelper()->__($response['StatusMessage']);
             } else {
                 $errorMsg = $this->_getHelper()->__($response);
             }
         }
     } catch (Exception $e) {
         Mage::throwException($e->getMessage());
     }
     if (isset($errorMsg) && !empty($errorMsg)) {
         Mage::throwException($errorMsg);
     }
     return $this;
 }
 /**
  * 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);
 }
Example #5
0
 /**
  * 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;
 }
 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);
         if (is_array($response) && !empty($response) && isset($response['Status']) && $response['Status'] == 'Successful') {
             /* save the returnbyid 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', $response['TransactionId'], 'string');
             $sql = $db->bindVars($sql, ':transactionStatus', $response['Status'], 'string');
             $sql = $db->bindVars($sql, ':orderID', $refundD['oID'], 'string');
             $sql = $db->bindVars($sql, ':requestOBJ', serialize($req), 'string');
             $sql = $db->bindVars($sql, ':responseOBJ', serialize($response), 'string');
             $db->Execute($sql);
Example #7
0
 public function returnUnlinked($options = array())
 {
     try {
         $xml = VelocityXmlCreator::returnUnlinkedXML($options);
         // got ReturnById xml object.
         $xml->formatOutput = TRUE;
         $body = $xml->saveXML();
         //echo '<xmp>'.$body.'</xmp>';
         list($error, $response) = $this->connection->post($this->path(self::$workflowid, null, self::$Txn_method[7]), array('sessiontoken' => $this->sessionToken, 'xml' => $body, 'method' => self::$Txn_method[7]));
         return $this->handleResponse($error, $response);
         //return $response;
     } catch (Exception $e) {
         throw new Exception($e->getMessage());
     }
 }
Example #8
0
 /**
  * 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));
 }