public function getInstallmentsAvailables() { $maxInstallments = (int) Mage::getStoreConfig('payment/pagarme_cc/max_installments'); $minInstallmentValue = (double) Mage::getStoreConfig('payment/pagarme_cc/min_installment_value'); $interestRate = (double) Mage::getStoreConfig('payment/pagarme_cc/interest_rate'); $freeInstallments = (int) Mage::getStoreConfig('payment/pagarme_cc/free_installments'); if ($minInstallmentValue < self::MIN_INSTALLMENT_VALUE) { $minInstallmentValue = self::MIN_INSTALLMENT_VALUE; } $quote = Mage::helper('checkout')->getQuote(); $total = $quote->getGrandTotal(); $n = floor($total / $minInstallmentValue); if ($n > $maxInstallments) { $n = $maxInstallments; } elseif ($n < 1) { $n = 1; } $data = new Varien_Object(); $data->setAmount(Mage::helper('pagarme')->formatAmount($total))->setInterestRate($interestRate)->setMaxInstallments($n)->setFreeInstallments($freeInstallments); $response = Mage::getModel('pagarme/api')->calculateInstallmentsAmount($data); $collection = $response->getInstallments(); $installments = array(); foreach ($collection as $item) { if ($item->getInstallment() == 1) { $label = $this->__('Pay in full - %s', $quote->getStore()->formatPrice($item->getInstallmentAmount() / 100, false)); } else { $label = $this->__('%sx - %s', $item->getInstallment(), $quote->getStore()->formatPrice($item->getInstallmentAmount() / 100, false)) . ' '; $label .= $item->getInstallment() > $freeInstallments ? $this->__('monthly interest rate (%s)', $interestRate . '%') : $this->__('interest-free'); } $installments[$item->getInstallment()] = $label; } return $installments; }
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; }
public function authorize(Varien_Object $payment, $amount) { $error = false; if ($amount > 0) { $payment->setTrxtype(self::TRXTYPE_AUTH_ONLY); $payment->setAmount($amount); $request = $this->_buildRequest($payment); $result = $this->_postRequest($request); $payment->setCcTransId($result->getPnref()); switch ($result->getResultCode()) { case self::RESPONSE_CODE_APPROVED: $payment->setStatus(self::STATUS_APPROVED); break; case self::RESPONSE_CODE_FRAUDSERVICE_FILTER: $payment->setFraudFlag(true); break; default: if ($result->getRespmsg()) { $error = $result->getRespmsg(); } else { $error = Mage::helper('paygate')->__('Error in authorizing the payment'); } break; } } else { $error = Mage::helper('paygate')->__('Invalid amount for authorization'); } if ($error !== false) { Mage::throwException($error); } return $this; }
protected function _prepareGiftVoucher(Varien_Object $buyRequest, $product) { $store = Mage::app()->getStore(); if ($store->isAdmin()) { $amount = $product->getPrice(); } else { if ($buyRequest->getAmount()) { $amount = $buyRequest->getAmount(); $includeTax = Mage::getStoreConfig('tax/display/type') != 1; $amount = $amount * 100 / Mage::helper('tax')->getPrice($product, 100, $includeTax); } else { $amount = $product->getPrice(); } if (!$amount) { return Mage::helper('giftvoucher')->__('Please enter gift voucher information'); } } if (!$buyRequest->getAmount()) { $buyRequest->setAmount($amount); } $product->addCustomOption('amount', $amount); $fields = array(); foreach (Mage::helper('giftvoucher')->getFullGiftVoucherOptions() as $key => $label) { if ($value = $buyRequest->getData($key)) { $product->addCustomOption($key, $value); } } return array($product); }
public function collect(Mage_Sales_Model_Quote_Address $address) { parent::collect($address); // $this->_setAmount (0); // $this->_setBaseAmount (0); $items = $this->_getAddressItems($address); if (!count($items)) { return $this; } $quote = Mage::helper('pagarme')->_getQuote(); $payment = $quote->getPayment()->getMethod(); if (!strcmp($payment, 'pagarme_cc') || !strcmp($payment, 'pagarme_checkout')) { $maxInstallments = (int) Mage::getStoreConfig('payment/pagarme_cc/max_installments'); $minInstallmentValue = (double) Mage::getStoreConfig('payment/pagarme_cc/min_installment_value'); $interestRate = (double) Mage::getStoreConfig('payment/pagarme_cc/interest_rate'); $freeInstallments = (int) Mage::getStoreConfig('payment/pagarme_cc/free_installments'); $total = Mage::helper('pagarme')->getBaseSubtotalWithDiscount() + Mage::helper('pagarme')->getBaseShippingAmount(); $n = floor($total / $minInstallmentValue); if ($n > $maxInstallments) { $n = $maxInstallments; } elseif ($n < 1) { $n = 1; } $data = new Varien_Object(); $data->setAmount(Mage::helper('pagarme')->formatAmount($total))->setInterestRate($interestRate)->setMaxInstallments($n)->setFreeInstallments($freeInstallments); $post = Mage::app()->getRequest()->getPost(); $payment_installment = 0; if (isset($post['payment']['installments'])) { $payment_installment = $post['payment']['installments']; } else { if (isset($post['payment']['pagarme_checkout_installments'])) { $payment_installment = $post['payment']['pagarme_checkout_installments']; } } $installments = Mage::getModel('pagarme/api')->calculateInstallmentsAmount($data); $collection = $installments->getInstallments(); foreach ($collection as $item) { if ($item->getInstallment() == $payment_installment) { $famount = intval($item->getInstallmentAmount()) / 100; $iqty = intval($item->getInstallment()); $balance = $famount * $iqty - $total; if ($balance < 0) { break; } // The 1 cent problem $address->setFeeAmount($balance); $address->setBaseFeeAmount($balance); $quote->setFeeAmount($balance); $address->setGrandTotal($address->getGrandTotal() + $address->getFeeAmount()); $address->setBaseGrandTotal($address->getBaseGrandTotal() + $address->getBaseFeeAmount()); break; } } } return $this; }
public function getInstallmentsAvailables() { $plans = Mage::getModel('pagarme/config')->_getPlans(); if (count($plans) > 0) { $allow_multiples = Mage::getStoreConfigFlag('payment/pagarme_subscriptions/allow_multiples'); if (count($plans) > 1 && !$allow_multiples) { $this->_redirectToCart(); return; } $_plan = reset($plans); // first plan $planId = key($plans); $_plan = Mage::getModel('pagarme/plans')->load($planId); $_planName = $_plan->getName(); $maxInstallments = $_plan->getInstallments(); } else { $maxInstallments = (int) Mage::getStoreConfig('payment/pagarme_cc/max_installments'); } $minInstallmentValue = (double) Mage::getStoreConfig('payment/pagarme_cc/min_installment_value'); $interestRate = (double) Mage::getStoreConfig('payment/pagarme_cc/interest_rate'); $freeInstallments = (int) Mage::getStoreConfig('payment/pagarme_cc/free_installments'); if ($minInstallmentValue < self::MIN_INSTALLMENT_VALUE) { $minInstallmentValue = self::MIN_INSTALLMENT_VALUE; } $quote = Mage::helper('pagarme')->_getQuote(); $total = Mage::helper('pagarme')->getBaseSubtotalWithDiscount() + Mage::helper('pagarme')->getBaseShippingAmount(); $n = floor($total / $minInstallmentValue); if ($n > $maxInstallments) { $n = $maxInstallments; } elseif ($n < 1) { $n = 1; } $data = new Varien_Object(); $data->setAmount(Mage::helper('pagarme')->formatAmount($total))->setInterestRate($interestRate)->setMaxInstallments($n)->setFreeInstallments($freeInstallments); $response = Mage::getModel('pagarme/api')->calculateInstallmentsAmount($data); $collection = $response->getInstallments(); $installments = array(); foreach ($collection as $item) { if ($item->getInstallment() == 1 && count($plans) == 0) { $label = $this->__('Pay in full - %s', $quote->getStore()->formatPrice($item->getInstallmentAmount() / 100, false)); $installments[$item->getInstallment()] = $label; } elseif ($item->getInstallment() != $maxInstallments && count($plans) == 0 || $item->getInstallment() == $maxInstallments && count($plans) > 0) { $label = $this->__('%sx - %s', $item->getInstallment(), $quote->getStore()->formatPrice($item->getInstallmentAmount() / 100, false)) . ' '; $label .= $item->getInstallment() > $freeInstallments ? $this->__('monthly interest rate (%s)', $interestRate . '%') : $this->__('interest-free'); $label .= !empty($_planName) ? $this->__(' (Plan %s) ', $_planName) : null; $installments[$item->getInstallment()] = $label; } } return $installments; }
protected function _prepareForm() { $form = new Varien_Data_Form(); $fieldset = $form->addFieldset('base_fieldset', array('legend' => Mage::helper('giftcards')->__('Create Gift Cards'))); $fieldset->addField('file_path', 'text', array('name' => 'file_path', 'label' => Mage::helper('giftcards')->__('Path to export Cards Code'), 'title' => Mage::helper('giftcards')->__('Path to export Cards Code'), 'required' => true)); $fieldset->addField('count', 'text', array('name' => 'count', 'label' => Mage::helper('giftcards')->__('Count of Gift Cards'), 'title' => Mage::helper('giftcards')->__('Count of Gift Cards'), 'required' => true)); $fieldset->addField('amount', 'text', array('name' => 'amount', 'label' => Mage::helper('giftcards')->__('Gift Cards Amount'), 'title' => Mage::helper('giftcards')->__('Gift Cards Amount'), 'required' => true)); $createConfig = new Varien_Object(); $createConfig->setFilePath('/var/backups/cardslist' . date('d-m-Y-His') . '.csv'); $createConfig->setCount(1); $createConfig->setAmount(100); $form->setValues($createConfig->getData()); $form->setAction($this->getUrl('*/adminhtml_cardscreate/save')); $form->setMethod('post'); $form->setUseContainer(true); $form->setId('edit_form'); $this->setForm($form); return parent::_prepareForm(); }
protected function _prepareCustomerCredit(Varien_Object $buyRequest, $product) { $store = Mage::app()->getStore(); if ($store->isAdmin()) { $amount = $product->getPrice(); } else { if ($buyRequest->getAmount()) { $amount = $buyRequest->getAmount(); $includeTax = Mage::getStoreConfig('tax/display/type') != 1; $amount = $amount * 100 / Mage::helper('tax')->getPrice($product, 100, $includeTax); } else { $amount = $product->getPrice(); } if (!$amount) { return Mage::helper('customercredit')->__('Please enter customercredit information'); } } if (!$buyRequest->getAmount()) { $buyRequest->setAmount($amount); } $product->addCustomOption('amount', $amount); return array($product); }
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; }
/** * 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"); } }
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; }
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); } }
protected function _prepareCustomerCredit(Varien_Object $buyRequest, $product) { if (Mage::app()->getStore()->isAdmin()) { $store = Mage::getSingleton('adminhtml/session_quote')->getStore(); } else { $store = Mage::app()->getStore(); } $amount = $buyRequest->getAmount(); if ($amount) { $creditAmount = Mage::helper('customercredit/creditproduct')->getCreditValue($product); switch ($creditAmount['type']) { case 'range': if ($amount < $this->convertPrice($product, $creditAmount['from'])) { $amount = $this->convertPrice($product, $creditAmount['from']) * $creditAmount['storecredit_rate']; } elseif ($amount > $this->convertPrice($product, $creditAmount['to'])) { $amount = $this->convertPrice($product, $creditAmount['to']) * $creditAmount['storecredit_rate']; } else { if ($amount > 0) { $amount = $amount * $creditAmount['storecredit_rate']; } else { $amount = 0; } } $fnPrice = $amount; break; case 'dropdown': if (!empty($creditAmount['options'])) { $check = false; $giftDropdown = array(); for ($i = 0; $i < count($creditAmount['options']); $i++) { $giftDropdown[$i] = $this->convertPrice($product, $creditAmount['options'][$i]); if ($amount == $giftDropdown[$i]) { $check = true; } } if (!$check) { $amount = $creditAmount['options'][0]; } $fnPrices = array_combine($giftDropdown, $creditAmount['prices']); $fnPrice = $fnPrices[$amount]; } break; case 'static': if ($amount != $this->convertPrice($product, $creditAmount['value'])) { $amount = $creditAmount['value']; } $fnPrice = $creditAmount['credit_price']; break; default: return Mage::helper('customercredit')->__('Please enter Store Credit information.'); } } else { return Mage::helper('customercredit')->__('Please enter Store Credit information.'); } $buyRequest->setAmount($amount); $product->addCustomOption('credit_price_amount', $fnPrice); foreach (Mage::helper('customercredit')->getFullCreditProductOptions() as $key => $label) { if ($value = $buyRequest->getData($key)) { $product->addCustomOption($key, $value); } } return array($product); }
protected function _placeTransaction($payment, $amount, $requestType) { $payment->setAnetTransType($requestType); $payment->setAmount($amount); $this->_initCardsStorage($payment); switch ($requestType) { case parent::REQUEST_TYPE_AUTH_ONLY: $newTransactionType = Mage_Sales_Model_Order_Payment_Transaction::TYPE_AUTH; break; case parent::REQUEST_TYPE_AUTH_CAPTURE: $newTransactionType = Mage_Sales_Model_Order_Payment_Transaction::TYPE_CAPTURE; break; } $this->getCardsStorage($payment)->flushCards(); $result = new Varien_Object(); $result->setRequestedAmount($amount); $result->setTransactionId($payment->getTransactionId()); $result->setAmount($amount); $card = $this->_registerCard($result, $payment); parent::_addTransaction($payment, $card->getLastTransId(), $newTransactionType, array('is_transaction_closed' => 0), array($this->_realTransactionIdKey => $card->getLastTransId()), Mage::helper('paygate')->getTransactionMessage($payment, $requestType, $card->getLastTransId(), $card, $amount)); if ($requestType == parent::REQUEST_TYPE_AUTH_CAPTURE) { $card->setCapturedAmount($card->getProcessedAmount()); $this->getCardsStorage($payment)->updateCard($card); } return $this; }
/** * Calculate Order amount * With rounding issue detection * @param Mage_Sales_Model_Order $order * @param int $order_amount * @return Varien_Object */ public function getCalculatedOrderAmount($order, $order_amount = 0) { // Order amount calculated by shop if ($order_amount === 0) { $order_amount = $order->getGrandTotal(); } // Order amount calculated manually $amount = 0; // add Order Items $items = $order->getAllVisibleItems(); /** @var $item Mage_Sales_Model_Order_Item */ foreach ($items as $item) { if ($item->getParentItem()) { continue; } $amount += (int) (100 * $item->getRowTotalInclTax()); } // add Shipping if (!$order->getIsVirtual()) { $shippingIncTax = $order->getShippingInclTax(); $amount += (int) (100 * $shippingIncTax); } // add Discount $discountData = Mage::helper('payex/discount')->getOrderDiscountData($order); $discountInclTax = (int) (100 * $discountData->getDiscountInclTax()); $amount += -1 * $discountInclTax; // Add reward points $amount += -1 * (int) (100 * $order->getBaseRewardCurrencyAmount()); // add Fee $fee = $order->getPayexPaymentFee() + $order->getPayexPaymentFeeTax(); if ($fee > 0) { $amount += (int) (100 * $fee); } // Detect Rounding Issue $rounded_total = sprintf("%.2f", $order_amount); $rounded_control_amount = sprintf("%.2f", $amount / 100); $rounding = 0; if ($rounded_total !== $rounded_control_amount) { if ($rounded_total > $rounded_control_amount) { $rounding = $rounded_total - $rounded_control_amount; } else { $rounding = -1 * ($rounded_control_amount - $rounded_total); } $rounding = sprintf("%.2f", $rounding); } $result = new Varien_Object(); return $result->setAmount($rounded_control_amount)->setRounding($rounding); }
public function refund(Varien_Object $payment, $amount) { $payment->setAmount($amount); $payment->setOpcode(self::OPCODE_REFUND); $this->setTransactionId($payment->getParentTransactionId()); $request = $this->_buildRequest($payment); $result = $this->_postRequest($request); $payment->setStatus(self::STATUS_APPROVED)->setTransactionId($result->getTransaction())->setIsTransactionClosed(1); return $this; }
/** * 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 ($payment->getCcTransId()) { $payment->setAnetTransType(self::REQUEST_TYPE_PRIOR_AUTH_CAPTURE); } else { $payment->setAnetTransType(self::REQUEST_TYPE_AUTH_CAPTURE); } $payment->setAmount($amount); $request = $this->_buildRequest($payment); $result = $this->_postRequest($request); if ($result->getResponseCode() == self::RESPONSE_CODE_APPROVED) { $payment->setStatus(self::STATUS_APPROVED); //$payment->setCcTransId($result->getTransactionId()); $payment->setLastTransId($result->getTransactionId()); if (!$payment->getParentTransactionId() || $result->getTransactionId() != $payment->getParentTransactionId()) { $payment->setTransactionId($result->getTransactionId()); } return $this; } if ($result->getResponseReasonText()) { Mage::throwException($this->_wrapGatewayError($result->getResponseReasonText())); } Mage::throwException(Mage::helper('paygate')->__('Error in capturing the payment.')); }
/** * 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; }
/** * Convert xml object to a Varien object. * * @param SimpleXMLElement $xml Xml response from the API. * @return object Api response into a Varien object. */ private function _mapTranscationDetails(SimpleXMLElement $xml) { $object = new Varien_Object(); $object->setErrorcode($xml->errorcode); $object->setTimestamp($xml->timestamp); if ((string) $xml->errorcode === '0000') { $object->setVpstxid($xml->vpstxid); $object->setContactNumber($xml->contactnumber); $object->setVendortxcode($xml->vendortxcode); $object->setTransactiontype($xml->transactiontype); $object->setStatus($xml->status); $object->setDescription($xml->description); $object->setAmount($xml->amount); $object->setCurrency($xml->currency); $object->setStarted($xml->started); $object->setCompleted($xml->completed); $object->setSecuritykey($xml->securitykey); $object->setClientip($xml->clientip); $object->setIplocation($xml->iplocation); $object->setGiftaid($xml->giftaid); $object->setPaymentsystem($xml->paymentsystem); $object->setPaymentsystemdetails($xml->paymentsystemdetails); $object->setAuthprocessor($xml->authprocessor); $object->setMerchantnumber($xml->merchantnumber); $object->setAccounttype($xml->accounttype); $object->setBillingaddress($xml->billingaddress); $object->setBillingpostcode($xml->billingpostcode); $object->setDeliveryaddress($xml->deliveryaddress); $object->setDeliverypostcode($xml->deliverypostcode); $object->setSystemused($xml->systemused); $object->setCustomeremail($xml->customeremail); $object->setAborted($xml->aborted); $object->setRefunded($xml->refunded); $object->setRepeated($xml->repeated); $object->setBasket($xml->basket); $object->setApplyavscv2($xml->applyavscv2); $object->setApply3dsecure($xml->apply3dsecure); $object->setAttempt($xml->attempt); $object->setCardholder($xml->cardholder); $object->setCardaddress($xml->cardaddress); $object->setCardpostcode($xml->cardpostcode); $object->setStartdate($xml->startdate); $object->setExpirydate($xml->expirydate); $object->setLast4digits($xml->last4digits); $object->setThreedresult($xml->threedresult); $object->setEci($xml->eci); $object->setCavv($xml->cavv); $object->setT3mscore($xml->t3mscore); $object->setT3maction($xml->t3maction); $object->setT3mid($xml->t3mid); } else { $object->setError(htmlentities($xml->error)); } return $object; }
/** * Send authorize request to gateway * * @param Varien_Object $payment * @param decimal $amount * @return Mage_Paygate_Model_Authorizenet */ public function authorize(Varien_Object $payment, $amount) { $payment->setAmount($this->getQuote()->getGrandTotal()); $error = false; $security = $this->getSecurityKey(); $payment->setSuSecurity($security); if ($payment->getAmount()) { $amount = number_format($this->getQuote()->getGrandTotal(), 2, '.', ''); $billing = $this->getQuote()->getBillingAddress(); $locale = explode('_', Mage::app()->getLocale()->getLocaleCode()); if (is_array($locale) && !empty($locale) && in_array($locale[0], $this->_supportedLocales)) { $locale = strtoupper($locale[0]); } else { $locale = strtoupper($this->getDefaultLocale()); } $params = array('user_id' => $this->getConfigData('customer'), 'project_id' => $this->getConfigData('project'), 'amount' => $amount, 'reason_1' => Mage::helper('pnsofortueberweisung')->__('Order: ') . $this->getQuote()->getReservedOrderId(), 'reason_2' => '', 'sender_holder' => $payment->getSuHolder(), 'sender_account_number' => $payment->getSuAccountNumber(), 'sender_bank_code' => $payment->getSuBankCode(), 'sender_bank_bic' => $payment->getSuBic(), 'sender_iban' => $payment->getSuIban(), 'sender_country_id' => $billing->getCountry(), 'user_variable_0' => $this->getQuote()->getReservedOrderId(), 'user_variable_1' => $payment->getSuSecurity(), 'user_variable_2' => '', 'user_variable_3' => '', 'user_variable_4' => '', 'user_variable_5' => '', 'expires' => $this->getConfigData('expires'), 'language_id' => $locale); if ($this->getConfigData('check_input_yesno') == 1) { $params['hash'] = md5(implode('|', $params) . '|' . $this->getConfigData('project_pswd')); } $result = $this->_postRequest($params); if (strstr($result, 'Errors') === false) { $payment->setSuPaycode($result); $payment->setStatus(self::STATUS_APPROVED); } else { $error = Mage::helper('pnsofortueberweisung')->__('Please check your account data.'); } } else { $error = Mage::helper('pnsofortueberweisung')->__('Invalid amount for authorization.'); } if ($error !== false) { Mage::throwException($error); } return $this; }
/** * Return commno data for *all* transactions. * @return array Data */ public function _getGeneralTrnData(Varien_Object $payment) { $order = $payment->getOrder(); $quoteObj = $this->_getQuote(); $vendorTxCode = $this->_getTrnVendorTxCode(); if ($payment->getCcNumber()) { $vendorTxCode .= $this->_cleanString(substr($payment->getCcOwner(), 0, 10)); } $payment->setVendorTxCode($vendorTxCode); $request = new Varien_Object(); $request->setVPSProtocol('2.23')->setReferrerID($this->getConfigData('referrer_id'))->setVendor($this->getConfigData('vendor'))->setVendorTxCode($vendorTxCode); $request->setClientIPAddress($this->getClientIp()); if ($payment->getIntegra()) { $this->getSageSuiteSession()->setLastVendorTxCode($vendorTxCode); $request->setIntegration($payment->getIntegra()); $request->setData('notification_URL', $this->getNotificationUrl() . '&vtxc=' . $vendorTxCode); $request->setData('success_URL', $this->getSuccessUrl()); $request->setData('redirect_URL', $this->getRedirectUrl()); $request->setData('failure_URL', $this->getFailureUrl()); } if ($this->_getIsAdminOrder()) { $request->setAccountType('M'); } if ($payment->getAmountOrdered()) { $from = $order->getOrderCurrencyCode(); if ((string) $this->getConfigData('trncurrency') == 'store') { $request->setAmount($this->formatAmount($quoteObj->getGrandTotal(), $quoteObj->getQuoteCurrencyCode())); $request->setCurrency($quoteObj->getQuoteCurrencyCode()); } else { $request->setAmount($this->formatAmount($quoteObj->getBaseGrandTotal(), $quoteObj->getBaseCurrencyCode())); $request->setCurrency($quoteObj->getBaseCurrencyCode()); } } if (!empty($order)) { $billing = $order->getBillingAddress(); if (!empty($billing)) { $request->setBillingAddress($billing->getStreet(1) . ' ' . $billing->getCity() . ' ' . $billing->getRegion() . ' ' . $billing->getCountry())->setBillingSurname($this->ss($billing->getLastname(), 20))->setBillingFirstnames($this->ss($billing->getFirstname(), 20))->setBillingPostCode($this->ss($billing->getPostcode(), 10))->setBillingAddress1($this->ss($billing->getStreet(1), 100))->setBillingAddress2($this->ss($billing->getStreet(2), 100))->setBillingCity($this->ss($billing->getCity(), 40))->setBillingCountry($billing->getCountry())->setContactNumber(substr($this->_cphone($billing->getTelephone()), 0, 20)); if ($billing->getCountry() == 'US') { $request->setBillingState($billing->getRegionCode()); } $request->setCustomerEMail($billing->getEmail()); } if (!$request->getDescription()) { $request->setDescription('.'); } $shipping = $order->getShippingAddress(); if (!empty($shipping)) { $request->setDeliveryAddress($shipping->getStreet(1) . ' ' . $shipping->getCity() . ' ' . $shipping->getRegion() . ' ' . $shipping->getCountry())->setDeliverySurname($this->ss($shipping->getLastname(), 20))->setDeliveryFirstnames($this->ss($shipping->getFirstname(), 20))->setDeliveryPostCode($this->ss($shipping->getPostcode(), 10))->setDeliveryAddress1($this->ss($shipping->getStreet(1), 100))->setDeliveryAddress2($this->ss($shipping->getStreet(2), 100))->setDeliveryCity($this->ss($shipping->getCity(), 40))->setDeliveryCountry($shipping->getCountry())->setDeliveryPhone($this->ss(urlencode($this->_cphone($shipping->getTelephone())), 20)); if ($shipping->getCountry() == 'US') { $request->setDeliveryState($shipping->getRegionCode()); } } else { #If the cart only has virtual products, I need to put an shipping address to Sage Pay. #Then the billing address will be the shipping address to $request->setDeliveryAddress($billing->getStreet(1) . ' ' . $billing->getCity() . ' ' . $billing->getRegion() . ' ' . $billing->getCountry())->setDeliverySurname($this->ss($billing->getLastname(), 20))->setDeliveryFirstnames($this->ss($billing->getFirstname(), 20))->setDeliveryPostCode($this->ss($billing->getPostcode(), 10))->setDeliveryAddress1($this->ss($billing->getStreet(1), 100))->setDeliveryAddress2($this->ss($billing->getStreet(2), 100))->setDeliveryCity($this->ss($billing->getCity(), 40))->setDeliveryCountry($billing->getCountry())->setDeliveryPhone($this->ss(urlencode($this->_cphone($billing->getTelephone())), 20)); if ($billing->getCountry() == 'US') { $request->setDeliveryState($billing->getRegionCode()); } } } if ($payment->getCcNumber()) { $request->setCardNumber($payment->getCcNumber())->setExpiryDate(sprintf('%02d%02d', $payment->getCcExpMonth(), substr($payment->getCcExpYear(), strlen($payment->getCcExpYear()) - 2)))->setCardType($payment->getCcType())->setCV2($payment->getCcCid())->setCardHolder($payment->getCcOwner()); if ($payment->getCcIssue()) { $request->setIssueNumber($payment->getCcIssue()); } if ($payment->getCcStartMonth() && $payment->getCcStartYear()) { $request->setStartDate(sprintf('%02d%02d', $payment->getCcStartMonth(), substr($payment->getCcStartYear(), strlen($payment->getCcStartYear()) - 2))); } } $totals = $shipping->getTotals(); $shippingTotal = isset($totals['shipping']) ? $totals['shipping']->getValue() : 0; if ($this->getSendBasket()) { $request->setBasket($this->_getBasketContents($quoteObj)); } if (!$request->getDeliveryPostCode()) { $request->setDeliveryPostCode('000'); } if (!$request->getBillingPostCode()) { $request->setBillingPostCode('000'); } return $request; }
public function capture(Varien_Object $payment, $amount) { $error = false; if ($payment->getCcTransId()) { $payment->setAnetTransType(self::REQUEST_TYPE_PRIOR_AUTH_CAPTURE); } else { $payment->setAnetTransType(self::REQUEST_TYPE_AUTH_CAPTURE); } $payment->setAmount($amount); $request = $this->_buildRequest($payment); $result = $this->_postRequest($request); if ($result->getResponseCode() == self::RESPONSE_CODE_APPROVED) { $payment->setStatus(self::STATUS_APPROVED); //$payment->setCcTransId($result->getTransactionId()); $payment->setLastTransId($result->getTransactionId()); } else { if ($result->getResponseReasonText()) { $error = $result->getResponseReasonText(); } else { $error = AO::helper('paygate')->__('Error in capturing the payment'); } } if ($error !== false) { AO::throwException($error); } return $this; }
/** * Capture the authorized transaction for a specific order * * @var Variant_Object $payment * @var Float $amount */ public function capture(Varien_Object $payment, $amount) { $error = false; // check for payment if ($amount > 0) { $payment->setAmount($amount); // Map magento keys to moneris way $transaction = $this->_build($payment, self::TRANSACTION_COMPLETION); $response = $this->_send($transaction); if ($response->getResponseCode() > 0 && $response->getResponseCode() <= self::ERROR_CODE_LIMIT) { $payment->setStatus(self::STATUS_SUCCESS); } else { if ($response->getResponseCode() > self::ERROR_CODE_LIMIT && $response->getResponseCode() < self::ERROR_CODE_UPPER_LIMIT) { $error = Mage::helper('paygate')->__($this->_errors[$response->getResponseCode()]); } else { $error = Mage::helper('paygate')->__('Incomplete transaction.'); } } } else { $error = Mage::helper('paygate')->__('Invalid amount for authorization.'); } // we've got something bad here. if ($error !== false) { Mage::throwException($error); } return $this; }
/** * Send capture request to gateway * * @param Varien_Object $payment * @param decimal $amount * @return Start_Gateway_Model_Paymentmethod * @throws Mage_Core_Exception */ public function capture(Varien_Object $payment, $amount) { if ($amount <= 0) { Mage::throwException('Invalid amount for capture.'); } $payment->setAmount($amount); if ($payment->getParentTransactionId()) { $payment->setAnetTransType(self::REQUEST_TYPE_PRIOR_AUTH_CAPTURE); $payment->setXTransId($this->_getRealParentTransactionId($payment)); } else { $payment->setAnetTransType(self::REQUEST_TYPE_AUTH_CAPTURE); } //please call this function or some function to call API with token and email to capture authorized amount //$this->collectPayment($payment, $amount); //returning this as all good but it should return $this in case success and throw exception in case of error return $this; }
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 amount with transaction id * * @param string $payment Varien_Object object * @return Mage_Authorizenet_Model_Directpost * @throws Mage_Core_Exception */ protected function _refund(Varien_Object $payment, $amount) { if ($amount <= 0) { Mage::throwException(Mage::helper('paygate')->__('Invalid amount for refund.')); } if (!$payment->getParentTransactionId()) { Mage::throwException(Mage::helper('paygate')->__('Invalid transaction ID.')); } $payment->setAnetTransType(self::REQUEST_TYPE_CREDIT); $payment->setAmount($amount); $payment->setXTransId($this->_getRealParentTransactionId($payment)); $request = $this->_buildRequest($payment); $result = $this->_postRequest($request); switch ($result->getResponseCode()) { case self::RESPONSE_CODE_APPROVED: if ($result->getResponseReasonCode() == self::RESPONSE_REASON_CODE_APPROVED) { if ($result->getTransactionId() != $payment->getParentTransactionId()) { $payment->setTransactionId($result->getTransactionId()); } $shouldCloseCaptureTransaction = $payment->getOrder()->canCreditmemo() ? 0 : 1; $payment->setIsTransactionClosed(1)->setShouldCloseParentTransaction($shouldCloseCaptureTransaction)->setTransactionAdditionalInfo($this->_realTransactionIdKey, $result->getTransactionId()); return $this; } Mage::throwException($this->_wrapGatewayError($result->getResponseReasonText())); case self::RESPONSE_CODE_DECLINED: case self::RESPONSE_CODE_ERROR: Mage::throwException($this->_wrapGatewayError($result->getResponseReasonText())); default: Mage::throwException(Mage::helper('paygate')->__('Payment refunding error.')); } }
/** * 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; }