Example #1
0
 /**
  * Capture payment
  *
  * @param   Varien_Object $orderPayment
  * @param float $amount
  * @return  Mage_Payment_Model_Abstract
  */
 public function capture(Varien_Object $payment, $amount)
 {
     $quote = $this->_getQuote();
     $vpstxid = trim($quote->getPayment()->getRepeatCode());
     $transaction = Mage::getModel('sagepaysuite2/sagepaysuite_transaction')->loadByVpsTxId($vpstxid);
     if ($transaction->getId()) {
         //Retrieve Quote's currency code, it may differ with original transaction
         $currencyCode = $this->getConfigCurrencyCode($quote);
         //REPEAT payment
         $rs = $this->repeat($transaction, $amount, $currencyCode);
         Mage::getSingleton('sagepaysuite/session')->setLastVendorTxCode($rs['_requestvendor_']);
         if ($rs['Status'] == 'OK') {
             //Allow different currency than the original transaction
             $transactionCurrency = !is_null($currencyCode) ? $currencyCode : $transaction->getTrnCurrency();
             $repeatTransaction = clone $transaction;
             $repeatTransaction->setId(null)->setOrderId(null)->setReleased(null)->setStatus($rs['Status'])->setStatusDetail($rs['StatusDetail'])->setVpsTxId($rs['VPSTxId'])->setTxAuthNo($rs['TxAuthNo'])->setSecurityKey($rs['SecurityKey'])->setIntegration($transaction->getIntegration())->setVendorTxCode($rs['_requestvendor_'])->setVpsProtocol($transaction->getVpsProtocol())->setVendorname($transaction->getVendorname())->setMode($transaction->getMode())->setTxType(strtoupper($rs['_requesttxtype_']))->setTrnCurrency($transactionCurrency)->setTrndate($this->getDate())->save();
             if (isset($rs['_requesttxtype_']) && $rs['_requesttxtype_'] == parent::REQUEST_TYPE_REPEATDEFERRED) {
                 $this->release($repeatTransaction, $amount);
             }
             //If we don't do this, refund online is not available.
             $payment->setLastTransId($rs['VPSTxId']);
         } else {
             Mage::throwException(Mage::helper('sagepaysuite')->__($rs['StatusDetail']));
         }
     } else {
         Mage::throwException(Mage::helper('sagepaysuite')->__('Transaction was not found.'));
     }
     return $this;
 }
 public function order(Varien_Object $payment, $amount)
 {
     $order = $payment->getOrder();
     $order_id = $order->getId();
     $order_increment_id = $order->getIncrementId();
     $store_id = $order->getStoreId();
     $ccType = $payment->getCcType();
     // reorder
     $reorder_increment_id = explode('-', $order_increment_id);
     // reorder
     $order_increment_id = $reorder_increment_id[0];
     $order_suffix_id = @$reorder_increment_id[1];
     $expiration = strtotime('+' . $this->_getStoreConfig($ccType, 'expiration') . 'days');
     $transaction_expiration = date('Y-m-d', $expiration);
     $increment = $this->_getStoreConfig('slips', 'order_id_increment');
     $order_increment_prefix = $this->_getOrderIncrementPrefix($store_id);
     $number = $order_increment_id - $order_increment_prefix;
     if (!empty($order_suffix_id)) {
         $number *= pow(10, strlen($order_suffix_id));
         $number += $order_suffix_id;
     }
     $number += $increment;
     $data = array('order_id' => $order_id, 'amount' => $amount, 'expiration' => $transaction_expiration, 'number' => $number);
     $result = Mage::getModel('utils/sql')->insert('gamuza_slips_transactions', $data);
     if (!$result) {
         Mage::throwException(Mage::helper('slips')->__('Unable to save the Slip and Deposit informations. Please verify your database.'));
     }
     $this->setStore($payment->getOrder()->getStoreId());
     $payment->setAmount($amount);
     $payment->setLastTransId($order_id);
     $payment->setStatus(self::STATUS_APPROVED);
     return $this;
 }
Example #3
0
 public function authorize(Varien_Object $payment, $amount)
 {
     $payment->setLastTransId($this->getTransactionId())->setIsTransactionPending(true);
     // create payment link and add it to comment history and send to shopper
     $order = $payment->getOrder();
     /*
      * Do not send a email notification when order is created.
      * Only do this on the AUHTORISATION notification.
      * This is needed for old versions where there is no check if email is already send
      */
     //        $order->setCanSendNewEmailFlag(false);
     $fields = $this->getFormFields();
     $url = $this->getFormUrl();
     $count = 0;
     $size = count($fields);
     foreach ($fields as $field => $value) {
         if ($count == 0) {
             $url .= "?";
         }
         $url .= urlencode($field) . "=" . urlencode($value);
         if ($count != $size) {
             $url .= "&";
         }
         ++$count;
     }
     $comment = "<a target=\"_blank\" href=\"" . $url . "\">Generated payment url</a>";
     $status = $this->_getConfigData('order_status');
     $payment->getOrder()->addStatusHistoryComment($comment, $status);
     $payment->setAdditionalInformation('payment_url', $url);
     // send out email to shopper
     //        $templateId = "Fav Email";
     //
     //        $emailTemplate = Mage::getModel('core/email_template')->loadByCode($templateId);
     //
     //        $vars = array('user_name' => $userName, 'product_name' => $productName);
     //
     //        $emailTemplate->getProcessedTemplate($vars);
     //
     //        $emailTemplate->setSenderEmail(Mage::getStoreConfig('trans_email/ident_general/email', $storeId));
     //
     //        $emailTemplate->setSenderName(Mage::getStoreConfig('trans_email/ident_general/name', $storeId));
     //
     //
     //        $emailTemplate->send($receiveEmail,$receiveName, $vars);
     //        $order->
     //        $order->sendNewOrderEmail(); // send order email
     return $this;
 }
Example #4
0
 public function authorize(Varien_Object $payment, $amount)
 {
     $payment->setLastTransId($this->getTransactionId())->setIsTransactionPending(true);
     $order = $payment->getOrder();
     /*
      * Do not send a email notification when order is created.
      * Only do this on the AUHTORISATION notification.
      * This is needed for old versions where there is no check if email is already send
      */
     $order->setCanSendNewEmailFlag(false);
     if (Mage::app()->getStore()->isAdmin()) {
         $storeId = $payment->getOrder()->getStoreId();
     } else {
         $storeId = null;
     }
     $merchantAccount = trim($this->_getConfigData('merchantAccount', 'adyen_abstract', $storeId));
     $incrementId = $order->getIncrementId();
     $orderCurrencyCode = $order->getOrderCurrencyCode();
     $customerId = $order->getCustomerId();
     $amount = Mage::helper('adyen')->formatAmount($amount, $orderCurrencyCode);
     // do cash API
     $request = array("merchantAccount" => $merchantAccount, "shopperReference" => $customerId, "variantCode" => 'c_cash', "reference" => $incrementId, "amount.value" => $amount, "amount.currency" => $orderCurrencyCode);
     $ch = curl_init();
     $isConfigDemoMode = $this->getConfigDataDemoMode($storeId = null);
     $wsUsername = $this->getConfigDataWsUserName($storeId);
     $wsPassword = $this->getConfigDataWsPassword($storeId);
     if ($isConfigDemoMode) {
         curl_setopt($ch, CURLOPT_URL, "https://pal-test.adyen.com/pal/servlet/CustomPayment/beginCustomPayment");
     } else {
         curl_setopt($ch, CURLOPT_URL, "https://pal-live.adyen.com/pal/servlet/CustomPayment/beginCustomPayment");
     }
     curl_setopt($ch, CURLOPT_HEADER, false);
     curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
     curl_setopt($ch, CURLOPT_USERPWD, $wsUsername . ":" . $wsPassword);
     curl_setopt($ch, CURLOPT_POST, count($request));
     curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($request));
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     $results = curl_exec($ch);
     $httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
     if ($httpStatus != 200) {
         Mage::throwException(Mage::helper('adyen')->__('HTTP Status code %s received, data %s', $httpStatus, $results));
     }
     if ($results === false) {
         Mage::throwException(Mage::helper('adyen')->__('Got an empty response, status code %s', $httpStatus));
     }
 }
Example #5
0
 /**
  * Check customer credit via capayable
  *
  * @param Varien_Object $payment
  * @param float $amount
  * @return $this|Mage_Payment_Model_Abstract
  * @throws Mage_Payment_Model_Info_Exception
  */
 public function authorize(Varien_Object $payment, $amount)
 {
     if ($amount <= 0) {
         Mage::throwException(Mage::helper('capayable')->__('The amount due must be greater than 0.'));
     }
     // Convert amount to cents
     $amount = $this->getHelper()->convertToCents($amount);
     $_order = $payment->getOrder();
     // Load saved capayable customer if exists. Otherwise load empty model.
     $capayableCustomer = Mage::getModel('capayable/customer')->loadByEmail($_order->getCustomerEmail());
     // Throw exception if capayable can't provide customer credit
     $result = $this->checkCredit($capayableCustomer, $amount, true);
     if (!$result->getIsAccepted()) {
         throw new Mage_Payment_Model_Info_Exception(Mage::helper('capayable')->__('The payment was refused by Capayable') . ": " . Mage::helper('capayable')->__(Tritac_CapayableApiClient_Enums_RefuseReason::toString($result->getRefuseReason())) . " " . Mage::helper('capayable')->__('For additional information contact Capayable on +31 40 - 259 5072.'));
     }
     $_order->setState(Mage::helper('capayable')->getOrderStatus($_order->getStore()), true, Mage::helper('capayable')->__('Order is authorized by Capayable with transaction ID %s', $result->getTransactionNumber()), null, false);
     // Set magento transaction id which returned from capayable
     $payment->setLastTransId($result->getTransactionNumber());
     return $this;
 }
 /**
  * Refund the card transaction through gateway
  *
  * @param Mage_Payment_Model_Info $payment
  * @param $amount
  * @param Varien_Object $card
  * @return bool|Mage_Sales_Model_Order_Payment_Transaction
  */
 protected function _refundCardTransaction($payment, $amount, $card)
 {
     /**
      * Card has last transaction with type "refund" when all captured amount is refunded.
      * Until this moment card has last transaction with type "capture".
      */
     $credit_memo = Mage::registry('current_creditmemo');
     $captureTransactionId = $credit_memo->getInvoice()->getTransactionId();
     $captureTransaction = $payment->getTransaction($captureTransactionId);
     $realCaptureTransactionId = $captureTransaction->getAdditionalInformation($this->_realTransactionIdKey);
     $payment->setChasePaymentechTransType(Gorilla_ChasePaymentech_Model_Profile::TRANS_TYPE_REFUND);
     $payment->setTransId($realCaptureTransactionId);
     $payment->setAmount($amount);
     $result = $this->_postRequest($payment);
     switch ($result->getResponseCode()) {
         case self::RESPONSE_CODE_NEW_ORDER_SUCCESS:
             if ($result->getApprovalCode() == self::RESPONSE_APPROVAL_STATUS) {
                 $refundTransactionId = $result->getTransactionId() . '-refund';
                 $shouldCloseCaptureTransaction = 0;
                 /**
                  * If it is last amount for refund, transaction with type "capture" will be closed
                  * and card will has last transaction with type "refund"
                  */
                 if ($this->_formatAmount($card->getCapturedAmount() - $card->getRefundedAmount()) == $amount) {
                     $card->setLastTransId($refundTransactionId);
                     $shouldCloseCaptureTransaction = 1;
                 }
                 return $this->_addTransaction($payment, $refundTransactionId, Mage_Sales_Model_Order_Payment_Transaction::TYPE_REFUND, array('is_transaction_closed' => 1, 'should_close_parent_transaction' => $shouldCloseCaptureTransaction, 'parent_transaction_id' => $captureTransactionId), array($this->_realTransactionIdKey => $result->getTransactionId()), Mage::helper('paygate')->getTransactionMessage($payment, $payment->getChasePaymentechTransType(), $result->getTransactionId(), $card, $amount));
             }
             $exceptionMessage = $this->_wrapGatewayError($result->getResponseReasonText());
             break;
         case self::RESPONSE_CODE_DECLINED:
             //case self::RESPONSE_CODE_ERROR:
             $exceptionMessage = $this->_wrapGatewayError($result->getResponseReasonText());
             break;
         default:
             $exceptionMessage = $this->_getHelper()->__('Payment refunding error.');
             break;
     }
     $exceptionMessage = Mage::helper('paygate')->getTransactionMessage($payment, $payment->getChasePaymentechTransType(), $realCaptureTransactionId, $card, $amount, $exceptionMessage);
     Mage::throwException($exceptionMessage);
     return false;
 }
 public function authorize(Varien_Object $payment, $amount)
 {
     $order = $payment->getOrder();
     $order_id = $order->getId();
     $order_increment_id = $order->getIncrementId();
     $quote = $order->getQuote();
     $store_id = $order->getStoreId();
     $ccType = $payment->getCcType();
     $code = $this->_getStoreConfig('code');
     $key = $this->_getStoreConfig('key');
     $obs = $this->_getStoreConfig('obs');
     $obsadd1 = $this->_getStoreConfig('obsadd1');
     $obsadd2 = $this->_getStoreConfig('obsadd2');
     $obsadd3 = $this->_getStoreConfig('obsadd3');
     $tax_vat = $order->getCustomer()->getTaxvat();
     $address = $quote->getBillingAddress();
     $name = $address->getName();
     $street1 = $address->getStreet1();
     $street2 = $address->getStreet2();
     $postcode = $address->getPostcode();
     $city = $address->getCity();
     $region = $address->getRegion();
     $expiration = strtotime('+' . $this->_getStoreConfig('expiration') . 'days');
     $bank_expiration = date('dmY', $expiration);
     $transaction_expiration = date('Y-m-d', $expiration);
     $return_url = $this->_getStoreConfig('return_url');
     $increment = $this->_getStoreConfig('order_id_increment');
     $order_increment_prefix = $this->_getOrderIncrementPrefix($store_id);
     $number = $order_increment_id - $order_increment_prefix + $increment;
     $submit_dc = Mage::getModel('itaushopline/itaucripto')->geraDados($code, $number, str_replace('.', "", number_format($amount, 2, ',', '.')), $obs, $key, $name, '01', $tax_vat, $street1, $street2, $postcode, $city, $region, $bank_expiration, $return_url, $obsadd1, $obsadd2, $obsadd3);
     if (strlen($submit_dc) < self::ITAU_SHOPLINE_SUBMIT_TRANSACTION_LENGTH) {
         Mage::throwException(Mage::helper('itaushopline')->__('Unable to generate submit transaction code. Please check your settings.'));
     }
     $query_dc = Mage::getModel('itaushopline/itaucripto')->geraConsulta($code, $number, '0', $key);
     if (strlen($query_dc) < self::ITAU_SHOPLINE_QUERY_TRANSACTION_LENGTH) {
         Mage::throwException(Mage::helper('itaushopline')->__('Unable to generate query transaction code. Please check your settings.'));
     }
     $data = array('order_id' => $order_id, 'amount' => $amount, 'expiration' => $transaction_expiration, 'number' => $number, 'submit_dc' => $submit_dc, 'query_dc' => $query_dc);
     $result = Mage::getModel('utils/sql')->insert('gamuza_itaushopline_transactions', $data);
     if (!$result) {
         Mage::throwException(Mage::helper('itaushopline')->__('Unable to save the Itau ShopLine informations. Please verify your database.'));
     }
     $this->setStore($payment->getOrder()->getStoreId());
     $payment->setAmount($amount);
     $payment->setLastTransId($order_id);
     $payment->setStatus(self::STATUS_APPROVED);
     return $this;
 }
 public function capture(Varien_Object $payment, $amount)
 {
     $session = Mage::getSingleton('core/session');
     $logger = Mage::helper('worldpay/logger');
     if ($session->getData('wp_3dscompletionNeeded')) {
         $payment->setIsTransactionClosed(0);
         $payment->setSkipOrderProcessing(true);
         $payment->setStatus(self::STATUS_APPROVED);
         $payment->setAmount($amount);
         $payment->setShouldCloseParentTransaction(1);
         $payment->setAdditionalInformation("worldpayOrderCode", $session->getData('wp_orderCode'));
         $payment->setLastTransId($session->getData('wp_orderCode'));
         $payment->setTransactionId($session->getData('wp_orderCode'));
         $session->setData('wp_3dscompletionNeeded', false);
         return $this;
     }
     $worldpayOrderCode = $payment->getData('last_trans_id');
     if ($worldpayOrderCode) {
         $worldpay = $this->setupWorldpay();
         try {
             $authorizationTransaction = $payment->getAuthorizationTransaction();
             if ($authorizationTransaction) {
                 $payment->setAdditionalInformation("worldpayOrderCode", $authorizationTransaction->getTxnId());
                 $worldpayOrderCode = $authorizationTransaction->getTxnId();
             } else {
                 $worldpayOrderCode = $payment->getAdditionalInformation('worldpayOrderCode');
             }
             $worldpay->captureAuthorisedOrder($worldpayOrderCode, $amount * 100);
             $payment->setShouldCloseParentTransaction(1)->setIsTransactionClosed(1);
             $logger->log('Capture Order: ' . $session->getData('wp_orderCode') . ' success');
         } catch (Exception $e) {
             $logger->log('Capture Order: ' . $session->getData('wp_orderCode') . ' failed with ' . $e->getMessage());
             Mage::throwException('Payment failed, please try again later ' . $e->getMessage());
         }
     } else {
         $payment->setAdditionalInformation('payment_type', 'capture');
         return $this->createOrder($payment, $amount, false);
     }
 }
Example #9
0
 /**
  * Send capture request to gateway
  *
  * @param Varien_Object $payment
  * @param decimal $amount
  * @return Mage_Paygate_Model_Authorizenet
  * @throws Mage_Core_Exception
  */
 public function capture(Varien_Object $payment, $amount)
 {
     if ($amount <= 0) {
         Mage::throwException(Mage::helper('linkpoint')->__('Invalid amount for transaction.'));
     }
     $payment->setAmount($amount);
     $data = $this->_prepareData();
     $data['ordertype'] = "SALE";
     $creditcard = array('cardnumber' => $payment->getCcNumber(), 'cardexpmonth' => $payment->getCcExpMonth(), 'cardexpyear' => substr($payment->getCcExpYear(), -2));
     if ($this->getConfigData('useccv') == 1) {
         $creditcard["cvmindicator"] = "provided";
         $creditcard["cvmvalue"] = $payment->getCcCid();
     }
     $shipping = array();
     $billing = array();
     $order = $payment->getOrder();
     if (!empty($order)) {
         $BillingAddress = $order->getBillingAddress();
         $billing['name'] = $BillingAddress->getFirstname() . " " . $BillingAddress->getLastname();
         $billing['company'] = $BillingAddress->getCompany();
         $billing['address'] = $BillingAddress->getStreet(1);
         $billing['city'] = $BillingAddress->getCity();
         $billing['state'] = $BillingAddress->getRegion();
         $billing['zip'] = $BillingAddress->getPostcode();
         $billing['country'] = $BillingAddress->getCountry();
         $billing['email'] = $order->getCustomerEmail();
         $billing['phone'] = $BillingAddress->getTelephone();
         $billing['fax'] = $BillingAddress->getFax();
         $ShippingAddress = $order->getShippingAddress();
         if (!empty($shipping)) {
             $shipping['sname'] = $ShippingAddress->getFirstname() . " " . $ShippingAddress->getLastname();
             $shipping['saddress1'] = $ShippingAddress->getStreet(1);
             $shipping['scity'] = $ShippingAddress->getCity();
             $shipping['sstate'] = $ShippingAddress->getRegion();
             $shipping['szip'] = $ShippingAddress->getPostcode();
             $shipping['scountry'] = $ShippingAddress->getCountry();
         }
     }
     $transactiondetails = array();
     $merchantinfo = array();
     $merchantinfo['configfile'] = $data['storenumber'];
     $merchantinfo['keyfile'] = $data['key'];
     $paymentdetails = array();
     $paymentdetails['chargetotal'] = $payment->getAmount();
     $data = array_merge($data, $creditcard, $billing, $shipping, $transactiondetails, $merchantinfo, $paymentdetails);
     $result = $this->_postRequest($data);
     if (is_array($result) && count($result) > 0) {
         if (array_key_exists("r_approved", $result)) {
             if ($result["r_approved"] != "APPROVED") {
                 $payment->setStatus(self::STATUS_ERROR);
                 Mage::throwException("Gateway error : {" . (string) $result["r_error"] . "}");
             } else {
                 $payment->setStatus(self::STATUS_APPROVED);
                 $payment->setLastTransId((string) $result["r_ordernum"]);
                 if (!$payment->getParentTransactionId() || (string) $result["r_ordernum"] != $payment->getParentTransactionId()) {
                     $payment->setTransactionId((string) $result["r_ordernum"]);
                 }
                 return $this;
             }
         } else {
             Mage::throwException("No approval found");
         }
     } else {
         Mage::throwException("No response found");
     }
 }
Example #10
0
 /**
  * Refund the payment transaction
  *
  * @param Mage_Sale_Model_Order_Payment $payment
  * @param flaot $amount
  * @return Mage_Cybersource_Model_Soap
  */
 public function refund(Varien_Object $payment, $amount)
 {
     $error = false;
     if ($payment->getRefundTransactionId() && $payment->getRefundCybersourceToken() && $amount > 0) {
         $soapClient = $this->getSoapApi();
         $this->iniRequest();
         $ccCreditService = new stdClass();
         $ccCreditService->run = "true";
         $ccCreditService->captureRequestToken = $payment->getCybersourceToken();
         $ccCreditService->captureRequestID = $payment->getCcTransId();
         $this->_request->ccCreditService = $ccCreditService;
         $purchaseTotals = new stdClass();
         $purchaseTotals->grandTotalAmount = $amount;
         $this->_request->purchaseTotals = $purchaseTotals;
         try {
             $result = $soapClient->runTransaction($this->_request);
             if ($result->reasonCode == self::RESPONSE_CODE_SUCCESS) {
                 $payment->setLastTransId($result->requestID)->setLastCybersourceToken($result->requestToken);
             } else {
                 $error = Mage::helper('cybersource')->__('There is an error in processing payment. Please try again or contact us.');
             }
         } catch (Exception $e) {
             Mage::throwException(Mage::helper('cybersource')->__('Gateway request error: %s', $e->getMessage()));
         }
     } else {
         $error = Mage::helper('cybersource')->__('Error in refunding the payment');
     }
     if ($error !== false) {
         Mage::throwException($error);
     }
     return $this;
 }
Example #11
0
 /**
  * Authorize or Capture payment
  *
  * @param Varien_Object|Mage_Sales_Model_Order_Payment $payment
  * @param float $amount
  * @param bool $capture
  * @return  $this
  */
 private function _authorize(Varien_Object $payment, $amount, $capture)
 {
     $order = $payment->getOrder();
     /* @var $order Mage_Sales_Model_Order */
     $multiToken = false;
     $cardData = null;
     $additionalData = new Varien_Object($payment->getAdditionalData() ? unserialize($payment->getAdditionalData()) : null);
     $secureToken = $additionalData->getSecuresubmitToken() ? $additionalData->getSecuresubmitToken() : null;
     $saveCreditCard = !!(bool) $additionalData->getCcSaveFuture();
     $customerId = $additionalData->getCustomerId();
     if ($saveCreditCard) {
         $multiToken = true;
         $cardData = new HpsCreditCard();
         $cardData->number = $payment->getCcLast4();
         $cardData->expYear = $payment->getCcExpYear();
         $cardData->expMonth = $payment->getCcExpMonth();
     }
     $chargeService = $this->_getChargeService();
     $cardHolder = $this->_getCardHolderData($order);
     $details = $this->_getTxnDetailsData($order);
     $cardOrToken = new HpsTokenData();
     $cardOrToken->tokenValue = $secureToken;
     try {
         if ($capture) {
             if ($payment->getCcTransId()) {
                 $response = $chargeService->capture($payment->getCcTransId(), $amount);
             } else {
                 $response = $chargeService->charge($amount, strtolower($order->getBaseCurrencyCode()), $cardOrToken, $cardHolder, $multiToken, $details);
             }
         } else {
             $response = $chargeService->authorize($amount, strtolower($order->getBaseCurrencyCode()), $cardOrToken, $cardHolder, $multiToken, $details);
         }
         $this->_debugChargeService($chargeService);
         $payment->setStatus(self::STATUS_APPROVED);
         $payment->setAmount($amount);
         $payment->setLastTransId($response->transactionId);
         $payment->setCcTransId($response->transactionId);
         $payment->setTransactionId($response->transactionId);
         $payment->setIsTransactionClosed(0);
         if ($multiToken) {
             $tokenData = $response->tokenData;
             /* @var $tokenData HpsTokenData */
             if ($tokenData->responseCode == '0') {
                 if ($customerId > 0) {
                     Mage::helper('hps_securesubmit')->saveMultiToken($response->tokenData->tokenValue, $cardData, $response->cardType, $customerId);
                 } else {
                     Mage::helper('hps_securesubmit')->saveMultiToken($response->tokenData->tokenValue, $cardData, $response->cardType);
                 }
             } else {
                 Mage::log('Requested multi token has not been generated for the transaction # ' . $response->transactionId, Zend_Log::WARN);
             }
         }
     } catch (HpsCreditException $e) {
         Mage::logException($e);
         $this->_debugChargeService($chargeService, $e);
         $payment->setStatus(self::STATUS_DECLINED);
         $this->throwUserError($e->getMessage(), $e->resultText, TRUE);
     } catch (HpsException $e) {
         $this->_debugChargeService($chargeService, $e);
         $payment->setStatus(self::STATUS_ERROR);
         $this->throwUserError($e->getMessage(), NULL, TRUE);
     } catch (Exception $e) {
         $this->_debugChargeService($chargeService, $e);
         Mage::logException($e);
         $payment->setStatus(self::STATUS_ERROR);
         $this->throwUserError($e->getMessage());
     }
     return $this;
 }
 /**
  * Authorize or Capture payment
  *
  * @param Varien_Object|Mage_Sales_Model_Order_Payment $payment
  * @param float $amount
  * @param bool $capture
  * @return  $this
  */
 private function _authorize(Varien_Object $payment, $amount, $capture)
 {
     $order = $payment->getOrder();
     /* @var $order Mage_Sales_Model_Order */
     $multiToken = false;
     $cardData = null;
     $additionalData = new Varien_Object($payment->getAdditionalData() ? unserialize($payment->getAdditionalData()) : null);
     $secureToken = $additionalData->getSecuresubmitToken() ? $additionalData->getSecuresubmitToken() : null;
     $saveCreditCard = !!(bool) $additionalData->getCcSaveFuture();
     $customerId = $additionalData->getCustomerId();
     $giftService = $this->_getGiftService();
     $giftCardNumber = $additionalData->getGiftcardNumber();
     if ($giftCardNumber) {
         // 1. check balance
         $giftcard = new HpsGiftCard();
         $giftcard->number = $giftCardNumber;
         $giftResponse = $giftService->balance($giftcard);
         // 2. is balance > amount?
         if ($giftResponse->balanceAmount > $amount) {
             //  2.yes. process full to gift
             try {
                 if (strpos($this->getConfigData('secretapikey'), '_cert_') !== false) {
                     $giftresp = $giftService->sale($giftcard, 10.0);
                 } else {
                     $giftresp = $giftService->sale($giftcard, $amount);
                 }
                 $order->addStatusHistoryComment('Used Heartland Gift Card ' . $giftCardNumber . ' for amount $' . $amount . '. [full payment]');
                 $payment->setTransactionAdditionalInfo(Mage_Sales_Model_Order_Payment_Transaction::RAW_DETAILS, array('gift_card_number' => $giftCardNumber, 'gift_card_transaction' => $giftresp->transactionId, 'gift_card_amount_charged' => $amount));
                 $payment->setStatus(self::STATUS_APPROVED);
                 $payment->setAmount($amount);
                 $payment->setLastTransId($response->transactionId);
                 $payment->setTransactionId($response->transactionId);
                 $payment->setIsTransactionClosed(0);
                 return $this;
             } catch (Exception $e) {
                 Mage::logException($e);
                 $payment->setStatus(self::STATUS_ERROR);
                 $this->throwUserError($e->getMessage(), null, true);
             }
         } else {
             //  2.no. process full gift card amt and card process remainder
             $giftresp = $giftService->sale($giftcard, $giftResponse->balanceAmount);
             $order->addStatusHistoryComment('Used Heartland Gift Card ' . $giftCardNumber . ' for amount $' . $giftResponse->balanceAmount . '. [partial payment]')->save();
             $payment->setTransactionAdditionalInfo(Mage_Sales_Model_Order_Payment_Transaction::RAW_DETAILS, array('gift_card_number' => $giftCardNumber, 'gift_card_transaction' => $giftresp->transactionId, 'gift_card_amount_charged' => $giftResponse->balanceAmount));
             $payment->setAmount($giftResponse->balanceAmount)->save();
             $amount = $amount - $giftResponse->balanceAmount;
             // remainder
             // 3. TODO: if the card payment fails later, refund the gift transaction
         }
     }
     if ($saveCreditCard) {
         $multiToken = true;
         $cardData = new HpsCreditCard();
         $cardData->number = $payment->getCcLast4();
         $cardData->expYear = $payment->getCcExpYear();
         $cardData->expMonth = $payment->getCcExpMonth();
     }
     $chargeService = $this->_getChargeService();
     $cardHolder = $this->_getCardHolderData($order);
     $details = $this->_getTxnDetailsData($order);
     $cardOrToken = new HpsTokenData();
     $cardOrToken->tokenValue = $secureToken;
     try {
         if ($capture) {
             if ($payment->getCcTransId()) {
                 $response = $chargeService->capture($payment->getCcTransId(), $amount);
             } else {
                 $response = $chargeService->charge($amount, strtolower($order->getBaseCurrencyCode()), $cardOrToken, $cardHolder, $multiToken, $details);
             }
         } else {
             $response = $chargeService->authorize($amount, strtolower($order->getBaseCurrencyCode()), $cardOrToken, $cardHolder, $multiToken, $details);
         }
         $this->_debugChargeService($chargeService);
         $payment->setStatus(self::STATUS_APPROVED);
         $payment->setAmount($amount);
         $payment->setLastTransId($response->transactionId);
         $payment->setCcTransId($response->transactionId);
         $payment->setTransactionId($response->transactionId);
         $payment->setIsTransactionClosed(0);
         if ($giftCardNumber) {
             $order->addStatusHistoryComment('Remaining amount to be charged to credit card  ' . $this->_formatAmount($amount) . '. [partial payment]')->save();
         }
         if ($multiToken) {
             $tokenData = $response->tokenData;
             /* @var $tokenData HpsTokenData */
             if ($tokenData->responseCode == '0') {
                 if ($customerId > 0) {
                     Mage::helper('hps_securesubmit')->saveMultiToken($response->tokenData->tokenValue, $cardData, $response->cardType, $customerId);
                 } else {
                     Mage::helper('hps_securesubmit')->saveMultiToken($response->tokenData->tokenValue, $cardData, $response->cardType);
                 }
             } else {
                 Mage::log('Requested multi token has not been generated for the transaction # ' . $response->transactionId, Zend_Log::WARN);
             }
         }
     } catch (HpsCreditException $e) {
         Mage::logException($e);
         $this->getFraudSettings();
         $this->_debugChargeService($chargeService, $e);
         // refund gift (if used)
         if ($giftCardNumber) {
             $order->addStatusHistoryComment('Reversed Heartland Gift Card ' . $giftCardNumber . ' for amount $' . $giftResponse->balanceAmount . '. [full reversal]')->save();
             $giftResponse = $giftService->reverse($giftcard, $giftResponse->balanceAmount);
         }
         if ($this->_allow_fraud && $e->getCode() == HpsExceptionCodes::POSSIBLE_FRAUD_DETECTED) {
             // we can skip the card saving if it fails for possible fraud there will be no token.
             if ($this->_email_fraud && $this->_fraud_address != '') {
                 // EMAIL THE PEOPLE
                 $this->sendEmail($this->_fraud_address, $this->_fraud_address, 'Suspicious order (' . $order->getIncrementId() . ') allowed', 'Hello,<br><br>Heartland has determined that you should review order ' . $order->getRealOrderId() . ' for the amount of ' . $amount . '.');
             }
             $payment->setStatus(self::STATUS_APPROVED);
             $payment->setAmount($amount);
             $payment->setIsTransactionClosed(0);
         } else {
             $payment->setStatus(self::STATUS_ERROR);
             if ($e->getCode() == HpsExceptionCodes::POSSIBLE_FRAUD_DETECTED) {
                 $this->throwUserError($this->_fraud_text, null, true);
             } else {
                 $this->throwUserError($e->getMessage(), null, true);
             }
         }
     } catch (HpsException $e) {
         $this->_debugChargeService($chargeService, $e);
         $payment->setStatus(self::STATUS_ERROR);
         $this->throwUserError($e->getMessage(), null, true);
     } catch (Exception $e) {
         $this->_debugChargeService($chargeService, $e);
         Mage::logException($e);
         $payment->setStatus(self::STATUS_ERROR);
         $this->throwUserError($e->getMessage());
     }
     return $this;
 }
Example #13
0
 public function placeOrder(Varien_Object $payment)
 {
     $api = $this->getApi();
     $api->setAmount($payment->getOrder()->getBaseGrandTotal())->setTrxtype($this->getPaymentAction())->setCurrencyCode($payment->getOrder()->getBaseCurrencyCode());
     if ($api->callDoExpressCheckoutPayment() !== false) {
         $payment->setStatus('APPROVED')->setPayerId($api->getPayerId());
         if ($this->getPaymentAction() == Mage_PaypalUk_Model_Api_Pro::TRXTYPE_AUTH_ONLY) {
             $payment->setCcTransId($api->getTransactionId());
         } else {
             $payment->setLastTransId($api->getTransactionId());
         }
     } else {
         $e = $api->getError();
         die($e['message']);
     }
     return $this;
 }
 public function authorize(Varien_Object $payment, $amount)
 {
     $orderId = $payment->getOrder()->getIncrementId();
     try {
         $paymentValues = array("cardType" => $payment->getCcCid(), "expiresMonth" => $payment->getCcExpMonth(), "expiresYear" => $payment->getCcExpYear(), "cardHolderName" => $payment->getCcOwner(), "cardNumber" => $payment->getCcNumber(), "amount" => $amount, "orderId" => $orderId, "bankId" => $payment->getOrder()->getPosBankId(), "installment" => $payment->getOrder()->getPosInstallment());
         //FIXME: Find a way to define this part in the $payment object which is Magento_Sales_Info or something like that.
         if ($bankid == 12) {
             //Different banks...
             $paymentValues['username'] = "******";
             $paymentValues['password'] = "******";
             $paymentValues['clientid'] = "my_clientid_given_to_me_by_the_bank";
         } else {
             if ($bankid == 14) {
                 //... can require different values to be sent to them
                 $paymentValues['username'] = "******";
                 $paymentValues['password'] = "******";
                 $paymentValues['clientid'] = "my_clientid_given_to_me_by_the_bank";
                 $paymentValues['additionalSecondBankField'] = "additional_info";
             } else {
                 Mage::throwException("Invalid bankid: {$bankid}");
             }
         }
         //Define the url where I'm making the request...
         $urlToPost = "https://my.bank.com/pos/service/address/";
         //Now Create the request which I will send via Post Method...
         //Create a string like: cardType=VI&expiresMonth=12&expiresYear=2011&amount=100.50
         $postData = "";
         foreach ($paymentValues as $key => $val) {
             $posData .= "{$key}=" . urlencode($val) . "&";
         }
         //Let's create a curl request and send the values above to the bank...
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_URL, $urlToPost);
         curl_setopt($ch, CURLOPT_TIMEOUT, 180);
         curl_setopt($ch, CURLOPT_HEADER, false);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
         curl_setopt($ch, CURLOPT_POST, true);
         curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
         //Put the created string here in use...
         curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
         $data = curl_exec($ch);
         //This value is the string returned from the bank...
         if (!$data) {
             throw new Exception(curl_error($ch));
         }
         $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
         if ($httpcode && substr($httpcode, 0, 2) != "20") {
             //Unsuccessful post request...
             Mage::throwException("Returned HTTP CODE: " . $httpcode . " for this URL: " . $urlToPost);
         }
         curl_close($ch);
     } catch (Exception $e) {
         $payment->setStatus(self::STATUS_ERROR);
         $payment->setAmount($amount);
         $payment->setLastTransId($orderId);
         $this->setStore($payment->getOrder()->getStoreId());
         Mage::throwException($e->getMessage());
     }
     /*
      * Data outputted from the curl request
      *  is generally an xml string.
      * Assume that it is something like:
      *
      * <response>
      *   <isPaymentAccepted>1</isPaymentAccepted>
      *   <bankOrderId>1234233241</bankOrderId>
      * </response>
      *
      * However no bank response is never this simple by the way...
      * But this one gives you a general view of the thing.
      */
     $xmlResponse = new SimpleXmlElement($data);
     //Simple way to parse xml, Magento might have an equivalent class
     $isPaymentAccepted = $xmlResponse->isPaymentAccepted == 1;
     if ($isPaymentAccepted) {
         $this->setStore($payment->getOrder()->getStoreId());
         $payment->setStatus(self::STATUS_APPROVED);
         $payment->setAmount($amount);
         $payment->setLastTransId($orderId);
     } else {
         $this->setStore($payment->getOrder()->getStoreId());
         $payment->setStatus(self::STATUS_ERROR);
         //Throw an exception to fail the current transaction...
         Mage::throwException("Payment is not approved");
     }
     return $this;
 }
Example #15
0
 public function refund(Varien_Object $payment, $amount)
 {
     if ($payment->getRefundTransactionId() && $amount > 0) {
         $transId = $payment->getCcTransId();
         //if transaction type was purchase (authorize & capture)
         if (is_null($transId)) {
             $transId = $payment->getLastTransId();
         }
         $txnDetails = array('txn_type' => self::TRANSACTION_TYPE_REFUND, 'refund_transaction_id' => $transId, 'paynz_account_id' => $payment->getFlo2cashAccountId(), 'amount' => sprintf('%.2f', $amount));
     } else {
         AO::throwException(AO::helper('flo2cash')->__('Error in refunding the payment.'));
     }
     $response = $this->_sendRequest($txnDetails);
     if ($response['txn_status'] == self::TRANSACTION_STATUS_DECLINED) {
         AO::throwException(AO::helper('flo2cash')->__('Payment transaction has been declined.'));
     }
     $payment->setLastTransId($response['transaction_id']);
     return $this;
 }
Example #16
0
 public function createOrder(Varien_Object $payment, $amount, $authorize)
 {
     $store_id = Mage::app()->getStore()->getStoreId();
     $logger = Mage::helper('worldpay/logger');
     if ($payment->getOrder()) {
         $orderId = $payment->getOrder()->getIncrementId();
         $order = $payment->getOrder();
     } else {
         $quote = $payment->getQuote();
         $orderId = $quote->getReservedOrderId();
         $quote->save();
     }
     $session = Mage::getSingleton('core/session');
     $token = $session->getData('payment_token');
     $savedCard = $session->getData('saved_card');
     $logger->log('Begin create order');
     $session->setData('wp_3dsSuccess', false);
     $session->setData('wp_orderCode', false);
     $worldpay = $this->setupWorldpay();
     $checkout = Mage::getSingleton('checkout/session')->getQuote();
     $billing = $checkout->getBillingAddress();
     $order_description = Mage::getStoreConfig('payment/worldpay/description', $store_id);
     if (!$order_description) {
         $order_description = "Order";
     }
     $currency_code = Mage::app()->getStore()->getCurrentCurrencyCode();
     $name = $billing->getName();
     $billing_address = array("address1" => $billing->getStreet(1), "address2" => $billing->getStreet(2), "address3" => $billing->getStreet(3), "postalCode" => $billing->getPostcode(), "city" => $billing->getCity(), "state" => "", "countryCode" => $billing->getCountry());
     try {
         $mode = Mage::getStoreConfig('payment/worldpay_mode', Mage::app()->getStore()->getStoreId());
         $settlementCurrency = Mage::getStoreConfig('payment/worldpay/settlementcurrency', Mage::app()->getStore()->getStoreId());
         $createOrderRequest = array('token' => $token, 'orderDescription' => $order_description, 'amount' => $amount * 100, 'currencyCode' => $currency_code, 'name' => $name, 'billingAddress' => $billing_address, 'customerOrderCode' => $orderId, 'settlementCurrency' => $settlementCurrency, 'successUrl' => Mage::getUrl('worldpay/apm/success', array('_secure' => true)), 'pendingUrl' => Mage::getUrl('worldpay/apm/pending', array('_secure' => true)), 'failureUrl' => Mage::getUrl('worldpay/apm/failure', array('_secure' => true)), 'cancelUrl' => Mage::getUrl('worldpay/apm/cancel', array('_secure' => true)));
         $logger->log('Order Request: ' . print_r($createOrderRequest, true));
         $response = $worldpay->createApmOrder($createOrderRequest);
         $logger->log('Order Response: ' . print_r($response, true));
         if ($response['paymentStatus'] === 'SUCCESS') {
             $this->setStore($payment->getOrder()->getStoreId());
             $logger->log('Order: ' . $response['orderCode'] . ' SUCCESS');
             $payment->setStatus(self::STATUS_APPROVED);
             $payment->setAmount($amount);
             $payment->setLastTransId($orderId);
             $payment->setTransactionId($response['orderCode']);
             $payment->setAdditionalInformation("worldpayOrderCode", $response['orderCode']);
             $payment->setShouldCloseParentTransaction(1)->setIsTransactionClosed(1)->registerCaptureNotification($amount);
         } else {
             if ($response['paymentStatus'] == 'PRE_AUTHORIZED') {
                 $logger->log('Order: ' . $response['orderCode'] . ' PRE_AUTHORIZED');
                 $payment->setAmount($amount);
                 $payment->setAdditionalInformation("worldpayOrderCode", $response['orderCode']);
                 $payment->setLastTransId($orderId);
                 $payment->setTransactionId($response['orderCode']);
                 $payment->setIsTransactionClosed(false);
                 $session->setData('wp_redirectURL', $response['redirectURL']);
                 $session->setData('wp_orderCode', $response['orderCode']);
             } else {
                 if (isset($response['paymentStatusReason'])) {
                     throw new Exception($response['paymentStatusReason']);
                 } else {
                     throw new Exception(print_r($response, true));
                 }
             }
         }
     } catch (Exception $e) {
         $payment->setStatus(self::STATUS_ERROR);
         $payment->setAmount($amount);
         $payment->setLastTransId($orderId);
         $logger->log($e->getMessage());
         Mage::throwException('Payment failed, please try again later ' . $e->getMessage());
     }
     return $this;
 }
Example #17
0
 /**
  * Success response processor
  *
  * @param string $request
  * @param mixed $result
  * @param Varien_Object $payment
  *
  */
 protected function _beforeProcessResponse($request, $result, Varien_Object $payment)
 {
     $action = explode('.', $request['PAYMENT.CODE']);
     if (!isset($action[1])) {
         Mage::throwException(Mage::helper('moneybookerspsp')->__('MoneybookersPSP: Wrong response data, method is missing'));
     }
     $method = strtoupper($action[0]);
     $action = strtoupper($action[1]);
     switch ((string) $result->Transaction->Processing->Result) {
         case 'ACK':
             switch ($action) {
                 case self::PAYMENT_TYPE_PREAUTHORIZE:
                     if ((string) $result->Transaction->Processing->Result == 'ACK') {
                         $payment->setLastTransId((string) $result->Transaction->Identification->UniqueID);
                         $payment->setCcTransId((string) $result->Transaction->Identification->UniqueID)->setAmountAuthorized($payment->getOrder()->getTotalDue())->setBaseAmountAuthorized($payment->getOrder()->getBaseTotalDue())->setBaseAmountPaid(0)->setAmountPaid(0);
                         $payment->save();
                         $payment->getOrder()->setCustomerNote(Mage::helper('moneybookerspsp')->__('Payment has been preauthorized.'));
                         return true;
                     } else {
                         Mage::throwException($result->Transaction->Processing->Return . ' (' . $result->Transaction->Processing->Return['code'] . ')');
                     }
                     break;
                 case self::PAYMENT_TYPE_DEBIT:
                     if ((string) $result->Transaction->Processing->Result == 'ACK') {
                         $payment->setLastTransId((string) $result->Transaction->Identification->UniqueID);
                         $payment->setCcTransId((string) $result->Transaction->Identification->UniqueID);
                         $payment->save();
                         $payment->getOrder()->setCustomerNote(Mage::helper('moneybookerspsp')->__('Payment has been authorized and captured.'));
                         return true;
                     } else {
                         Mage::throwException($result->Transaction->Processing->Return . ' (' . $result->Transaction->Processing->Return['code'] . ')');
                     }
                     break;
                 case self::PAYMENT_TYPE_CAPTURE:
                     $payment->getOrder()->setCustomerNote(Mage::helper('moneybookerspsp')->__('Payment has been captured.'));
                     break;
                 case self::PAYMENT_TYPE_REFUND:
                     $payment->getOrder()->setCustomerNote(Mage::helper('moneybookerspsp')->__('Payment has been refunded.'));
                     break;
                 case self::PAYMENT_TYPE_REBILL:
                     $payment->getOrder()->setCustomerNote(Mage::helper('moneybookerspsp')->__('Payment has been reversed.'));
                     break;
             }
             break;
         case 'NOK':
             switch ($action) {
                 case self::PAYMENT_TYPE_PREAUTHORIZE:
                     break;
                 case self::PAYMENT_TYPE_DEBIT:
                     break;
             }
             break;
     }
 }
Example #18
0
 /**
  * Making right API call for current trasaction
  *
  * @param Varien_Object $payment
  * @return Mage_Paypal_Model_Express
  */
 public function placeOrder(Varien_Object $payment)
 {
     $api = $this->getApi();
     $api->setAmount($payment->getOrder()->getBaseGrandTotal())->setCurrencyCode($payment->getOrder()->getBaseCurrencyCode())->setInvNum($this->getQuote()->getReservedOrderId());
     if ($api->callDoExpressCheckoutPayment() !== false) {
         $payment->setStatus('APPROVED')->setPayerId($api->getPayerId());
         if ($this->getPaymentAction() == Mage_Paypal_Model_Api_Nvp::PAYMENT_TYPE_AUTH) {
             $payment->setCcTransId($api->getTransactionId());
         } else {
             $payment->setLastTransId($api->getTransactionId());
         }
     } else {
         $e = $api->getError();
         die($e['short_message'] . ': ' . $e['long_message']);
     }
     return $this;
 }
Example #19
0
 public function createOrder(Varien_Object $payment, $amount, $authorize)
 {
     $store_id = Mage::app()->getStore()->getStoreId();
     if ($payment->getOrder()) {
         $orderId = $payment->getOrder()->getIncrementId();
     } else {
         $orderId = $payment->getQuote()->getIncrementId();
         // $order = $payment->getOrder())
     }
     $logger = Mage::helper('worldpay/logger');
     $session = Mage::getSingleton('core/session');
     $token = $session->getData('payment_token');
     $savedCard = $session->getData('saved_card');
     $logger->log('Begin create order');
     $session->setData('wp_3dsSuccess', false);
     $session->setData('wp_orderCode', false);
     $worldpay = $this->setupWorldpay();
     if (Mage::app()->getStore()->isAdmin()) {
         $checkout = Mage::getSingleton('adminhtml/session_quote')->getQuote();
     } else {
         $checkout = Mage::getSingleton('checkout/session')->getQuote();
     }
     $billing = $checkout->getBillingAddress();
     $order_description = Mage::getStoreConfig('payment/' . $this->_code . '/description', $store_id);
     if (!$order_description) {
         $order_description = "Order";
     }
     $currency_code = Mage::app()->getStore()->getCurrentCurrencyCode();
     $name = $billing->getName();
     $billing_address = array("address1" => $billing->getStreet(1), "address2" => $billing->getStreet(2), "address3" => $billing->getStreet(3), "postalCode" => $billing->getPostcode(), "city" => $billing->getCity(), "state" => "", "countryCode" => $billing->getCountry());
     try {
         $mode = Mage::getStoreConfig('payment/worldpay_mode', Mage::app()->getStore()->getStoreId());
         $orderType = 'ECOM';
         $threeDS = Mage::getStoreConfig('payment/worldpay_cc/use3ds', Mage::app()->getStore()->getStoreId());
         if (Mage::app()->getStore()->isAdmin()) {
             $orderType = 'MOTO';
             $threeDS = false;
         }
         if ($threeDS && $mode == 'Test Mode') {
             $name = '3D';
         }
         $settlementCurrency = Mage::getStoreConfig('payment/worldpay_cc/settlementcurrency', Mage::app()->getStore()->getStoreId());
         $createOrderRequest = array('token' => $token, 'orderDescription' => $order_description, 'amount' => $amount * 100, 'currencyCode' => $currency_code, 'name' => $name, 'orderType' => $orderType, 'is3DSOrder' => $threeDS, 'authoriseOnly' => $authorize, 'billingAddress' => $billing_address, 'customerOrderCode' => $orderId, 'settlementCurrency' => $settlementCurrency);
         $logger->log('Order Request: ' . print_r($createOrderRequest, true));
         $response = $worldpay->createOrder($createOrderRequest);
         $logger->log('Order Response: ' . print_r($response, true));
         if ($response['paymentStatus'] === 'SUCCESS') {
             $this->setStore($payment->getOrder()->getStoreId());
             $logger->log('Order: ' . $response['orderCode'] . ' SUCCESS');
             $payment->setStatus(self::STATUS_APPROVED);
             $payment->setAmount($amount);
             $payment->setLastTransId($orderId);
             $payment->setTransactionId($response['orderCode']);
             $payment->setAdditionalInformation("worldpayOrderCode", $response['orderCode']);
             // $formatedPrice = $order->getBaseCurrency()->formatTxt($amount);
             $payment->setShouldCloseParentTransaction(1)->setIsTransactionClosed(1)->registerCaptureNotification($amount);
         } else {
             if ($response['paymentStatus'] == 'AUTHORIZED') {
                 $this->setStore($payment->getOrder()->getStoreId());
                 $logger->log('Order: ' . $response['orderCode'] . ' AUTHORIZED');
                 $payment->setIsTransactionClosed(0);
                 $payment->setSkipOrderProcessing(true);
                 $payment->setStatus(self::STATUS_APPROVED);
                 $payment->setAmount($amount);
                 $payment->setAdditionalInformation("worldpayOrderCode", $response['orderCode']);
                 $payment->setLastTransId($orderId);
                 $payment->setTransactionId($response['orderCode']);
             } else {
                 if ($response['is3DSOrder']) {
                     $session = Mage::getSingleton('core/session');
                     $logger->log('Starting 3DS Order: ' . $response['orderCode']);
                     $session->setData('wp_3dsSuccess', false);
                     $session->setData('wp_redirectURL', $response['redirectURL']);
                     $session->setData('wp_oneTime3DsToken', $response['oneTime3DsToken']);
                     $session->setData('wp_orderCode', $response['orderCode']);
                     // IF normal checkout
                     $currentUrl = Mage::helper('core/url')->getCurrentUrl();
                     $url = Mage::getSingleton('core/url')->parseUrl($currentUrl);
                     $path = $url->getPath();
                     if (strpos($path, 'onepage') === false) {
                         Mage::app()->getFrontController()->getResponse()->setRedirect(Mage::getUrl('worldpay/threeDS'));
                         Mage::app()->getResponse()->sendResponse();
                     } else {
                         echo 'window.WorldpayMagento.loadThreeDS("' . Mage::getUrl('worldpay/threeDS') . '")';
                     }
                     exit;
                 } else {
                     if (isset($response['paymentStatusReason'])) {
                         throw new Exception($response['paymentStatusReason']);
                     } else {
                         throw new Exception(print_r($response, true));
                     }
                 }
             }
         }
     } catch (Exception $e) {
         $payment->setStatus(self::STATUS_ERROR);
         $payment->setAmount($amount);
         $payment->setLastTransId($orderId);
         $logger->log($e->getMessage());
         Mage::throwException('Payment failed, please try again later ' . $e->getMessage());
     }
     return $this;
 }
 /**
  * Refund the card transaction through gateway
  *
  * @param Mage_Payment_Model_Info $payment
  * @param Varien_Object $card
  * @return Mage_Sales_Model_Order_Payment_Transaction
  */
 protected function _refundCardTransaction($payment, $amount, $card)
 {
     /**
      * Card has last transaction with type "refund" when all captured amount is refunded.
      * Until this moment card has last transaction with type "capture".
      */
     $captureTransactionId = $card->getLastTransId();
     $captureTransaction = $payment->getTransaction($captureTransactionId);
     $realCaptureTransactionId = $captureTransaction->getAdditionalInformation($this->_realTransactionIdKey);
     $payment->setAnetTransType(self::REQUEST_TYPE_CREDIT);
     $payment->setXTransId($realCaptureTransactionId);
     $payment->setAmount($amount);
     $request = $this->_buildRequest($payment);
     $request->setXCardNum($card->getCcLast4());
     $result = $this->_postRequest($request);
     switch ($result->getResponseCode()) {
         case self::RESPONSE_CODE_APPROVED:
             if ($result->getResponseReasonCode() == self::RESPONSE_REASON_CODE_APPROVED) {
                 $refundTransactionId = $result->getTransactionId() . '-refund';
                 $shouldCloseCaptureTransaction = 0;
                 /**
                  * If it is last amount for refund, transaction with type "capture" will be closed
                  * and card will has last transaction with type "refund"
                  */
                 if ($this->_formatAmount($card->getCapturedAmount() - $card->getRefundedAmount()) == $amount) {
                     $card->setLastTransId($refundTransactionId);
                     $shouldCloseCaptureTransaction = 1;
                 }
                 return $this->_addTransaction($payment, $refundTransactionId, Mage_Sales_Model_Order_Payment_Transaction::TYPE_REFUND, array('is_transaction_closed' => 1, 'should_close_parent_transaction' => $shouldCloseCaptureTransaction, 'parent_transaction_id' => $captureTransactionId), array($this->_realTransactionIdKey => $result->getTransactionId()), Mage::helper('paygate')->getTransactionMessage($payment, self::REQUEST_TYPE_CREDIT, $result->getTransactionId(), $card, $amount));
             }
             $exceptionMessage = $this->_wrapGatewayError($result->getResponseReasonText());
             break;
         case self::RESPONSE_CODE_DECLINED:
         case self::RESPONSE_CODE_ERROR:
             $exceptionMessage = $this->_wrapGatewayError($result->getResponseReasonText());
             break;
         default:
             $exceptionMessage = Mage::helper('paygate')->__('Payment refunding error.');
             break;
     }
     $exceptionMessage = Mage::helper('paygate')->getTransactionMessage($payment, self::REQUEST_TYPE_CREDIT, $realCaptureTransactionId, $card, $amount, $exceptionMessage);
     Mage::throwException($exceptionMessage);
 }
 /**
  * This method handles the authorization mechanism used by the EcorePay payment gateway.
  *
  */
 public function authorize(Varien_Object $payment, $amount)
 {
     $order = $payment->getOrder();
     try {
         $billingaddress = $order->getBillingAddress();
         ob_start();
         $regionModel = Mage::getModel('directory/region')->load($billingaddress->getData('region_id'));
         $dob = Mage::getModel('customer/customer')->load($order->getCustomerId())->getDob();
         $devMode = false;
         $ipAddress = $_SERVER['REMOTE_ADDR'];
         $dobStr = "";
         if (!isset($dob)) {
             $dob = $order->getCustomerDob();
         }
         if (isset($dob)) {
             $dobStr = str_replace("00:00:00", "", $dob);
             $dobStr = str_replace("-", "", $dobStr);
             $dobStr = trim($dobStr);
         }
         $totals = number_format($amount, 2, '.', '');
         $fields = array('Reference' => $order->getId(), 'Amount' => $totals, 'Currency' => $order->getBaseCurrencyCode(), 'Email' => $billingaddress->getData('email'), 'IPAddress' => $_SERVER['REMOTE_ADDR'], 'Phone' => $billingaddress->getData('telephone'), 'FirstName' => $billingaddress->getData('firstname'), 'LastName' => $billingaddress->getData('lastname'), 'DOB' => $dobStr, 'Address' => $billingaddress->getData('street'), 'City' => $billingaddress->getData('city'), 'State' => $regionModel->getCode(), 'PostCode' => $billingaddress->getData('postcode'), 'Country' => $billingaddress->getData('country_id'), 'CardNumber' => $payment->getCcNumber(), 'CardExpMonth' => $payment->getCcExpMonth(), 'CardExpYear' => $payment->getCcExpYear(), 'CardCVV' => $payment->getCcCid());
         $accountId = 'Enter Your Account Id or API User Key';
         $accountAuth = 'Enter Your Account Auth or API Password Key';
         $fields_string = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Request type=\"AuthorizeCapture\"><AccountID>" . $accountId . "</AccountID><AccountAuth>" . $accountAuth . "</AccountAuth><Transaction>";
         foreach ($fields as $key => $value) {
             $fields_string .= '<' . $key . '>' . $value . '</' . $key . '>';
         }
         $fields_string .= '</Transaction></Request>';
         //open connection
         $ch = curl_init('https://gateway.ecorepay.cc/');
         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
         curl_setopt($ch, CURLOPT_POST, 1);
         curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
         curl_setopt($ch, CURLOPT_HEADER, 0);
         // DO NOT RETURN HTTP HEADERS
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
         // RETURN THE CONTENTS OF THE CALL
         curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120);
         // Timeout on connect (2 minutes)
         //execute post
         $data = curl_exec($ch);
         //This value is the string returned from the bank...
         if (!$data) {
             throw new Exception(curl_error($ch));
         }
         $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
         if ($httpcode && substr($httpcode, 0, 2) != "20") {
             // @TODO This should be moved to it's own method.
             throw new Exception("Returned HTTP CODE: " . $httpcode . " for this URL: " . $urlToPost);
         }
         curl_close($ch);
     } catch (Exception $e) {
         $payment->setStatus(self::STATUS_ERROR);
         $payment->setAmount($amount);
         $payment->setLastTransId($orderId);
         $this->setStore($payment->getOrder()->getStoreId());
         Mage::throwException($e->getMessage());
     }
     $xmlResponse = new SimpleXmlElement($data);
     // @TODO Keep looking for some Magento parse
     $contents = ob_get_contents();
     ob_end_clean();
     $isPaymentAccepted = $xmlResponse->ResponseCode[0] == 100;
     // @TODO Should come from constant
     $this->setStore($payment->getOrder()->getStoreId());
     $payment->setAmount($amount);
     $payment->setLastTransId($orderId);
     if ($isPaymentAccepted) {
         $payment->setStatus(self::STATUS_APPROVED);
     } else {
         $payment->setStatus(self::STATUS_ERROR);
         Mage::throwException("Please check your credit card information.");
     }
     return $this;
 }