Example #1
0
 /**
  * Validates alias for in quote provided addresses
  * @param Mage_Sales_Model_Quote $quote
  * @param Varien_Object $payment
  * @throws Mage_Core_Exception
  */
 protected function validateAlias($quote, $payment)
 {
     $alias = $payment->getAdditionalInformation('alias');
     if (0 < strlen(trim($alias)) && is_numeric($payment->getAdditionalInformation('cvc')) && false === Mage::helper('ops/alias')->isAliasValidForAddresses($quote->getCustomerId(), $alias, $quote->getBillingAddress(), $quote->getShippingAddress(), $quote->getStoreId())) {
         $this->getOnepage()->getCheckout()->setGotoSection('payment');
         Mage::throwException($this->getHelper()->__('Invalid payment information provided!'));
     }
 }
Example #2
0
 public function create(Varien_Object $payment, $merchantAccount)
 {
     $this->merchantAccount = $merchantAccount;
     $this->browserInfo->acceptHeader = $_SERVER['HTTP_ACCEPT'];
     $this->browserInfo->userAgent = $_SERVER['HTTP_USER_AGENT'];
     $this->shopperIP = $_SERVER['REMOTE_ADDR'];
     $this->md = $payment->getAdditionalInformation('md');
     $this->paResponse = $payment->getAdditionalInformation('paResponse');
     return $this;
 }
Example #3
0
 /**
  * retrieves the basic parameters for a capture call
  *
  * @param Netresearch_OPS_Model_Payment_Abstract $opsPaymentMethod
  * @param Varien_Object $payment
  * @param                                        $amount
  * @param                                        $arrInfo
  *
  * @return $this
  */
 protected function getBaseParams(Netresearch_OPS_Model_Payment_Abstract $opsPaymentMethod, Varien_Object $payment, $amount, $arrInfo)
 {
     $this->requestParams['AMOUNT'] = $this->getDataHelper()->getAmount($amount);
     $this->requestParams['PAYID'] = $payment->getAdditionalInformation('paymentId');
     $this->requestParams['OPERATION'] = $arrInfo['operation'];
     $this->requestParams['CURRENCY'] = Mage::app()->getStore($payment->getOrder()->getStoreId())->getBaseCurrencyCode();
     return $this;
 }
 /**
  * Authorizes specified amount
  * 
  * @param Varien_Object $payment
  * @param decimal $amount
  * @param boolean $capture
  * @return Braintree_Payments_Model_Paymentmethod
  */
 protected function _authorize(Varien_Object $payment, $amount, $capture, $token = false)
 {
     try {
         $order = $payment->getOrder();
         $orderId = $order->getIncrementId();
         $billing = $order->getBillingAddress();
         $shipping = $order->getShippingAddress();
         $transactionParams = array('channel' => $this->_getChannel(), 'orderId' => $orderId, 'amount' => $amount, 'customer' => array('firstName' => $billing->getFirstname(), 'lastName' => $billing->getLastname(), 'company' => $billing->getCompany(), 'phone' => $billing->getTelephone(), 'fax' => $billing->getFax(), 'email' => $order->getCustomerEmail()));
         $customerId = Mage::helper('braintree_payments')->generateCustomerId($order->getCustomerId(), $order->getCustomerEmail());
         if ($order->getCustomerId() && $this->exists($customerId)) {
             $transactionParams['customerId'] = $customerId;
             unset($transactionParams['customer']);
         } else {
             $transactionParams['customer']['id'] = $customerId;
         }
         if ($capture) {
             $transactionParams['options']['submitForSettlement'] = true;
         }
         if ($this->_merchantAccountId) {
             $transactionParams['merchantAccountId'] = $this->_merchantAccountId;
         }
         $token = $this->_getMethodSpecificAuthorizeTransactionToken($token);
         if ($token) {
             $nonce = Mage::helper('braintree_payments')->getNonceForVaultedToken($token);
             $transactionParams['customerId'] = $customerId;
         } else {
             $transactionParams['billing'] = $this->_toBraintreeAddress($billing);
             $transactionParams['shipping'] = $this->_toBraintreeAddress($shipping);
             $transactionParams['options']['addBillingAddressToPaymentMethod'] = true;
             $nonce = $payment->getAdditionalInformation('nonce');
         }
         $transactionParams['paymentMethodNonce'] = $nonce;
         $transactionParams = array_merge_recursive($transactionParams, $this->_addMethodSpecificAuthorizeTransactionParams($payment));
         if (isset($transactionParams['options']['storeInVault']) && !$transactionParams['options']['storeInVault']) {
             $transactionParams['options']['addBillingAddressToPaymentMethod'] = false;
         }
         $this->_debug($transactionParams);
         try {
             $result = Braintree_Transaction::sale($transactionParams);
             $this->_debug($result);
         } catch (Exception $e) {
             Mage::logException($e);
             Mage::throwException(Mage::helper('braintree_payments')->__('Please try again later'));
         }
         if ($result->success) {
             $this->setStore($payment->getOrder()->getStoreId());
             $payment = $this->_processSuccessResult($payment, $result, $amount);
         } else {
             Mage::throwException(Mage::helper('braintree_payments/error')->parseBraintreeError($result));
         }
     } catch (Exception $e) {
         $this->_processMethodSpecificAuthorizeTransactionError();
         throw new Mage_Payment_Model_Info_Exception($e->getMessage());
     }
     return $this;
 }
Example #5
0
 public function authorize(Varien_Object $payment, $amount)
 {
     if ($amount <= 0) {
         Mage::throwException(Mage::helper('aplazame')->__('Invalid amount for authorization.'));
     }
     $token = $payment->getAdditionalInformation(self::CHECKOUT_TOKEN);
     $api = Mage::getModel('aplazame/api_client');
     $result = $api->setOrderId($token)->authorize();
     if (isset($result["id"])) {
         $this->getInfoInstance()->setAdditionalInformation("charge_id", $result["id"]);
     } else {
         Mage::throwException(Mage::helper('aplazame')->__('Aplazame charge id not returned from call.'));
     }
     $this->_validate_amount_result(Aplazame_Util::formatDecimals($amount), $result);
     $payment->setTransactionId($this->getChargeId())->setIsTransactionClosed(0);
     return $this;
 }
 /**
  * Void/Cancel
  */
 protected function _void(Varien_Object $payment)
 {
     $orderTransaction = $payment->lookupTransaction(false, Mage_Sales_Model_Order_Payment_Transaction::TYPE_ORDER);
     if (!$orderTransaction) {
         $orderTransactionId = $payment->getAdditionalInformation('order_reference');
     } else {
         $orderTransactionId = $orderTransaction->getTxnId();
     }
     if ($orderTransaction) {
         $this->_getApi()->cancelOrderReference($orderTransactionId);
     }
     return $this;
 }
 /**
  * Prepare request to gateway
  * 
  * HERE WE NEED TO CHIME IN AND USE AN EXISTING CUSTOMER ACCOUNT IF A TOKEN
  * IS PRESENT
  *
  * @link http://www.authorize.net/support/AIM_guide.pdf
  * @param Mage_Payment_Model_Info $payment
  * @return Mage_Paygate_Model_Authorizenet_Request
  */
 protected function _buildRequest(Varien_Object $payment)
 {
     $order = $payment->getOrder();
     $this->setStore($order->getStoreId());
     $request = $this->_getRequest()->setXType($payment->getAnetTransType())->setXMethod(self::REQUEST_METHOD_CC);
     if ($order && $order->getIncrementId()) {
         $request->setXInvoiceNum($order->getIncrementId());
     }
     if ($payment->getAmount()) {
         $request->setXAmount($payment->getAmount(), 2);
         $request->setXCurrencyCode($order->getBaseCurrencyCode());
     }
     switch ($payment->getAnetTransType()) {
         case self::REQUEST_TYPE_AUTH_CAPTURE:
             $request->setXAllowPartialAuth($this->getConfigData('allow_partial_authorization') ? 'True' : 'False');
             if ($payment->getAdditionalInformation($this->_splitTenderIdKey)) {
                 $request->setXSplitTenderId($payment->getAdditionalInformation($this->_splitTenderIdKey));
             }
             break;
         case self::REQUEST_TYPE_AUTH_ONLY:
             $request->setXAllowPartialAuth($this->getConfigData('allow_partial_authorization') ? 'True' : 'False');
             if ($payment->getAdditionalInformation($this->_splitTenderIdKey)) {
                 $request->setXSplitTenderId($payment->getAdditionalInformation($this->_splitTenderIdKey));
             }
             break;
         case self::REQUEST_TYPE_CREDIT:
             /**
              * Send last 4 digits of credit card number to authorize.net
              * otherwise it will give an error
              * 
              * x_trans_id is the transaction ID we provide every 
              * transaction. It would be used to reference transactions in 
              * our system when doing export requests, etc.
              * 
              */
             $request->setXCardNum($payment->getCcLast4());
             $request->setXTransId($payment->getXTransId());
             break;
         case self::REQUEST_TYPE_VOID:
             $request->setXTransId($payment->getXTransId());
             break;
         case self::REQUEST_TYPE_PRIOR_AUTH_CAPTURE:
             $request->setXTransId($payment->getXTransId());
             break;
         case self::REQUEST_TYPE_CAPTURE_ONLY:
             /**
              * x_auth_code is the authorization code you would pass if you 
              * were doing a forced sale type where you already had an 
              * approval and needed to force it into PayTrace.
              */
             $request->setXAuthCode($payment->getCcAuthCode());
             break;
     }
     if ($this->getIsCentinelValidationEnabled()) {
         $params = $this->getCentinelValidator()->exportCmpiData(array());
         $request = Varien_Object_Mapper::accumulateByMap($params, $request, $this->_centinelFieldMap);
     }
     /**
      * x_description is a description you can pass along with the 
      * transaction which will show in PayTrace reporting for reporting 
      * purposes.
      */
     $request->setXDescription('Magento Store Online Order');
     if (!empty($order)) {
         $billing = $order->getBillingAddress();
         if (!empty($billing)) {
             $request->setXDelimChar(self::RESPONSE_DELIM_CHAR)->setXEncapChar('')->setXFirstName($billing->getFirstname())->setXLastName($billing->getLastname())->setXCompany($billing->getCompany())->setXAddress($billing->getStreet(1))->setXCity($billing->getCity())->setXState($billing->getRegion())->setXZip($billing->getPostcode())->setXPhone($billing->getTelephone())->setXFax($billing->getFax())->setXEmail($order->getCustomerEmail())->setXMerchantEmail($this->getConfigData('merchant_email'));
         }
         $shipping = $order->getShippingAddress();
         if (!empty($shipping)) {
             $request->setXShipToFirstName($shipping->getFirstname())->setXShipToLastName($shipping->getLastname())->setXShipToCompany($shipping->getCompany())->setXShipToAddress($shipping->getStreet(1))->setXShipToCity($shipping->getCity())->setXShipToState($shipping->getRegion())->setXShipToZip($shipping->getPostcode())->setXShipToCountry($shipping->getCountry());
         }
         /*
          * x_po_num - * For Authorize.net this field is for Purchase 
          * Order numbers, for PayTrace this is only used for 
          * transactions that are identified as corporate or purchasing 
          * credit cards. This is an identifier that your customer may 
          * ask you to provide in order to reference the transaction to 
          * their credit card statement.
          */
         //e            $po_number = $order->getPoNumber()
         //                        ?$order->getPoNumber()
         //                        : ($order->getQuote()
         //                               ? $order->getQuote()->getPoNumber()
         //                                : '');
         //
         //            $request->setXPoNum($po_number);
         //
         //            $request->setXTax($order->getBaseTaxAmount())
         //f               ->setXFreight($order->getBaseShippingAmount());
         //
         //    //        Use these fields if we're using a stored credit card
         //            $useSavedCard = $order->getUseSavedCard()
         //                    ? $order->getUseSavedCard()
         //                    : ($order->getQuote()
         //                            ? $order->getQuote()->getUseSavedCard()
         //                            : false);
         //            if ($useSavedCard) {
         //                // setXCustid
         //                // setXCustomerProfileId
         //                // setXCustomerPaymentProfileId
         //                $request->setXCustId( $order->getCustomerId() );
         //            }
     }
     //        Use these fields if we're using a newly entered credit card
     if ($payment->getCcNumber()) {
         $request->setXCardNum($payment->getCcNumber())->setXExpDate(sprintf('%02d-%04d', $payment->getCcExpMonth(), $payment->getCcExpYear()))->setXCardCode($payment->getCcCid());
     }
     return $request;
 }
 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
 /**
  * Void payment
  *
  * @param   Varien_Object $invoicePayment
  * @return  Mage_Payment_Model_Abstract
  */
 public function void(Varien_Object $payment)
 {
     $error = false;
     // Void is not enabled.
     if (!$this->getConfigData('enable_void')) {
         return $this;
     }
     if (in_array($payment->getAdditionalInformation(self::PAYMENTMETHOD), $this->_directPaymentMethods)) {
         // Do not run financial transactions on directpayment.
         return $this;
     }
     if (!$payment->getAdditionalInformation(self::TRANSACTION_ID)) {
         if (!$payment->getBbsTransactionId()) {
             $this->getApi()->doLog(Mage::helper('bbsnetaxept')->__('Could not find transaction id.'));
             return $this;
         } else {
             $bbsTransId = $payment->getBbsTransactionId();
             // Make it compatible with old fashion BBSNetterminal.
         }
     } else {
         $bbsTransId = $payment->getAdditionalInformation(self::TRANSACTION_ID);
     }
     $order = $payment->getOrder();
     $this->_useMobile = $payment->getAdditionalInformation(self::MOBILE_CLIENT) === true;
     if ($order->getInvoiceCollection()->count() > 0) {
         // Do no try to annul orders that have invoices.
         return $this;
     }
     $InvoiceId = $order->getIncrementId() ? $order->getIncrementId() : 'Unknown';
     if ($this->getApi()->void($bbsTransId, $InvoiceId) == $bbsTransId) {
         $payment->setStatus(self::STATUS_SUCCESS);
     } else {
         $error = Mage::helper('bbsnetaxept')->__('Error void the payment: %s', $this->getApi()->getErrorMessage());
     }
     if ($error !== false) {
         $this->getApi()->doLog($error);
         //    Mage::throwException($error);
     }
     return $this;
 }
 /**
  * Call DoAuthorize
  *
  * @param int $amount
  * @param Varien_Object $payment
  * @param string $parentTransactionId
  * @return Mage_Paypal_Model_Api_Abstract
  * @throws Mage_Paypal_Model_Api_ProcessableException
  */
 protected function _callDoAuthorize($amount, $payment, $parentTransactionId)
 {
     $apiData = $this->_pro->getApi()->getData();
     foreach ($apiData as $k => $v) {
         if (is_object($v)) {
             unset($apiData[$k]);
         }
     }
     Mage::getSingleton('checkout/session')->setPaypalTransactionData($apiData);
     $this->_pro->resetApi();
     $api = $this->_setApiProcessableErrors()->setAmount($amount)->setCurrencyCode($payment->getOrder()->getBaseCurrencyCode())->setTransactionId($parentTransactionId)->callDoAuthorization();
     $payment->setAdditionalInformation($this->_authorizationCountKey, $payment->getAdditionalInformation($this->_authorizationCountKey) + 1);
     return $api;
 }
Example #11
0
 public function capture(Varien_Object $payment, $amount)
 {
     if ($payment->getAdditionalInformation('hyperpay_transaction_code') == 'PA') {
         $refId = $payment->getAdditionalInformation('IDENTIFICATION_REFERENCEID');
         $currency = $payment->getAdditionalInformation('CURRENCY');
         $dataTransaction = $this->getCredentials();
         $dataTransaction['tx_mode'] = $this->getTransactionMode();
         $postData = getPostCapture($refId, $amount, $currency, $dataTransaction);
         $server = $this->getServerMode();
         $url = getExecuteUrl($server);
         $response = executePayment($postData, $url);
         $result = buildResponseArray($response);
         $payment->setAdditionalInformation('CAPTURE', $result['PROCESSING.RESULT']);
         if ($result['PROCESSING.RESULT'] == 'ACK') {
             $payment->setStatus('APPROVED')->setTransactionId($payment->getAdditionalInformation('IDENTIFICATION_REFERENCEID'))->setIsTransactionClosed(1)->save();
         } else {
             Mage::throwException(Mage::helper('hyperpay')->__('An error occurred while processing'));
         }
     } else {
         $payment->setStatus('APPROVED')->setTransactionId($payment->getAdditionalInformation('IDENTIFICATION_REFERENCEID'))->setIsTransactionClosed(1)->save();
     }
     return $this;
 }
 /**
  * Trigger online refund action from admin panel.
  *
  * @param Varien_Object $payment
  * @param float $amount
  * @return $this|Mage_Payment_Model_Abstract
  * @throws Mage_Core_Exception
  */
 public function refund(Varien_Object $payment, $amount)
 {
     $bzRefund = Mage::getModel('barzahlen/api_request_refund', array('transactionId' => $payment->getAdditionalInformation('transaction_id'), 'amount' => $amount, 'currency' => $payment->getOrder()->getOrderCurrencyCode()));
     try {
         $this->getBarzahlenApi()->handleRequest($bzRefund);
         $payment->setTransactionId($bzRefund->getRefundTransactionId());
     } catch (Exception $e) {
         Mage::helper('barzahlen')->bzLog($e);
         if (strpos($e->getMessage(), 'refund declined')) {
             Mage::throwException(Mage::helper('barzahlen')->__('bz_adm_refund_declined'));
         } else {
             Mage::throwException(Mage::helper('barzahlen')->__('bz_adm_refund_error'));
         }
     }
     return $this;
 }
 /**
  * Prepare request to gateway
  *
  * @link http://www.authorize.net/support/AIM_guide.pdf
  * @param Mage_Payment_Model_Info $payment
  * @return Mage_Paygate_Model_Authorizenet_Request
  */
 protected function _buildRequest(Varien_Object $payment)
 {
     $order = $payment->getOrder();
     $this->setStore($order->getStoreId());
     $request = $this->_getRequest()->setXType($payment->getAnetTransType())->setXMethod(self::REQUEST_METHOD_CC);
     if ($order && $order->getIncrementId()) {
         $request->setXInvoiceNum($order->getIncrementId());
     }
     if ($payment->getAmount()) {
         $request->setXAmount($payment->getAmount(), 2);
         $request->setXCurrencyCode($order->getBaseCurrencyCode());
     }
     switch ($payment->getAnetTransType()) {
         case self::REQUEST_TYPE_AUTH_CAPTURE:
             $request->setXAllowPartialAuth($this->getConfigData('allow_partial_authorization') ? 'True' : 'False');
             if ($payment->getAdditionalInformation($this->_splitTenderIdKey)) {
                 $request->setXSplitTenderId($payment->getAdditionalInformation($this->_splitTenderIdKey));
             }
             break;
         case self::REQUEST_TYPE_AUTH_ONLY:
             $request->setXAllowPartialAuth($this->getConfigData('allow_partial_authorization') ? 'True' : 'False');
             if ($payment->getAdditionalInformation($this->_splitTenderIdKey)) {
                 $request->setXSplitTenderId($payment->getAdditionalInformation($this->_splitTenderIdKey));
             }
             break;
         case self::REQUEST_TYPE_CREDIT:
             /**
              * Send last 4 digits of credit card number to authorize.net
              * otherwise it will give an error
              */
             $request->setXCardNum($payment->getCcLast4());
             $request->setXTransId($payment->getXTransId());
             break;
         case self::REQUEST_TYPE_VOID:
             $request->setXTransId($payment->getXTransId());
             break;
         case self::REQUEST_TYPE_PRIOR_AUTH_CAPTURE:
             $request->setXTransId($payment->getXTransId());
             break;
         case self::REQUEST_TYPE_CAPTURE_ONLY:
             $request->setXAuthCode($payment->getCcAuthCode());
             break;
     }
     if ($this->getIsCentinelValidationEnabled()) {
         $params = $this->getCentinelValidator()->exportCmpiData(array());
         $request = Varien_Object_Mapper::accumulateByMap($params, $request, $this->_centinelFieldMap);
     }
     if (!empty($order)) {
         $billing = $order->getBillingAddress();
         if (!empty($billing)) {
             $request->setXFirstName($billing->getFirstname())->setXLastName($billing->getLastname())->setXCompany($billing->getCompany())->setXAddress($billing->getStreet(1))->setXCity($billing->getCity())->setXState($billing->getRegion())->setXZip($billing->getPostcode())->setXCountry($billing->getCountry())->setXPhone($billing->getTelephone())->setXFax($billing->getFax())->setXCustId($order->getCustomerId())->setXCustomerIp($order->getRemoteIp())->setXCustomerTaxId($billing->getTaxId())->setXEmail($order->getCustomerEmail())->setXEmailCustomer($this->getConfigData('email_customer'))->setXMerchantEmail($this->getConfigData('merchant_email'));
         }
         $shipping = $order->getShippingAddress();
         if (!empty($shipping)) {
             $request->setXShipToFirstName($shipping->getFirstname())->setXShipToLastName($shipping->getLastname())->setXShipToCompany($shipping->getCompany())->setXShipToAddress($shipping->getStreet(1))->setXShipToCity($shipping->getCity())->setXShipToState($shipping->getRegion())->setXShipToZip($shipping->getPostcode())->setXShipToCountry($shipping->getCountry());
         }
         $request->setXPoNum($payment->getPoNumber())->setXTax($order->getBaseTaxAmount())->setXFreight($order->getBaseShippingAmount());
     }
     if ($payment->getCcNumber()) {
         $request->setXCardNum($payment->getCcNumber())->setXExpDate(sprintf('%02d-%04d', $payment->getCcExpMonth(), $payment->getCcExpYear()))->setXCardCode($payment->getCcCid());
     }
     return $request;
 }
Example #14
0
 public function refund(Varien_Object $payment, $amount)
 {
     if ($order = $payment->getOrder()) {
         $worldpay = $this->setupWorldpay();
         try {
             $logger = Mage::helper('worldpay/logger');
             $worldpay->refundOrder($payment->getAdditionalInformation("worldpayOrderCode"), $amount * 100);
             return $this;
         } catch (Exception $e) {
             Mage::throwException('Refund failed ' . $e->getMessage());
         }
     }
     Mage::throwException('No matching order found in Worldpay to refund. Please visit your Worldpay dashboard and refund the order manually.');
 }
Example #15
0
 public function create(Varien_Object $payment, $amount, $paymentMethod = null, $merchantAccount = null, $recurringType = null, $recurringPaymentType = null, $enableMoto = null)
 {
     $order = $payment->getOrder();
     $incrementId = $order->getIncrementId();
     $orderCurrencyCode = $order->getOrderCurrencyCode();
     // override amount because this amount uses the right currency
     $amount = $order->getGrandTotal();
     $customerId = $order->getCustomerId();
     if ($customerId) {
         $customer = Mage::getModel('customer/customer')->load($order->getCustomerId());
         $customerId = $customer->getData('adyen_customer_ref') ?: $customer->getData('increment_id') ?: $customerId;
     }
     $realOrderId = $order->getRealOrderId();
     $this->reference = $incrementId;
     $this->merchantAccount = $merchantAccount;
     $this->amount->currency = $orderCurrencyCode;
     $this->amount->value = Mage::helper('adyen')->formatAmount($amount, $orderCurrencyCode);
     //shopper data
     $customerEmail = $order->getCustomerEmail();
     $this->shopperEmail = $customerEmail;
     $this->shopperIP = $order->getRemoteIp();
     $this->shopperReference = !empty($customerId) ? $customerId : self::GUEST_ID . $realOrderId;
     // Set the recurring contract
     if ($recurringType) {
         if ($paymentMethod == "oneclick") {
             // For ONECLICK look at the recurringPaymentType that the merchant has selected in Adyen ONECLICK settings
             if ($payment->getAdditionalInformation('customer_interaction')) {
                 $this->recurring = new Adyen_Payment_Model_Adyen_Data_Recurring();
                 $this->recurring->contract = "ONECLICK";
             } else {
                 $this->recurring = new Adyen_Payment_Model_Adyen_Data_Recurring();
                 $this->recurring->contract = "RECURRING";
             }
         } elseif ($paymentMethod == "cc") {
             // if save card is disabled only shoot in as recurring if recurringType is set to ONECLICK,RECURRING
             if ($payment->getAdditionalInformation("store_cc") == "" && $recurringType == "ONECLICK,RECURRING") {
                 $this->recurring = new Adyen_Payment_Model_Adyen_Data_Recurring();
                 $this->recurring->contract = "RECURRING";
             } elseif ($payment->getAdditionalInformation("store_cc") == "1") {
                 $this->recurring = new Adyen_Payment_Model_Adyen_Data_Recurring();
                 $this->recurring->contract = $recurringType;
             } elseif ($recurringType == "RECURRING") {
                 // recurring permission is not needed from shopper so just save it as recurring
                 $this->recurring = new Adyen_Payment_Model_Adyen_Data_Recurring();
                 $this->recurring->contract = "RECURRING";
             }
         } else {
             $this->recurring = new Adyen_Payment_Model_Adyen_Data_Recurring();
             $this->recurring->contract = $recurringType;
         }
     }
     /**
      * Browser info
      * @var unknown_type
      */
     if (isset($_SERVER['HTTP_ACCEPT'])) {
         $this->browserInfo->acceptHeader = $_SERVER['HTTP_ACCEPT'];
     }
     if (isset($_SERVER['HTTP_USER_AGENT'])) {
         $this->browserInfo->userAgent = $_SERVER['HTTP_USER_AGENT'];
     }
     switch ($paymentMethod) {
         case "elv":
             $elv = unserialize($payment->getPoNumber());
             $this->card = null;
             $this->shopperName = null;
             $this->bankAccount = null;
             $this->elv->accountHolderName = $elv['account_owner'];
             $this->elv->bankAccountNumber = $elv['account_number'];
             $this->elv->bankLocation = $elv['bank_location'];
             $this->elv->bankLocationId = $elv['bank_location'];
             $this->elv->bankName = $elv['bank_name'];
             break;
         case "cc":
         case "oneclick":
             $this->shopperName = null;
             $this->elv = null;
             $this->bankAccount = null;
             $billingAddress = $order->getBillingAddress();
             $helper = Mage::helper('adyen');
             if ($billingAddress) {
                 $this->billingAddress = new Adyen_Payment_Model_Adyen_Data_BillingAddress();
                 $this->billingAddress->street = $helper->getStreet($billingAddress)->getName();
                 $this->billingAddress->houseNumberOrName = $helper->getStreet($billingAddress)->getHouseNumber();
                 $this->billingAddress->city = $billingAddress->getCity();
                 $this->billingAddress->postalCode = $billingAddress->getPostcode();
                 $this->billingAddress->stateOrProvince = $billingAddress->getRegionCode();
                 $this->billingAddress->country = $billingAddress->getCountryId();
             }
             $deliveryAddress = $order->getShippingAddress();
             if ($deliveryAddress) {
                 $this->deliveryAddress = new Adyen_Payment_Model_Adyen_Data_DeliveryAddress();
                 $this->deliveryAddress->street = $helper->getStreet($deliveryAddress)->getName();
                 $this->deliveryAddress->houseNumberOrName = $helper->getStreet($deliveryAddress)->getHouseNumber();
                 $this->deliveryAddress->city = $deliveryAddress->getCity();
                 $this->deliveryAddress->postalCode = $deliveryAddress->getPostcode();
                 $this->deliveryAddress->stateOrProvince = $deliveryAddress->getRegionCode();
                 $this->deliveryAddress->country = $deliveryAddress->getCountryId();
             }
             if ($paymentMethod == "oneclick") {
                 $recurringDetailReference = $payment->getAdditionalInformation("recurring_detail_reference");
                 if ($payment->getAdditionalInformation('customer_interaction')) {
                     $this->shopperInteraction = "Ecommerce";
                 } else {
                     $this->shopperInteraction = "ContAuth";
                 }
                 // For recurring Ideal and Sofort needs to be converted to SEPA for this it is mandatory to set selectBrand to sepadirectdebit
                 if (!$payment->getAdditionalInformation('customer_interaction')) {
                     if ($payment->getCcType() == "directEbanking" || $payment->getCcType() == "ideal") {
                         $this->selectedBrand = "sepadirectdebit";
                     }
                 }
             } else {
                 $recurringDetailReference = null;
                 $this->shopperInteraction = "Ecommerce";
             }
             if ($paymentMethod == "cc" && Mage::app()->getStore()->isAdmin() && $enableMoto != null && $enableMoto == 1) {
                 $this->shopperInteraction = "Moto";
             }
             // if it is a sepadirectdebit set selectedBrand to sepadirectdebit
             if ($payment->getCcType() == "sepadirectdebit") {
                 $this->selectedBrand = "sepadirectdebit";
             }
             if ($recurringDetailReference && $recurringDetailReference != "") {
                 $this->selectedRecurringDetailReference = $recurringDetailReference;
             }
             if (Mage::getModel('adyen/adyen_cc')->isCseEnabled()) {
                 $this->card = null;
                 // this is only needed for creditcards
                 if ($payment->getAdditionalInformation("encrypted_data") != "") {
                     $kv = new Adyen_Payment_Model_Adyen_Data_AdditionalDataKVPair();
                     $kv->key = new SoapVar("card.encrypted.json", XSD_STRING, "string", "http://www.w3.org/2001/XMLSchema");
                     $kv->value = new SoapVar($payment->getAdditionalInformation("encrypted_data"), XSD_STRING, "string", "http://www.w3.org/2001/XMLSchema");
                     $this->additionalData->entry = $kv;
                 } else {
                     if ($paymentMethod == 'cc') {
                         // log the browser data to see why it is failing
                         Mage::log($_SERVER['HTTP_USER_AGENT'], Zend_Log::ERR, "adyen_exception.log", true);
                         // For CC encrypted data is needed if you use CSE
                         Adyen_Payment_Exception::throwException(Mage::helper('adyen')->__('Missing the encrypted data value. Make sure the Client Side Encryption(CSE) script did encrypt the Credit Card details'));
                     }
                 }
             } else {
                 if ($recurringDetailReference && $recurringDetailReference != "") {
                     // this is only needed for creditcards
                     if ($payment->getCcCid() != "" && $payment->getCcExpMonth() != "" && $payment->getCcExpYear() != "") {
                         if ($recurringType != "RECURRING") {
                             $this->card->cvc = $payment->getCcCid();
                         }
                         $this->card->expiryMonth = $payment->getCcExpMonth();
                         $this->card->expiryYear = $payment->getCcExpYear();
                     } else {
                         $this->card = null;
                     }
                 } else {
                     // this is only the case for adyen_cc payments
                     $this->card->cvc = $payment->getCcCid();
                     $this->card->expiryMonth = $payment->getCcExpMonth();
                     $this->card->expiryYear = $payment->getCcExpYear();
                     $this->card->holderName = $payment->getCcOwner();
                     $this->card->number = $payment->getCcNumber();
                 }
             }
             // installments
             if (Mage::helper('adyen/installments')->isInstallmentsEnabled() && $payment->getAdditionalInformation('number_of_installments') > 0) {
                 $this->installments = new Adyen_Payment_Model_Adyen_Data_Installments();
                 $this->installments->value = $payment->getAdditionalInformation('number_of_installments');
             }
             // add observer to have option to overrule and or add request data
             Mage::dispatchEvent('adyen_payment_card_payment_request', array('order' => $order, 'paymentMethod' => $paymentMethod, 'paymentRequest' => $this));
             break;
         case "boleto":
             $boleto = unserialize($payment->getPoNumber());
             $this->card = null;
             $this->elv = null;
             $this->bankAccount = null;
             $this->socialSecurityNumber = $boleto['social_security_number'];
             $this->selectedBrand = $boleto['selected_brand'];
             $this->shopperName->firstName = $boleto['firstname'];
             $this->shopperName->lastName = $boleto['lastname'];
             $this->deliveryDate = $boleto['delivery_date'];
             break;
         case "sepa":
             $sepa = unserialize($payment->getPoNumber());
             $this->card = null;
             $this->elv = null;
             $this->shopperName = null;
             $this->bankAccount->iban = $sepa['iban'];
             $this->bankAccount->ownerName = $sepa['account_name'];
             $this->bankAccount->countryCode = $sepa['country'];
             $this->selectedBrand = "sepadirectdebit";
             break;
     }
     return $this;
 }
 /**
  * update invoice items to sofortueberweisung
  * 
  * @param Varien_Object $payment object of the order
  * @param array $items of the the invoice
  * @param string $comment to add
  * @param string $invoiceNumber
  * @param string $customerNumber
  * @param string $orderNumber
  * @return Paymentnetwork_Pnsofortueberweisung_Model_Sofortrechnung
  * @throws Exception
  */
 public function updateInvoice(Varien_Object $payment, $items, $comment, $invoiceNumber = '', $customerNumber = '', $orderNumber = '')
 {
     // load current transaction id
     $transactionId = $payment->getAdditionalInformation('sofort_transaction');
     $order = $payment->getOrder();
     if (!empty($transactionId)) {
         // create articles
         $pnagArticles = array();
         foreach ($items as $item) {
             array_push($pnagArticles, array('itemId' => $item['item_id'], 'productNumber' => $item['product_number'], 'productType' => $item['product_type'], 'title' => $item['title'], 'description' => $item['description'], 'quantity' => $item['quantity'], 'unitPrice' => $item['unit_price'], 'tax' => $item['tax']));
         }
         // create connection class
         $PnagInvoice = new PnagInvoice(Mage::getStoreConfig('payment/sofort/configkey'), $transactionId);
         $PnagInvoice->setTransactionId($transactionId);
         $PnagInvoice->updateInvoice($transactionId, $pnagArticles, $comment, $invoiceNumber, $customerNumber, $orderNumber);
         // add error
         if ($PnagInvoice->isError()) {
             Mage::throwException($PnagInvoice->getError());
         } else {
             // update history
             $order->addStatusHistoryComment(Mage::helper('pnsofortueberweisung')->__('The invoice has been edit.') . "\n\n\"" . $comment . '"');
             $order->save();
             Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('pnsofortueberweisung')->__('Successfully edit invoice.'));
             return $this;
         }
     }
     // no transaction id exist
     Mage::getSingleton('adminhtml/session')->addError(Mage::helper('pnsofortueberweisung')->__('Could not edit invoice.'));
     return $this;
 }
Example #17
0
 public function _place(Varien_Object $payment, $amount, $requestType)
 {
     try {
         $order = $payment->getOrder();
         $billingAddress = $order->getBillingAddress();
         $flag = $payment->getCcType();
         $parcels = $payment->getInstallments();
         $parcelMax = Mage::getStoreConfig('payment/azpay_cc/max_installments_' . $flag . '');
         $parcelMinValue = ceil(Mage::getStoreConfig('payment/azpay_cc/min_installment_value_' . $flag . ''));
         $amountTotal = ceil(Mage::helper('azpay')->formatAmount($amount));
         $parcelValue = ceil($amountTotal / $parcels);
         // Check quantity of parcels
         if ($parcels > $parcelMax) {
             return Mage::throwException("Quantidade inválida de parcelas.");
         }
         // Check value of parcel
         if ($parcelValue < $parcelMinValue) {
             return Mage::throwException("Valor da parcela inválido.");
         }
         //AZPay config
         $azpay = new AZPay($this->_merchantId, $this->_merchantKey);
         $azpay->curl_timeout = 60;
         $azpay->config_order['reference'] = $order->getRealOrderId();
         $azpay->config_order['totalAmount'] = Mage::helper('azpay')->formatAmount($amount);
         $azpay->config_options['urlReturn'] = Mage::getUrl('azpay/transaction_cc/postback');
         $azpay->config_card_payments['amount'] = Mage::helper('azpay')->formatAmount($amount);
         $azpay->config_card_payments['acquirer'] = $this->getConfigData('acquirer_' . $flag . '');
         $azpay->config_card_payments['method'] = $parcels == '1' ? 1 : 2;
         $azpay->config_card_payments['flag'] = $payment->getCcType();
         $azpay->config_card_payments['numberOfPayments'] = $parcels;
         $azpay->config_card_payments['cardHolder'] = $payment->getCcOwner();
         $azpay->config_card_payments['cardNumber'] = Mage::helper('core')->decrypt($payment->getCcNumber());
         $azpay->config_card_payments['cardSecurityCode'] = Mage::helper('core')->decrypt($payment->getCcCid());
         $azpay->config_card_payments['cardExpirationDate'] = $payment->getCcExpYear() . $payment->getCcExpMonth();
         if ($order->getCustomerId()) {
             $azpay->config_billing['customerIdentity'] = $order->getCustomerId();
         } else {
             $azpay->config_billing['customerIdentity'] = $order->getRealOrderId();
         }
         $azpay->config_billing['name'] = $order->getCustomerName();
         $azpay->config_billing['address'] = $billingAddress->getStreet(1);
         $azpay->config_billing['addressNumber'] = $billingAddress->getStreet(2);
         $azpay->config_billing['address2'] = $billingAddress->getStreet(3) ? $billingAddress->getStreet(3) : '';
         $azpay->config_billing['city'] = $billingAddress->getCity();
         $azpay->config_billing['state'] = $billingAddress->getRegionCode();
         $azpay->config_billing['postalCode'] = Zend_Filter::filterStatic($billingAddress->getPostcode(), 'Digits');
         $azpay->config_billing['phone'] = $billingAddress->getTelephone();
         $azpay->config_billing['email'] = $order->getCustomerEmail();
         //Authorize method
         if ($requestType == "authorize") {
             //Fraud config
             $phoneData = Mage::helper('azpay')->splitTelephone($billingAddress->getTelephone());
             $costumerIP = $payment->getAdditionalInformation('customer_ip');
             $azpay->config_options['fraud'] = "true";
             $azpay->config_options['costumerIP'] = $costumerIP;
             $azpay->config_billing['phonePrefix'] = $phoneData['ddd'];
             $azpay->config_billing['phoneNumber'] = $phoneData['number'];
             foreach ($order->getItemsCollection() as $_item) {
                 $azpay->config_product['productName'] = $_item->getProduct()->getName();
                 $azpay->config_product['quantity'] = $_item->getQtyOrdered();
                 $azpay->config_product['price'] = $_item->getProduct()->getFinalPrice($_item->getQtyOrdered());
             }
             //Prepare authorization to transaction
             $operation = $azpay->authorize();
             //XML to save in log
             $azpay->getXml();
         }
         //Sale method
         if ($requestType == "authorize_capture") {
             //Prepare authorization to direct sale
             $operation = $azpay->sale();
         }
         //Log
         if ($this->getConfigData('log')) {
             Mage::log($azpay, null, "azpay_cc.log");
         }
         //Execute operation
         $operation->execute();
     } catch (AZPay_Error $e) {
         # HTTP 409 - AZPay Error
         $error = $azpay->responseError();
         $response_message = $error['error_message'];
         Mage::log($e->getMessage(), null, "azpay_cc_error.log");
         return Mage::throwException("Ocorreu um erro com o seu pagamento: " . $response_message);
     } catch (AZPay_Curl_Exception $e) {
         # Connection Error
         $response_message = $e->getMessage();
         return Mage::throwException("Ocorreu um erro com o seu pagamento: " . $response_message);
     } catch (AZPay_Exception $e) {
         # General Error
         $response_message = $e->getMessage();
         return Mage::throwException("Ocorreu um erro com o seu pagamento: " . $response_message);
     }
     //Response AZPay
     $gateway_response = $azpay->response();
     //Check response return
     if (!isset($gateway_response)) {
         return Mage::throwException("Ocorreu um erro com a resposta do pagamento");
     }
     $response_status = intval($gateway_response->status);
     $response_message = Config::$STATUS_MESSAGES[$response_status]['title'];
     if ($response_status == Config::$STATUS['AUTHORIZED'] || $response_status == Config::$STATUS['APPROVED']) {
     } else {
         return Mage::throwException("Ocorreu um erro com o seu pagamento: " . $response_message);
     }
     // azpay info
     $payment->setAzpayTransactionId($gateway_response->transactionId);
     return $this;
 }
Example #18
0
 private function ProcessApi(Varien_Object $payment, $transcition_type, $amount = false)
 {
     //call your authorize api here, incase of error throw exception.
     //only example code written below to show flow of code
     $order = $payment->getOrder();
     $paymentAction = $this->getConfigData('payment_action');
     $totals = strval($amount * 100);
     $orderId = $order->getIncrementId();
     $currencyDesc = $order->getBaseCurrencyCode();
     $order = $payment->getOrder();
     $szOrderID = $order->getRealOrderId();
     //$szCrossReference = $payment->getLastTransId();
     $additionalInformation = $payment->getAdditionalInformation();
     $szCrossReference = $additionalInformation["CrossReference"];
     $szPaymentCurrency = $additionalInformation["PaymentCurrency"];
     //$szCrossReference = $payment->getLastTransId();
     // check the CrossRference and TransactionType parameters
     if (!$szCrossReference) {
         $error = 'Error occurred for ' . $szTransactionType . ': Missing Cross Reference';
     }
     if (!$szTransactionType) {
         $error = 'Error occurred for ' . $szTransactionType . ': Missing Transaction Type';
     }
     /* Checking Payment method */
     $payment_method_code = $order->getPayment()->getMethodInstance()->getCode();
     if ($payment_method_code == 'payhosted') {
         $MerchantPassword = Mage::getStoreConfig('payment/payhosted/api_password');
         $MerchantID = trim(Mage::getStoreConfig('payment/payhosted/api_username'));
         $module_currency_code = Mage::getStoreConfig('payment/payhosted/payment_currency');
     } elseif ($payment_method_code == 'pay') {
         $MerchantPassword = Mage::getStoreConfig('payment/pay/api_password');
         $MerchantID = trim(Mage::getStoreConfig('payment/pay/api_username'));
         $module_currency_code = Mage::getStoreConfig('payment/pay/payment_currency');
     } elseif ($payment_method_code == 'paymoto') {
         $MerchantPassword = Mage::getStoreConfig('payment/paymoto/api_password');
         $MerchantID = trim(Mage::getStoreConfig('payment/paymoto/api_username'));
         $module_currency_code = Mage::getStoreConfig('payment/paymoto/payment_currency');
     }
     // Set Currency and Rates
     $baseCurrency_code = Mage::app()->getBaseCurrencyCode();
     $storeId = Mage::app()->getStore()->getId();
     $SelectedCurrency = Mage::app()->getStore($storeId)->getCurrentCurrencyCode();
     //$currency_code        = Mage::app()->getStore()->getCurrentCurrencyCode();
     $currcode = $order->getOrderCurrencyCode();
     $paymentSenseSelectedCurrency = explode(',', $module_currency_code);
     $curArray = array('USD', 'GBP', 'EUR');
     if ($szPaymentCurrency == '') {
         if (in_array($SelectedCurrency, $paymentSenseSelectedCurrency)) {
             $currcode = $SelectedCurrency;
         } else {
             if (in_array($baseCurrency_code, $paymentSenseSelectedCurrency)) {
                 $currcode = $baseCurrency_code;
             } else {
                 if (in_array($baseCurrency_code, $curArray)) {
                     $currcode = $paymentSenseSelectedCurrency[0];
                 } else {
                     return array('status' => 0, 'transaction_id' => time(), 'fraud' => rand(0, 1), 'message' => 'Currency Error', 'data' => '', 'CrossReference' => '');
                 }
             }
         }
     } else {
         $currcode = $szPaymentCurrency;
     }
     $grandTotal = $order->getData('base_grand_total');
     $allowedCurrencies = Mage::getModel('directory/currency')->getConfigAllowCurrencies();
     $currencyRates = Mage::getModel('directory/currency')->getCurrencyRates($baseCurrency_code, array_values($allowedCurrencies));
     //$baseCurrnecyrate  =  1/$currencyRates[Mage::app()->getStore()->getCurrentCurrencyCode()];
     $baseCurrnecyrate = $currencyRates[$currcode];
     if ($currcode == 'EUR') {
         if ($currcode = $baseCurrency_code && $baseCurrency_code != '') {
             //$newprice = number_format((float)($order->getGrandTotal()*$baseCurrnecyrate),'2', '.', '');
             $newprice = number_format((double) ($grandTotal * $baseCurrnecyrate), '2', '.', '');
         } else {
             //$newprice = Mage::helper('directory')->currencyConvert($order->getGrandTotal(),'EUR',Mage::app()->getStore()->getCurrentCurrencyCode());
             $newprice = Mage::helper('directory')->currencyConvert($grandTotal, 'EUR', Mage::app()->getStore()->getCurrentCurrencyCode());
         }
         $currdes = '978';
     } elseif ($currcode == 'GBP') {
         if ($currcode = $baseCurrency_code && $baseCurrency_code != '') {
             //$newprice = number_format((float)($order->getGrandTotal()*$baseCurrnecyrate),'2', '.', '');
             $newprice = number_format((double) ($grandTotal * $baseCurrnecyrate), '2', '.', '');
         } else {
             //$newprice = Mage::helper('directory')->currencyConvert($order->getGrandTotal(),Mage::app()->getStore()->getCurrentCurrencyCode(),'GBP');
             $newprice = Mage::helper('directory')->currencyConvert($order->getGrandTotal(), Mage::app()->getStore()->getCurrentCurrencyCode(), 'GBP');
         }
         $currdes = '826';
     } else {
         if ($currcode = $baseCurrency_code && $baseCurrency_code != '') {
             //$newprice = number_format((float)($order->getGrandTotal()*$baseCurrnecyrate),'2', '.', '');
             $newprice = number_format((double) ($grandTotal * $baseCurrnecyrate), '2', '.', '');
         } else {
             //$newprice = Mage::helper('directory')->currencyConvert($order->getGrandTotal(),'USD',Mage::app()->getStore()->getCurrentCurrencyCode());
             $newprice = Mage::helper('directory')->currencyConvert($grandTotal, 'USD', Mage::app()->getStore()->getCurrentCurrencyCode());
         }
         $currdes = '840';
     }
     $newprice = round($newprice, 2);
     //die;
     if ($amount === false) {
         $nAmount = $newprice * 100;
     } else {
         $nAmount = $amount * 100;
     }
     $url = $this->getConfigData('gateway_url');
     $fields = array('MerchantID' => $MerchantID, 'MerchantPassword' => $MerchantPassword, 'TransactionType' => $transcition_type, 'OrderID' => $szOrderID, 'CrossReference' => $szCrossReference, 'CurrencyCode' => $currdes, 'Amount' => $nAmount);
     $headers = array('SOAPAction:https://www.thepaymentgateway.net/CrossReferenceTransaction', 'Content-Type: text/xml; charset = utf-8', 'Connection: close');
     $xml = '<?xml version="1.0" encoding="utf-8" ?>';
     $xml .= '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">';
     $xml .= '<soap:Body>';
     $xml .= '<CrossReferenceTransaction xmlns="https://www.thepaymentgateway.net/">';
     $xml .= '<PaymentMessage>';
     $xml .= '<TransactionDetails Amount="' . $fields['Amount'] . '" CurrencyCode="' . $fields['CurrencyCode'] . '">';
     $xml .= '<MessageDetails TransactionType="' . $fields['TransactionType'] . '" CrossReference="' . $fields['CrossReference'] . '" />';
     $xml .= '<OrderID>' . $fields['OrderID'] . '</OrderID>';
     $xml .= '</TransactionDetails>';
     $xml .= '<MerchantAuthentication MerchantID="' . $fields['MerchantID'] . '" Password="******" />';
     $xml .= '</PaymentMessage>';
     $xml .= ' </CrossReferenceTransaction>';
     $xml .= '</soap:Body>';
     $xml .= '</soap:Envelope>';
     $gwId = 1;
     $domain = "paymentsensegateway.com";
     $port = "4430";
     $transattempt = 1;
     $soapSuccess = false;
     while (!$soapSuccess && $gwId <= 3 && $transattempt <= 3) {
         $url = 'https://gw' . $gwId . '.' . $domain . ':' . $port . '/';
         //$url = 'https://gw1.paymentsensegateway.com:4430/';
         //=================================================================================
         $curl = curl_init();
         curl_setopt($curl, CURLOPT_HEADER, false);
         curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
         curl_setopt($curl, CURLOPT_POST, true);
         curl_setopt($curl, CURLOPT_URL, $url);
         curl_setopt($curl, CURLOPT_POSTFIELDS, $xml);
         curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
         curl_setopt($curl, CURLOPT_ENCODING, 'UTF-8');
         curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
         $caInfoSetting = ini_get("curl.cainfo");
         if (empty($caInfoSetting)) {
             curl_setopt($curl, CURLOPT_CAINFO, Mage::getModuleDir('', 'Paymentsense') . DS . 'lib' . DS . "cacert.pem");
         }
         $ret = curl_exec($curl);
         $err = curl_errno($curl);
         $retHead = curl_getinfo($curl);
         curl_close($curl);
         $curl = null;
         if ($err == 0) {
             $StatusCode = null;
             $soapStatusCode = null;
             preg_match('/<Message>(.*)<\\/Message>/', $ret, $message);
             $message = $message[1];
             $json['error'] = $message;
             if (preg_match('#<AuthCode>([a-zA-Z0-9]+)</AuthCode>#iU', $ret, $soapAuthCode)) {
                 $AuthCode = $soapAuthCode[1];
             }
             $json['authCode'] = $AuthCode;
             if (preg_match('#<TransactionOutputData.*CrossReference="([a-zA-Z0-9]+)".*>#iU', $ret, $soapCrossReference)) {
                 $CrossReference = $soapCrossReference[1];
             }
             $json['crossReference'] = $CrossReference;
             if (preg_match('#<StatusCode>([0-9]+)</StatusCode>#iU', $ret, $soapStatusCode)) {
                 $StatusCode = (int) $soapStatusCode[1];
                 $Message = null;
                 $soapMessage = null;
                 if ($StatusCode != 50) {
                     $soapSuccess = true;
                     switch ($StatusCode) {
                         case 0:
                             $successmessage = 'AuthCode: ' . $AuthCode . " || " . 'CrossReference: ' . $CrossReference . " || " . 'AVS Check: ' . $AVSCheck . " || " . 'Postcode Check: ' . $PostCodeCheck . " || " . 'CV2 Check: ' . $CV2Check . ' || ' . '3D Secure: PASSED';
                             $json['error'] = '';
                             break;
                         case 30:
                             // Referred
                             $json['error'] = $message;
                             break;
                         default:
                             $json['error'] = $message;
                     }
                 }
             }
         }
         if ($transattempt <= 3) {
             $transattempt++;
         } else {
             $transattempt = 1;
             $gwId++;
         }
         return array('status' => $StatusCode, 'fraud' => rand(0, 1), 'message' => $json['error'], 'crossReference' => $json['crossReference'], 'paymenstatus' => $message);
     }
     //return array('status'=>$status,'transaction_id' => time() , 'fraud' => rand(0,1),'message'=>$json['error'],'data'=>$json);
 }
Example #19
0
 /**
  * Call DoAuthorize
  *
  * @param int $amount
  * @param Varien_Object $payment
  * @param string $parentTransactionId
  * @return Mage_Paypal_Model_Api_Abstract
  */
 protected function _callDoAuthorize($amount, $payment, $parentTransactionId)
 {
     $api = $this->_pro->resetApi()->getApi()->setAmount($amount)->setCurrencyCode($payment->getOrder()->getBaseCurrencyCode())->setTransactionId($parentTransactionId)->callDoAuthorization();
     $payment->setAdditionalInformation($this->_authorizationCountKey, $payment->getAdditionalInformation($this->_authorizationCountKey) + 1);
     return $api;
 }
Example #20
0
 /**
  * Refund specified amount for payment
  *
  * @param Varien_Object $payment
  * @param float $amount
  *
  * @return Mage_Payment_Model_Abstract
  */
 public function refund(Varien_Object $payment, $amount)
 {
     if (!$this->canRefund()) {
         Mage::throwException(Mage::helper('payment')->__('Refund action is not available.'));
     }
     //Prepare data in order to refund
     if ($payment->getAdditionalInformation('OrderKey')) {
         $data['OrderKey'] = $payment->getAdditionalInformation('OrderKey');
         $data['ManageOrderOperationEnum'] = 'Void';
         //Call Gateway Api
         $api = Mage::getModel('mundipagg/api');
         $refund = $api->manageOrderRequest($data, $this);
         // Xml
         $xml = $refund['result'];
         $json = json_encode($xml);
         $refund['result'] = array();
         $refund['result'] = json_decode($json, true);
         // We record transaction(s)
         if (count($refund['result']['CreditCardTransactionResultCollection']) > 0) {
             if (count($xml->CreditCardTransactionResultCollection->CreditCardTransactionResult) == 1) {
                 $trans = $refund['result']['CreditCardTransactionResultCollection']['CreditCardTransactionResult'];
                 $this->_addTransaction($payment, $trans['TransactionKey'], 'void', $trans);
             } else {
                 foreach ($refund['result']['CreditCardTransactionResultCollection']['CreditCardTransactionResult'] as $key => $trans) {
                     $this->_addTransaction($payment, $trans['TransactionKey'], 'void', $trans);
                 }
             }
         }
         if (isset($xml->CreditCardTransactionResultCollection->CreditCardTransactionResult)) {
             if (count($xml->CreditCardTransactionResultCollection->CreditCardTransactionResult) == 1) {
                 $capturedAmountInCents = $manageOrderResult->CreditCardTransactionResultCollection->CreditCardTransactionResult->CapturedAmountInCents;
             } else {
                 $capturedAmountInCents = 0;
                 foreach ($refund['result']['CreditCardTransactionResultCollection']['CreditCardTransactionResult'] as $key => $trans) {
                     $capturedAmountInCents += $trans['CapturedAmountInCents'];
                 }
             }
             $order = $payment->getOrder();
             $order->setBaseDiscountRefunded($order->getBaseDiscountInvoiced());
             $order->setBaseShippingRefunded($order->getBaseShippingAmount());
             $order->setBaseShippingTaxRefunded($order->getBaseShippingTaxInvoiced());
             $order->setBaseSubtotalRefunded($order->getBaseSubtotalInvoiced());
             $order->setBaseTaxRefunded($order->getBaseTaxInvoiced());
             $order->setBaseTotalOnlineRefunded($capturedAmountInCents * 0.01);
             $order->setDiscountRefunded($order->getDiscountInvoiced());
             $order->setShippinRefunded($order->getShippingInvoiced());
             $order->setShippinTaxRefunded($order->getShippingTaxAmount());
             $order->setSubtotalRefunded($order->getSubtotalInvoiced());
             $order->setTaxRefunded($order->getTaxInvoiced());
             $order->setTotalOnlineRefunded($capturedAmountInCents * 0.01);
             $order->setTotalRefunded($capturedAmountInCents * 0.01);
             $order->save();
             return $this;
         } else {
             $error = Mage::helper('mundipagg')->__('Unable to refund order.');
             //Log error
             Mage::log($error, null, 'Uecommerce_Mundipagg.log');
             Mage::throwException($error);
         }
     } else {
         Mage::throwException(Mage::helper('mundipagg')->__('No OrderKey found.'));
     }
 }
Example #21
0
 /**
  * Capture payment
  *
  * @param Varien_Object $payment
  * @param float $amount
  * @return Mage_Payment_Model_Abstract
  */
 public function capture(Varien_Object $payment, $amount)
 {
     $transactionId = $payment->getAdditionalInformation(Mage_XmlConnect_Model_Paypal_Mep_Checkout::PAYMENT_INFO_TRANSACTION_ID);
     $payment->setTransactionId($transactionId);
     return $this;
 }
 /**
  * Build request for getting token
  *
  * @param Mage_Sales_Model_Order_Payment $payment
  * @return Varien_Object
  */
 protected function _buildTokenRequest(Varien_Object $payment, $amount)
 {
     $orderId = null;
     $fullAmount = $payment->getAdditionalInformation('authorization_amount');
     $salesDocument = $payment->getOrder();
     if (!$salesDocument) {
         $salesDocument = $payment->getQuote();
         if (!$salesDocument->getReservedOrderId()) {
             $salesDocument->reserveOrderId();
         }
         $orderId = $salesDocument->getReservedOrderId();
     } else {
         $orderId = $salesDocument->getIncrementId();
     }
     $request = $this->_buildBasicRequest($payment);
     if (empty($salesDocument)) {
         return $request;
     }
     $request->setCreatesecuretoken('Y')->setSecuretokenid($this->_generateSecureTokenId())->setTrxtype($this->_getTrxTokenType())->setAmt($this->_formatStr('%.2F', $amount))->setCurrency($salesDocument->getBaseCurrencyCode())->setInvnum($orderId)->setCustref($orderId)->setPonum($salesDocument->getId());
     if ($fullAmount != Mage_Paypal_Model_Config::AUTHORIZATION_AMOUNT_FULL) {
         $request->setSubtotal($this->_formatStr('%.2F', $salesDocument->getBaseSubtotal()))->setTaxamt($this->_formatStr('%.2F', $salesDocument->getBaseTaxAmount()))->setFreightamt($this->_formatStr('%.2F', $salesDocument->getBaseShippingAmount()));
     }
     $billing = $salesDocument->getBillingAddress();
     if (!empty($billing)) {
         $request->setFirstname($billing->getFirstname())->setLastname($billing->getLastname())->setStreet(implode(' ', $billing->getStreet()))->setCity($billing->getCity())->setState($billing->getRegionCode())->setZip($billing->getPostcode())->setCountry($billing->getCountry())->setEmail($salesDocument->getCustomerEmail());
     }
     $shipping = $salesDocument->getShippingAddress();
     if (!empty($shipping)) {
         $this->_applyCountryWorkarounds($shipping);
         $request->setShiptofirstname($shipping->getFirstname())->setShiptolastname($shipping->getLastname())->setShiptostreet(implode(' ', $shipping->getStreet()))->setShiptocity($shipping->getCity())->setShiptostate($shipping->getRegionCode())->setShiptozip($shipping->getPostcode())->setShiptocountry($shipping->getCountry());
     }
     //pass store Id to request
     $request->setUser1($salesDocument->getStoreId())->setUser2($this->_getSecureSilentPostHash($payment));
     return $request;
 }
Example #23
0
 public function create(Varien_Object $payment, $amount, $order, $paymentMethod = null, $merchantAccount = null, $recurringType = null, $enableMoto = null)
 {
     $incrementId = $order->getIncrementId();
     $orderCurrencyCode = $order->getOrderCurrencyCode();
     // override amount because this amount uses the right currency
     $amount = $order->getGrandTotal();
     $customerId = $order->getCustomerId();
     $realOrderId = $order->getRealOrderId();
     $this->reference = $incrementId;
     $this->merchantAccount = $merchantAccount;
     $this->amount->currency = $orderCurrencyCode;
     $this->amount->value = Mage::helper('adyen')->formatAmount($amount, $orderCurrencyCode);
     //shopper data
     $customerEmail = $order->getCustomerEmail();
     $this->shopperEmail = $customerEmail;
     $this->shopperIP = $order->getRemoteIp();
     $this->shopperReference = !empty($customerId) ? $customerId : self::GUEST_ID . $realOrderId;
     // add recurring type for oneclick and recurring
     if ($recurringType) {
         /* if user uncheck the checkbox store creditcard don't set ONECLICK in the recurring contract
          * for contracttype  oneclick,recurring it means it will use recurring and if contracttype is recurring this can stay on recurring
          */
         if ($paymentMethod == "cc" && $payment->getAdditionalInformation("store_cc") == "" && $recurringType == "ONECLICK,RECURRING") {
             $this->recurring = new Adyen_Payment_Model_Adyen_Data_Recurring();
             $this->recurring->contract = "RECURRING";
         } else {
             if (!($paymentMethod == "cc" && $payment->getAdditionalInformation("store_cc") == "" && $recurringType != "RECURRING")) {
                 $this->recurring = new Adyen_Payment_Model_Adyen_Data_Recurring();
                 $this->recurring->contract = $recurringType;
             }
         }
     }
     /**
      * Browser info
      * @var unknown_type
      */
     $this->browserInfo->acceptHeader = $_SERVER['HTTP_ACCEPT'];
     $this->browserInfo->userAgent = $_SERVER['HTTP_USER_AGENT'];
     switch ($paymentMethod) {
         case "elv":
             $elv = unserialize($payment->getPoNumber());
             $this->card = null;
             $this->shopperName = null;
             $this->bankAccount = null;
             $this->elv->accountHolderName = $elv['account_owner'];
             $this->elv->bankAccountNumber = $elv['account_number'];
             $this->elv->bankLocation = $elv['bank_location'];
             $this->elv->bankLocationId = $elv['bank_location'];
             $this->elv->bankName = $elv['bank_name'];
             break;
         case "cc":
         case "oneclick":
             $this->shopperName = null;
             $this->elv = null;
             $this->bankAccount = null;
             if ($paymentMethod == "oneclick") {
                 $recurringDetailReference = $payment->getAdditionalInformation("recurring_detail_reference");
             } else {
                 $recurringDetailReference = null;
             }
             // set shopperInteraction
             if ($recurringType == "RECURRING") {
                 $this->shopperInteraction = "ContAuth";
             } else {
                 $this->shopperInteraction = "Ecommerce";
             }
             if (Mage::app()->getStore()->isAdmin() && $enableMoto != null && $enableMoto == 1) {
                 $this->shopperInteraction = "Moto";
             }
             if (Mage::getModel('adyen/adyen_cc')->isCseEnabled()) {
                 if ($recurringDetailReference && $recurringDetailReference != "") {
                     $this->selectedRecurringDetailReference = $recurringDetailReference;
                 }
                 $this->card = null;
                 $kv = new Adyen_Payment_Model_Adyen_Data_AdditionalDataKVPair();
                 $kv->key = new SoapVar("card.encrypted.json", XSD_STRING, "string", "http://www.w3.org/2001/XMLSchema");
                 $kv->value = new SoapVar($payment->getAdditionalInformation("encrypted_data"), XSD_STRING, "string", "http://www.w3.org/2001/XMLSchema");
                 $this->additionalData->entry = $kv;
             } else {
                 if ($recurringDetailReference && $recurringDetailReference != "") {
                     $this->selectedRecurringDetailReference = $recurringDetailReference;
                     if ($recurringType != "RECURRING") {
                         $this->card->cvc = $payment->getCcCid();
                     }
                     // TODO: check if expirymonth and year is changed if so add this in the card object
                     $this->card->expiryMonth = $payment->getCcExpMonth();
                     $this->card->expiryYear = $payment->getCcExpYear();
                 } else {
                     $this->card->cvc = $payment->getCcCid();
                     $this->card->expiryMonth = $payment->getCcExpMonth();
                     $this->card->expiryYear = $payment->getCcExpYear();
                     $this->card->holderName = $payment->getCcOwner();
                     $this->card->number = $payment->getCcNumber();
                 }
             }
             // installments
             if (Mage::helper('adyen/installments')->isInstallmentsEnabled() && $payment->getAdditionalInformation('number_of_installments') > 0) {
                 $this->installments = new Adyen_Payment_Model_Adyen_Data_Installments();
                 $this->installments->value = $payment->getAdditionalInformation('number_of_installments');
             }
             break;
         case "boleto":
             $boleto = unserialize($payment->getPoNumber());
             $this->card = null;
             $this->elv = null;
             $this->bankAccount = null;
             $this->socialSecurityNumber = $boleto['social_security_number'];
             $this->selectedBrand = $boleto['selected_brand'];
             $this->shopperName->firstName = $boleto['firstname'];
             $this->shopperName->lastName = $boleto['lastname'];
             $this->deliveryDate = $boleto['delivery_date'];
             break;
         case "sepa":
             $sepa = unserialize($payment->getPoNumber());
             $this->card = null;
             $this->elv = null;
             $this->shopperName = null;
             $this->bankAccount->iban = $sepa['iban'];
             $this->bankAccount->ownerName = $sepa['account_name'];
             $this->bankAccount->countryCode = $sepa['country'];
             $this->selectedBrand = "sepadirectdebit";
             break;
     }
     return $this;
 }
 /**
  * Returns method specific extra transaction information, to be logged as part of the order payment
  * 
  * @param array $transaction
  * @param Varien_Object $payment
  * @return array
  */
 protected function _getMethodSpecificExtraTransactionInformation($transaction, $payment)
 {
     $data = array();
     // 3D Secure
     $liabilityShiftStatus = '';
     if ($payment->getAdditionalInformation('threeDSecure') === true) {
         if ($payment->getAdditionalInformation('liabilityShiftPossible') == true) {
             if ($payment->getAdditionalInformation('liabilityShifted') == true) {
                 $liabilityShiftStatus = Mage::helper('braintree_payments')->__('Liability Shifted');
             } else {
                 $liabilityShiftStatus = Mage::helper('braintree_payments')->__('Failed Authentication');
             }
         } else {
             $liabilityShiftStatus = Mage::helper('braintree_payments')->__('Ineligible for 3D Secure');
         }
     } else {
         $liabilityShiftStatus = Mage::helper('braintree_payments')->__('Not applicable');
     }
     $data['liabilityShiftStatus'] = $liabilityShiftStatus;
     // Kount Risk data
     if (isset($transaction->riskData) && $transaction->riskData) {
         if ($transaction->riskData->decision) {
             $data['riskDecision'] = $transaction->riskData->decision;
         }
         if ($transaction->riskData->id) {
             $data['riskTransactionId'] = $transaction->riskData->id;
         }
     }
     return $data;
 }
 /**
  * Check if the payment needs to be corrected - payment additional information
  * would have the is_correction_required flag set to true and the cc last 4
  * for the current payment would match the last4_to_correct payment
  * additional information.
  * @param Varien_Object $payment
  * @return bool
  */
 protected function _getIsCorrectionNeededForPayment(Varien_Object $payment)
 {
     return $payment->getAdditionalInformation('is_correction_required') && $payment->getCcLast4() === $payment->getAdditionalInformation('last4_to_correct');
 }
Example #26
0
 /**
  * Internal CrossReference function for all VOID, REFUND, COLLECTION transaction types
  *
  * @param Varien_Object $payment
  * @param unknown_type $szTransactionType
  * @param unknown_type $amount
  * @return unknown
  */
 private function _runCrossReferenceTransaction(Varien_Object $payment, $szTransactionType, $amount = false)
 {
     $takePaymentInStoreBaseCurrency = $this->getConfigData('takePaymentInStoreBaseCurrency');
     $error = false;
     $boTransactionProcessed = false;
     $PaymentProcessorFullDomain;
     $rgeplRequestGatewayEntryPointList;
     $crtCrossReferenceTransaction;
     $crtrCrossReferenceTransactionResult;
     $todTransactionOutputData;
     $szMerchantID = $this->getConfigData('merchantid');
     $szPassword = $this->getConfigData('password');
     //
     $iclISOCurrencyList = CSV_ISOCurrencies::getISOCurrencyList();
     $szAmount;
     $nAmount;
     $szCurrencyShort;
     $iclISOCurrencyList;
     $power;
     $nDecimalAmount;
     $szNewCrossReference;
     $order = $payment->getOrder();
     $szOrderID = $order->getRealOrderId();
     //$szCrossReference = $payment->getLastTransId();
     $additionalInformation = $payment->getAdditionalInformation();
     $szCrossReference = $additionalInformation["CrossReference"];
     $szCrossReference = $payment->getLastTransId();
     // check the CrossRference and TransactionType parameters
     if (!$szCrossReference) {
         $error = 'Error occurred for ' . $szTransactionType . ': Missing Cross Reference';
     }
     if (!$szTransactionType) {
         $error = 'Error occurred for ' . $szTransactionType . ': Missing Transaction Type';
     }
     if ($error === false) {
         $PaymentProcessorFullDomain = $this->_getPaymentProcessorFullDomain();
         $rgeplRequestGatewayEntryPointList = new CSV_RequestGatewayEntryPointList();
         $rgeplRequestGatewayEntryPointList->add("https://gw1." . $PaymentProcessorFullDomain, 100, 2);
         $rgeplRequestGatewayEntryPointList->add("https://gw2." . $PaymentProcessorFullDomain, 200, 2);
         $rgeplRequestGatewayEntryPointList->add("https://gw3." . $PaymentProcessorFullDomain, 300, 2);
         $crtCrossReferenceTransaction = new CSV_CrossReferenceTransaction($rgeplRequestGatewayEntryPointList);
         $crtCrossReferenceTransaction->getMerchantAuthentication()->setMerchantID($szMerchantID);
         $crtCrossReferenceTransaction->getMerchantAuthentication()->setPassword($szPassword);
         if (!$takePaymentInStoreBaseCurrency) {
             $power = pow(10, $icISOCurrency->getExponent());
             $nAmount = round($order->getGrandTotal() * $power, 0);
         } else {
             $nAmount = $this->_getRoundedAmount($amount, $icISOCurrency->getExponent());
         }
         $szCurrencyShort = $order->getOrderCurrency()->getCurrencyCode();
         if ($szCurrencyShort != '' && $iclISOCurrencyList->getISOCurrency($szCurrencyShort, $icISOCurrency)) {
             $nCurrencyCode = new CSV_NullableInt($icISOCurrency->getISOCode());
             $crtCrossReferenceTransaction->getTransactionDetails()->getCurrencyCode()->setValue($icISOCurrency->getISOCode());
         }
         // round the amount before use
         //$nDecimalAmount = $this->_getRoundedAmount($nAmount, $icISOCurrency->getExponent());
         $crtCrossReferenceTransaction->getTransactionDetails()->setOrderID($szOrderID);
         $crtCrossReferenceTransaction->getTransactionDetails()->getAmount()->setValue($nAmount);
         $crtCrossReferenceTransaction->getTransactionDetails()->getMessageDetails()->setCrossReference($szCrossReference);
         $crtCrossReferenceTransaction->getTransactionDetails()->getMessageDetails()->setTransactionType($szTransactionType);
         try {
             $boTransactionProcessed = $crtCrossReferenceTransaction->processTransaction($crtrCrossReferenceTransactionResult, $todTransactionOutputData);
         } catch (Exception $exc) {
             Mage::log("exception: " . $exc->getMessage());
         }
         if ($boTransactionProcessed == false) {
             // could not communicate with the payment gateway
             $error = "Couldn't complete " . $szTransactionType . " transaction. Details: " . $crtCrossReferenceTransaction->getLastException();
             $szLogMessage = $error;
         } else {
             switch ($crtrCrossReferenceTransactionResult->getStatusCode()) {
                 case 0:
                     $error = false;
                     $szNewCrossReference = $todTransactionOutputData->getCrossReference();
                     $szLogMessage = $szTransactionType . " CrossReference transaction successfully completed. Response object: ";
                     $payment->setTransactionId($szNewCrossReference)->setParentTransactionId($szCrossReference)->setIsTransactionClosed(1);
                     $payment->save();
                     break;
                 default:
                     $szLogMessage = $crtrCrossReferenceTransactionResult->getMessage();
                     if ($crtrCrossReferenceTransactionResult->getErrorMessages()->getCount() > 0) {
                         $szLogMessage = $szLogMessage . ".";
                         for ($LoopIndex = 0; $LoopIndex < $crtrCrossReferenceTransactionResult->getErrorMessages()->getCount(); $LoopIndex++) {
                             $szLogMessage = $szLogMessage . $crtrCrossReferenceTransactionResult->getErrorMessages()->getAt($LoopIndex) . ";";
                         }
                         $szLogMessage = $szLogMessage . " ";
                     }
                     $error = "Couldn't complete " . $szTransactionType . " transaction for CrossReference: " . $szCrossReference . ". Payment Response: " . $szLogMessage;
                     $szLogMessage = $szTransactionType . " CrossReference transaction failed. Response object: ";
                     break;
             }
             $szLogMessage = $szLogMessage . print_r($crtrCrossReferenceTransactionResult, 1);
         }
         Mage::log($szLogMessage);
     }
     return $error;
 }