/** * Prepare base request * * @access public * @return object which was set with all basic required information */ protected function _buildBasicRequest(Varien_Object $payment) { if (!$payment->getTender()) { $payment->setTender(self::TENDER_CC); } $request = Mage::getModel('paygate/payflow_pro_request')->setUser($this->getConfigData('user'))->setVendor($this->getConfigData('vendor'))->setPartner($this->getConfigData('partner'))->setPwd($this->getConfigData('pwd'))->setTender($payment->getTender())->setTrxtype($payment->getTrxtype())->setVerbosity($this->getConfigData('verbosity'))->setRequestId($this->_generateRequestId())->setOrigid($payment->getCcTransId()); return $request; }
/** * Refunds specified amount * * @param Varien_Object $payment * @param decimal $amount * @return Braintree_Payments_Model_Paymentmethod */ public function refund(Varien_Object $payment, $amount) { $transactionId = Mage::helper('braintree_payments')->clearTransactionId($payment->getRefundTransactionId()); try { $transaction = Braintree_Transaction::find($transactionId); $this->_debug($payment->getCcTransId()); $this->_debug($transaction); if ($transaction->status === Braintree_Transaction::SUBMITTED_FOR_SETTLEMENT) { if ($transaction->amount != $amount) { Mage::throwException(Mage::helper('braintree_payments')->__('This refund is for a partial amount but the Transaction has not settled. ' . 'Please wait 24 hours before trying to issue a partial refund.')); } else { Mage::throwException(Mage::helper('braintree_payments')->__('The Transaction has not settled. ' . 'Please wait 24 hours before trying to issue a refund or use Void option.')); } } if ($transaction->status === Braintree_Transaction::SETTLED || $transaction->status === Braintree_Transaction::SETTLING) { $result = Braintree_Transaction::refund($transactionId, $amount); } else { $result = Braintree_Transaction::void($transactionId); } $this->_debug($result); if ($result->success) { $payment->setIsTransactionClosed(1); } else { Mage::throwException(Mage::helper('braintree_payments/error')->parseBraintreeError($result)); } } catch (Exception $e) { Mage::throwException(Mage::helper('braintree_payments')->__('There was an error refunding the transaction.') . ' ' . $e->getMessage()); } return $this; }
/** * refund the amount with transaction id * * @access public * @param string $payment Varien_Object object * @return Mage_Payment_Model_Abstract */ public function refund(Varien_Object $payment, $amount) { if ($payment->getCcTransId() && $payment->getAmount() > 0) { $api = $this->getApi(); //we can refund the amount full or partial so it is good to set up as partial refund $api->setTransactionId($payment->getCcTransId())->setRefundType(Mage_Paypal_Model_Api_Nvp::REFUND_TYPE_PARTIAL)->setAmount($amount); if ($api->callRefundTransaction() !== false) { $payment->setStatus('SUCCESS')->setCcTransId($api->getTransactionId()); } else { $e = $api->getError(); $payment->setStatus('ERROR')->setStatusDescription($e['short_message'] . ': ' . $e['long_message']); } } else { $payment->setStatus('ERROR'); $payment->setStatusDescription(Mage::helper('paypal')->__('Error in refunding the payment')); } }
/** * Capture payment abstract method * * @param Varien_Object $payment * @param float $amount * * @return Mage_Payment_Model_Abstract */ public function capture(Varien_Object $payment, $amount) { if ($payment->getCcTransId() == null || $payment->getCcTransId() == '') { //se não for a área administrativa e está sendo executado o método capture, então a ação é autorizar e capturar automaticamente $this->authorize($payment, $amount); return $this; } if (!$this->canCapture()) { Mage::throwException(Mage::helper('payment')->__('Esse pedido não pode ser capturado.')); } $tid = $payment->getCcTransId(); $valor = number_format($amount, 2, '', ''); $debug = Mage::getStoreConfig('payment/apelidocielo/debug'); if ($debug) { //Esse log só funciona se a opção Ativar log em Developer > Log no admin estiver marcada mage::log("\r\n=========== Dados do pagamento sendo enviados para captura ==========\r\n ", null, 'oitoo_cielo.log'); } $cielo = mage::getModel('apelidocielo/cielo'); $retornoCaptura = $cielo->setCaptura($tid, $valor); if ($retornoCaptura->captura->codigo == 6) { $payment->setAdditionalInformation('captura_codigo', (string) $retornoCaptura->captura->codigo); $payment->setAdditionalInformation('captura_mensagem', (string) $retornoCaptura->captura->mensagem); $payment->save(); //faz o log de sucesso Mage::dispatchEvent('oitoo_cielo_log', array('quote_id' => (string) $payment->getOrder()->getQuoteId(), 'codigo' => (string) $retornoCaptura->captura->codigo, 'texto' => (string) $retornoCaptura->captura->mensagem, 'tid' => $retornoCaptura->tid)); return $this; //a compra foi capturada. } else { if (isset($retornoCaptura->codigo)) { Mage::throwException(Mage::helper('payment')->__('Erro num: ' . $retornoCaptura->codigo . ' - ' . $retornoCaptura->mensagem)); } else { Mage::throwException(Mage::helper('payment')->__('Não foi possivel capturar a autorização pelo seguinte motivo: ' . $retornoCaptura->captura->codigo . ' - ' . $retornoCaptura->captura->mensagem)); } } return false; }
/** * @param Varien_Object|Mage_Sales_Model_Order_Payment $payment * @param $amount * @return Hps_Securesubmit_Model_Payment */ protected function _refund(Varien_Object $payment, $amount) { $transactionId = $payment->getCcTransId(); $order = $payment->getOrder(); /* @var $order Mage_Sales_Model_Order */ $chargeService = $this->_getChargeService(); $cardHolder = $this->_getCardHolderData($order); $details = $this->_getTxnDetailsData($order); try { $refundResponse = $chargeService->refundTransaction($amount, strtolower($order->getBaseCurrencyCode()), $transactionId, $cardHolder, $details); $payment->setTransactionId($refundResponse->transactionId)->setParentTransactionId($transactionId)->setIsTransactionClosed(1)->setShouldCloseParentTransaction(1); } catch (HpsException $e) { $this->_debugChargeService($chargeService, $e); $this->throwUserError($e->getMessage()); } catch (Exception $e) { $this->_debugChargeService($chargeService, $e); Mage::logException($e); $this->throwUserError($e->getMessage()); } $this->_debugChargeService($chargeService); return $this; }
/** * Capture payment * * @param Varien_Object $orderPayment * @return Mage_Payment_Model_Abstract */ public function capture(Varien_Object $payment, $amount) { if ($payment->getCcTransId()) { $api = $this->getApi()->setPaymentType(Mage_Paypal_Model_Api_Nvp::PAYMENT_TYPE_SALE)->setAmount($amount)->setBillingAddress($payment->getOrder()->getBillingAddress())->setPayment($payment); $api->setAuthorizationId($payment->getCcTransId())->setCompleteType('NotComplete'); $result = $api->callDoCapture() !== false; if ($result) { $payment->setStatus('APPROVED'); //$payment->setCcTransId($api->getTransactionId()); $payment->setLastTransId($api->getTransactionId()); } else { $e = $api->getError(); if (isset($e['short_message'])) { $message = $e['short_message']; } else { $message = AO::helper('paypal')->__("Unknown PayPal API error: %s", $e['code']); } if (isset($e['long_message'])) { $message .= ': ' . $e['long_message']; } AO::throwException($message); } } else { $this->placeOrder($payment); } return $this; }
public function void(Varien_Object $payment) { try { $result = Braintree_Transaction::void($payment->getCcTransId()); if ($result->success) { $payment->setIsTransactionClosed(1); } else { Mage::throwException($result->message); } } catch (Exception $e) { Mage::throwException(sprintf('There was an error voiding the transaction. (%s)', $e->getMessage())); } return $this; }
public function refund(Varien_Object $payment, $amount) { if ($payment->getCcTransId() && $amount > 0) { $api = $this->getApi()->setPayment($payment)->setAmount($amount); if ($api->refund() !== false) { $payment->setCcTransId($api->getTransactionId()); $payment->setStatus(self::STATUS_SUCCESS); } else { $e = $api->getError(); $payment->setStatus(self::STATUS_ERROR); $payment->setStatusDescription($e['message']); } } else { $payment->setStatus(self::STATUS_ERROR); $payment->setStatusDescription(Mage::helper('paypalUk')->__('Error in refunding the payment')); } return $this; }
/** * Process capturing of a payment * * @param Varien_Object $payment * @param float $amount * * @return Mage_Payment_Model_Abstract|void */ public function capture(Varien_Object $payment, $amount) { // Has the payment already been authorized? if ($payment->getCcTransId()) { // Convert the capture amount to the correct currency $captureAmount = $this->_getWrapper()->getCaptureAmount($payment->getOrder(), $amount); // Has the authorization already been settled? Partial invoicing if ($this->authorizationUsed($payment)) { // Set the token as false $token = false; // Was the original payment created with a token? if ($additionalInfoToken = $payment->getAdditionalInformation('token')) { try { // Init the environment $this->_getWrapper()->init($payment->getOrder()->getStoreId()); // Attempt to find the token Braintree_PaymentMethod::find($additionalInfoToken); // Set the token if a success $token = $additionalInfoToken; } catch (Exception $e) { $token = false; } } // If we managed to find a token use that for the capture if ($token) { // Stop processing the rest of the method // We pass $amount instead of $captureAmount as the authorize function contains the conversion $this->_authorize($payment, $amount, true, $token); return $this; } else { // Attempt to clone the transaction $result = $this->_getWrapper()->init($payment->getOrder()->getStoreId())->cloneTransaction($payment->getLastTransId(), $captureAmount); } } else { // Init the environment $result = $this->_getWrapper()->init($payment->getOrder()->getStoreId())->submitForSettlement($payment->getCcTransId(), $captureAmount); // Log the result Gene_Braintree_Model_Debug::log(array('capture:submitForSettlement' => $result)); } if ($result->success) { $this->_processSuccessResult($payment, $result, $amount); } else { if ($result->errors->deepSize() > 0) { // Clean up Gene_Braintree_Model_Wrapper_Braintree::cleanUp(); Mage::throwException($this->_getWrapper()->parseErrors($result->errors->deepAll())); } else { // Clean up Gene_Braintree_Model_Wrapper_Braintree::cleanUp(); Mage::throwException($result->transaction->processorSettlementResponseCode . ': ' . $result->transaction->processorSettlementResponseText); } } } else { // Otherwise we need to do an auth & capture at once $this->_authorize($payment, $amount, true); } return $this; }
protected function _refundcall(Varien_Object $payment) { if ($this->getDebug()) { $writer = new Zend_Log_Writer_Stream($this->getLogPath()); $logger = new Zend_Log($writer); $logger->info("entering _refundcall()"); } $paywayAPI = new Qvalent_PayWayAPI(); if ($this->getDebug()) { $logger->info("Qvalent_PayWayAPI created"); } $init = "certificateFile=" . $this->getCertificate() . "&" . "caFile=" . $this->getCaFile() . "&" . "logDirectory=" . $this->getLogDir(); if ($this->getDebug()) { $logger->info($init); } $paywayAPI->initialise($init); if ($this->getDebug()) { $logger->info("Qvalent_PayWayAPI initialised"); } $orderNumber = $payment->getOrder()->getStoreId() . str_pad($payment->getOrder()->getQuoteId(), 9, '0', STR_PAD_LEFT); if ($this->getDebug()) { $logger->info(print_r($payment->getOrder()->getData(), true)); } $params = array(); $params["order.type"] = "refund"; $params["customer.username"] = $this->getUsername(); $params["customer.password"] = $this->getPassword(); $params["customer.merchant"] = $this->getMerchantID(); $params["card.expiryYear"] = substr($payment->getCcExpYear(), 2, 2); $params["card.expiryMonth"] = str_pad($payment->getCcExpMonth(), 2, '0', STR_PAD_LEFT); $params["card.currency"] = $payment->getOrder()->getBaseCurrencyCode(); $params["order.amount"] = $this->getAmount() * 100; $params["order.ECI"] = "SSL"; $params["customer.orderNumber"] = $payment->getCcTransId() . "R"; $params["customer.originalOrderNumber"] = $payment->getCcTransId(); if ($this->getDebug()) { $logger->info("Params: " . print_r($params, true)); } $requestText = $paywayAPI->formatRequestParameters($params); $responseText = $paywayAPI->processCreditCard($requestText); $result = $paywayAPI->parseResponseParameters($responseText); if ($this->getDebug()) { $logger->info("Result: " . print_r($result, true)); } return $result; }
/** * Called before the request is processed * * @param string $request * @param mixed $options * @param Varien_Object $payment */ protected function _beforeProcessRequest($request, &$options, Varien_Object $payment) { switch ($request) { case 'capture': $options['origTrxNumber'] = $payment->getCcTransId() ? $payment->getCcTransId() : $payment->getLastTransId(); break; case 'refund': $options['origTrxNumber'] = $payment->getRefundTransactionId(); break; } }
/** * callApi is the major piece in the puzzle * * prepares information and call specific xml api * * @param object $payment Payment Object * @param int $amount Amount to charge * @param string $type either CIM or AIM * @param int $ccSaveId Used to determine whether or not a profile exists for the customer * @param int $tokenProfileId Checks if the payment profile already exists, if not, creates it */ public function callApi(Varien_Object $payment, $amount, $type) { /** * ===================================================================== * BEGIN AAI HACK * * Cleaned up so it would be a little easier to understand * ===================================================================== */ $order = $payment->getOrder(); $orderId = $order->getIncrementId(); $postData = Mage::app()->getRequest()->getPost('payment', array()); $ccSaveId = array_key_exists('ccsave_id', $postData) ? $postData['ccsave_id'] : null; if ($type != 'authorizeandcaptureAIM') { $customerID = $order->getCustomerId(); // for Guests, set the customerId to the Order's increment_id if (!$customerID) { $customerID = $orderId; } // order values $customerEmail = $order->getCustomerEmail(); $billingInfo = $order->getBillingAddress(); $shippingInfo = $order->getShippingAddress(); // payment values $ccType = $payment->getCcType(); $ccNumber = $payment->getCcNumber(); $ccExpDate = $payment->getCcExpYear() . '-' . str_pad($payment->getCcExpMonth(), 2, '0', STR_PAD_LEFT); $ccCCV = $payment->getCcCid(); // CIM token values $tokenProfileId = $payment->getTokenProfileId(); $tokenPaymentProfileId = $payment->getTokenPaymentProfileId(); if ($tokenProfileId == 0 && $tokenPaymentProfileId == 0 && in_array($type, array('authorize', 'capture', 'authorizeandcapture'))) { if (!is_null($ccSaveId)) { $profile = $this->getAuthnetcimCardProfileById($ccSaveId); $profileData = $profile->getData(); $tokenProfileId = $profileData['token_profile_id']; $tokenPaymentProfileId = $profileData['token_payment_profile_id']; } else { $profileCollection = $this->getAuthnetcimCardProfilesByCustomerId($customerID); if (count($profileCollection) === 0) { // Create new customer profile $responseXML = $this->createCustomerProfileRequest($customerID, $customerEmail, $billingInfo, $shippingInfo, $ccNumber, $ccExpDate, $ccCCV, $ccType); $tokenProfileId = $responseXML->customerProfileId; $tokenPaymentProfileId = $responseXML->customerPaymentProfileIdList->numericString; } else { $tokenProfileId = $profileCollection->getFirstItem()->getTokenProfileId(); $tokenPaymentProfileId = null; $ccLast4 = substr($ccNumber, -4, 4); foreach ($profileCollection as $profile) { if ($profile->getData("cc_last4") == $ccLast4) { $tokenPaymentProfileId = $profile->getData("token_payment_profile_id"); } } if (is_null($tokenPaymentProfileId)) { $tokenPaymentProfileId = $this->createCustomerPaymentProfileRequest($customerID, $tokenProfileId, $billingInfo, $ccNumber, $ccExpDate, $ccCCV, $ccType); } } } } } /** * ===================================================================== * END AAI HACK * * Cleaned up so it would be a little easier to understand * ===================================================================== */ // call xml creation functions switch ($type) { case 'authorize': $payment->setTokenProfileId($tokenProfileId); $payment->setTokenPaymentProfileId($tokenPaymentProfileId); $response = $this->createAuthorize($amount, $tokenProfileId, $tokenPaymentProfileId, $orderId, $ccCCV); break; case 'capture': $teoAuths = Mage::getModel('authorizenetcim/teoauths'); $authsCollection = $teoAuths->getCollection()->addFieldToFilter('order_id', $orderId); if (count($authsCollection) > 1) { $amountLeftToCapture = $amount; foreach ($authsCollection as $auths) { $teoAuths->load($auths->getId()); $teoAuthAmount = $teoAuths->getAuthorizationAmount(); $teoAuthAmountPaid = $teoAuths->getAmountPaid(); if ($amountLeftToCapture > 0) { $amountLeftOnAuth = $teoAuthAmount - $teoAuthAmountPaid; $authorizeTransactionId = $teoAuths->getAuthorizationNumber(); if ($amountLeftToCapture > $amountLeftOnAuth) { $response = $this->createCapture($amountLeftOnAuth, $tokenProfileId, $tokenPaymentProfileId, $authorizeTransactionId); $teoAuths->setAmountPaid($amountLeftOnAuth); $teoAuths->save(); $amountLeftToCapture = $amountLeftToCapture - $amountLeftOnAuth; } else { $response = $this->createCapture($amountLeftToCapture, $tokenProfileId, $tokenPaymentProfileId, $authorizeTransactionId); $teoAuths->setAmountPaid($amountLeftToCapture); $teoAuths->save(); $amountLeftToCapture = 0; } } } } else { //get authorize transaction id for capture $authorizeTransactionId = $payment->getCcTransId(); $response = $this->createCapture($amount, $tokenProfileId, $tokenPaymentProfileId, $authorizeTransactionId); } break; /** * ================================================================= * BEGIN AAI HACK * * ADD SPECIFIC METHOD FOR PARTIAL AUTH/CAPTURE(S) * ================================================================= */ /** * ================================================================= * BEGIN AAI HACK * * ADD SPECIFIC METHOD FOR PARTIAL AUTH/CAPTURE(S) * ================================================================= */ case 'partialcapture': $teoAuth = $this->getTeoAuthorizationByOrderId($orderId); $transId = $teoAuth->getData('authorization_number'); // Generate the XML for the API request and make a call to the API for a response $response = $this->createPartialCapture($amount, $tokenProfileId, $tokenPaymentProfileId, $transId, $order); break; /** * ================================================================= * END AAI HACK * * ADD SPECIFIC METHOD FOR PARTIAL AUTH/CAPTURE(S) * ================================================================= */ /** * ================================================================= * END AAI HACK * * ADD SPECIFIC METHOD FOR PARTIAL AUTH/CAPTURE(S) * ================================================================= */ case 'authorizeandcapture': $payment->setTokenProfileId($tokenProfileId); $payment->setTokenPaymentProfileId($tokenPaymentProfileId); $response = $this->createAuthorizeCapture($amount, $tokenProfileId, $tokenPaymentProfileId, $orderId, $ccCCV); break; case 'void': $refundTransactionId = $payment->getRefundTransactionId(); $response = $this->createVoid($tokenProfileId, $tokenPaymentProfileId, $refundTransactionId); break; case 'refund': $teoAuths = Mage::getModel('authorizenetcim/teoauths'); $authsCollection = $teoAuths->getCollection()->addFieldToFilter('order_id', $orderId); if (count($authsCollection) > 1) { $amountLeftToRefund = $amount; foreach ($authsCollection as $auths) { $teoAuths->load($auths->getId()); $teoAuthAmount = $teoAuths->getAuthorizationAmount(); $teoAuthAmountRefunded = $teoAuths->getAmountRefunded(); if ($amountLeftToRefund > 0) { $amountLeftOnAuth = $teoAuthAmount - $teoAuthAmountRefunded; $authorizeTransactionId = $teoAuths->getAuthorizationNumber(); if ($amountLeftToRefund > $amountLeftOnAuth) { $response = $this->createRefund($amountLeftOnAuth, $tokenProfileId, $tokenPaymentProfileId, $authorizeTransactionId); $teoAuths->setAmountRefunded($amountLeftOnAuth); $teoAuths->save(); $amountLeftToRefund = $amountLeftToRefund - $amountLeftOnAuth; } else { $response = $this->createRefund($amountLeftToRefund, $tokenProfileId, $tokenPaymentProfileId, $authorizeTransactionId); $teoAuths->setAmountRefunded($amountLeftToRefund); $teoAuths->save(); $amountLeftToRefund = 0; } } } } else { $refundTransactionId = $payment->getRefundTransactionId(); $response = $this->createRefund($amount, $tokenProfileId, $tokenPaymentProfileId, $refundTransactionId); } break; case 'authorizeandcaptureAIM': $response = $this->createAuthorizeCaptureAIM($amount, $payment, $order); break; case 'captureAIM': $response = $this->captureAIM($tokenProfileId); break; /** * AAI HACK * * clone of 'captureAIM' but adds an amount to be captured * instead of assuming that the full amount will be captured */ /** * AAI HACK * * clone of 'captureAIM' but adds an amount to be captured * instead of assuming that the full amount will be captured */ case 'captureWithAmountAIM': $teoAuth = $this->getTeoAuthorizationByOrderId($orderId); $transId = $teoAuth->getData('authorization_number'); $response = $this->captureWithAmountAIM($transId, $amount); break; /** * END AAI HACK */ /** * END AAI HACK */ case 'createauthorizeaim': $response = $this->createAuthorizeAim($amount, $payment, $order); break; case 'refundAIM': $response = $this->createRefundAIM($amount, $payment, $order); break; } return $response; }
/** * Preapare basic paramters for transaction * * @param Varien_Object $payment * @param decimal $amount * @return array */ protected function _prepareTxnDetails(Varien_Object $payment, $amount) { if ($payment->getCcTransId()) { $txnDetails = array('txn_type' => self::TRANSACTION_TYPE_CAPTURE, 'capture_transaction_id' => $payment->getCcTransId()); } else { $billingAddress = $payment->getOrder()->getBillingAddress(); if ($payment->getOrder()->getCustomerEmail()) { $customerEmail = $payment->getOrder()->getCustomerEmail(); } elseif ($billingAddress->getEmail()) { $customerEmail = $billingAddress->getEmail(); } else { $customerEmail = ''; } $txnDetails = array('card_holder_name' => $payment->getCcOwner(), 'card_number' => $payment->getCcNumber(), 'card_type' => $this->_convertCcType($payment->getCcType()), 'card_expiry' => sprintf('%02d', $payment->getCcExpMonth()) . substr($payment->getCcExpYear(), 2, 2), 'card_csc' => $payment->getCcCid(), 'customer_email' => $customerEmail); if ($this->getConfigData('payment_action') == self::ACTION_AUTHORIZE) { $txnDetails['txn_type'] = self::TRANSACTION_TYPE_AUTHORISE; } else { $txnDetails['txn_type'] = self::TRANSACTION_TYPE_PURCHASE; } } $accountId = $payment->getFlo2cashAccountId(); //if transaction type is authorize & capture or only authorize if (is_null($accountId)) { $accountId = $this->getAccountId(); } $txnDetails = array_merge($txnDetails, array('merchant_reference' => $payment->getOrder()->getIncrementId(), 'paynz_account_id' => $accountId, 'amount' => sprintf('%.2f', $amount))); return $txnDetails; }
/** * refund. * * Processes a partial or whole refund on an existing transaction. * * @param Varien_Object $payment * @param int/float $amount * * @return Mage_Payment_Model_Method_Cc $this. Failure will throw Mage::throwException('description') */ public function refund(Varien_Object $payment, $amount) { if ($this->getDebug()) { $writer = new Zend_Log_Writer_Stream($this->getLogPath()); $logger = new Zend_Log($writer); } $bankRespID = $payment->getCcTransId(); if (!$bankRespID) { Mage::throwException('Cannot issue a refund on this transaction: bank response id is missing.'); } //Create the transaction object $sxml = new securexml_transaction($this->getMode(NO_ANTIFRAUD), $this->getUsername(), $this->getPassword()); $transaction_id = $payment->getOrder()->getIncrementId(); if ($sxml->processRefund($amount, $transaction_id, $bankRespID)) { $transaction_id = $sxml->getResult('transaction_id'); if ($this->getDebug()) { $logger->info('Refund Approved. Response ID: ' . $transaction_id); } /* Don't reset $payment->CcTransId for refunds, so that more than one is possible. This means that the gateway response id ($transaction_id) is not stored here. If necessary, it can be recovered from the SecurePay Merchant Management Facility. http://securepay.com.au */ } else { $error = $sxml->getError(); if ($this->getDebug()) { $logger->info('Refund Declined. ' . $error); } Mage::throwException('' . $error); } return $this; }
/** * called if voiding a payment */ public function void(Varien_Object $payment) { $order = $payment->getOrder(); if (!empty($order)) { $hash = array('litleTxnId' => $payment->getCcTransId()); $merchantData = $this->merchantData($payment); $hash_in = array_merge($hash, $merchantData); $litleRequest = new LitleOnlineRequest(); $litleResponse = $litleRequest->echeckVoidRequest($hash_in); } $this->processResponse($payment, $litleResponse); }
/** * rewrited for Mage_Payment_Model_Method_Abstract */ public function cancel(Varien_Object $payment) { if (!is_null($payment->getCcTransId()) && is_null($payment->getLastTransId())) { $transactionId = $payment->getCcTransId(); $response = $this->getApi()->setStoreId($payment->getOrder()->getStoreId())->cancel($transactionId); if ($response->getStatus() == Mage_AmazonPayments_Model_Api_Asp_Fps_Response_Abstract::STATUS_ERROR) { Mage::throwException(Mage::helper('amazonpayments')->__('Order was not cancelled. Amazon Simple Pay service error: [%s] %s', $response->getCode(), $response->getMessage())); } if ($response->getStatus() == Mage_AmazonPayments_Model_Api_Asp_Fps_Response_Abstract::STATUS_CANCELLED) { $payment->getOrder()->setState(Mage_Sales_Model_Order::STATE_CANCELED, true, Mage::helper('amazonpayments')->__('Payment authorization cancelled with Amazon Simple Pay service.'), $notified = false); } } return $this; }
protected function _call(Varien_Object $payment, $callby = '', $amountcalled) { if ($this->getDebug()) { $writer = new Zend_Log_Writer_Stream($this->getLogPath()); $logger = new Zend_Log($writer); $logger->info("paymentAction: " . $this->getPaymentAction()); $storeId = $payment->getOrder()->getStoreId(); $logger->info("Storeid: " . $storeId); } //print "<pre>"; print_r($payment); print "</pre>"; exit; $ExpirationDate = $payment->getCcExpYear() . '-' . str_pad($payment->getCcExpMonth(), 2, '0', STR_PAD_LEFT); $invoiceno = $payment->getOrder()->getIncrementId(); $CustomerEmail = $payment->getOrder()->getCustomerEmail(); $CustomerId20 = $payment->getOrder()->getCustomerId(); $storeId = $payment->getOrder()->getStoreId(); $billToWho = $payment->getOrder()->getBillingAddress(); $shipToWho = $payment->getOrder()->getShippingAddress(); $tax = $payment->getOrder()->getTaxAmount(); $cvv = $payment->getCcCid(); if ($this->getStrictCVV()) { if (!$cvv) { $cvv = "111"; } } $ccnum = $payment->getCcNumber(); $ponum = $payment->getPoNumber(); if ($ccnum == '') { $ccnum = "tkn-{$ponum}"; } if ($ponum == '') { $ponum = $ccnum; } $cim = $payment->getCcSsStartMonth(); if ($this->getDebug()) { $logger->info("CcNumber PoNumber: {$ccnum}, {$ponum} SaveCimCC: {$cim}\n"); } if ($amountcalled < 1) { $amountcalled = $this->getAmount(); } $url = $this->getGatewayUrl(); if (strpos($ccnum, 'tkn') !== FALSE) { $fields = preg_split('/-/', $ccnum); $CustomerProfileID = $fields[1]; $PaymentProfileID = $fields[2]; $fields2 = preg_split('/-/', $ponum); $Approval = $fields2[2]; $fullcarddata = true; } else { $fields = preg_split('/-/', $ponum); $CustomerProfileID = $fields[0]; $fullcarddata = true; if (isset($fields[1]) and $callby != 'authorize' and strpos($ccnum, '-') !== FALSE) { $PaymentProfileID = $fields[1]; } else { $PaymentProfileID = 0; } if (isset($fields[2])) { $Approval = $fields[2]; } else { $Approval = 0; } } $authtransID = $payment->getOrder()->getTransactionId(); if ($authtransID < 1) { $authtransID = $payment->getParentTransactionId(); } if ($authtransID < 1) { $authtransID = $payment->getCcTransId(); } $authtrans2 = preg_split('/-/', $authtransID); $authtransID = $authtrans2[0]; if ($this->getDebug()) { $logger->info("from database: {$CustomerProfileID}, {$PaymentProfileID}, {$authtransID}\n"); } /* If we have the Customer ID and Payment ID, we can just do the transaction */ if ($CustomerProfileID > 0 and $PaymentProfileID > 0) { $TxRqXML = $this->createTransXML($amountcalled, $tax, $CustomerProfileID, $PaymentProfileID, $callby, $invoiceno, $authtransID, $Approval, $storeId); $TxRqResponse = $this->processRequest($url, $TxRqXML); if (isset($shipToWho['lastname']) and $shipToWho['lastname'] > '') { $createCustomerShippingAddressXML = $this->createCustomerShippingAddressXML($CustomerProfileID, $shipToWho, $storeId); $response = $this->processRequest($url, $createCustomerShippingAddressXML); if ($this->getDebug()) { $logger->info("\n\n Shipping Address Response: {$response}\n\n"); } } } else { /* First try to create a Customer Profile */ $CustProfileXML = $this->createCustomerXML($ccnum, $CustomerEmail, $ExpirationDate, $CustomerId20, $billToWho, $cvv, $storeId); $response = $this->processRequest($url, $CustProfileXML); $resultErrorCode = $this->parseXML('<code>', '</code>', $response); /* Get Customer Profile ID */ $CustomerProfileID = (int) $this->parseXML('<customerProfileId>', '</customerProfileId>', $response); /* Get Payment Profile ID */ $PaymentProfileID = (int) $this->parseXML('<customerPaymentProfileIdList><numericString>', '</numericString></customerPaymentProfileIdList>', $response); $ExistingCustProfile = $CustomerProfileID; $resultText = $this->parseXML('<text>', '</text>', $response); $resultCode = $this->parseXML('<resultCode>', '</resultCode>', $response); if ($resultErrorCode == 'E00039') { if ($this->getDebug()) { $logger->info("\n\n ALREADY HAVE A CUST PROFILE \n\n"); } $split = preg_split('/ /', $resultText); $ExistingCustProfile = $split[5]; $CustomerProfileID = $ExistingCustProfile; $addPaymentProfileXML = $this->addPaymentProfileXML($ExistingCustProfile, $ccnum, $ExpirationDate, $billToWho, $cvv, $storeId); $response = $this->processRequest($url, $addPaymentProfileXML); $PaymentProfileID = (int) $this->parseXML('<customerPaymentProfileId>', '</customerPaymentProfileId>', $response); $resultErrorCode = $this->parseXML('<code>', '</code>', $response); if ($resultErrorCode == 'E00039') { // Using an existing card already if ($this->getDebug()) { $logger->info("\n\n ALREADY HAVE A PAYMENT PROFILE WITH THE CARD \n\n"); } //Get Correct PaymentProfileID $getCustXML = $this->getProfileXML($ExistingCustProfile, $storeId); $responseGET = $this->processRequest($url, $getCustXML); $PaymentProfileID = $this->parseMultiXML($responseGET, $ccnum); if ($fullcarddata) { $updatePaymentProfileXML = $this->updatePaymentProfileXML($ExistingCustProfile, $PaymentProfileID, $ccnum, $ExpirationDate, $billToWho, $cvv, $storeId); $response = $this->processRequest($url, $updatePaymentProfileXML); if ($this->getDebug()) { $logger->info("\n\n UPDATED PROFILE {$PaymentProfileID} \n\n"); } } if ($this->getDebug()) { $logger->info("\n\ngetCustXML: {$getCustXML} ...\n...\nresponseGET{$responseGET} \n\n"); } } if ($PaymentProfileID == '0') { // Using an existing card already if ($this->getDebug()) { $logger->info("\n\n PROFILE ERROR \n\n"); } //Get Correct PaymentProfileID $getCustXML = $this->getProfileXML($ExistingCustProfile, $storeId); $responseGET = $this->processRequest($url, $getCustXML); $PaymentProfileID = $this->parseMultiXML($responseGET, $ccnum); if ($this->getDebug()) { $logger->info("\n\ngetCustXML: {$getCustXML} ...\n...\nresponseGET{$responseGET} \n\n"); } } if ($this->getDebug()) { $logger->info("\nUSING {$CustomerProfileID} - {$PaymentProfileID}"); } } if (isset($shipToWho['lastname']) and $shipToWho['lastname'] > '') { $createCustomerShippingAddressXML = $this->createCustomerShippingAddressXML($ExistingCustProfile, $shipToWho, $storeId); $response = $this->processRequest($url, $createCustomerShippingAddressXML); if ($this->getDebug()) { $logger->info("\n\n Shipping Address Response: {$response}\n\n"); } } $TxRqXML = $this->createTransXML($amountcalled, $tax, $CustomerProfileID, $PaymentProfileID, $callby, $invoiceno, $authtransID, $Approval, $storeId); $TxRqResponse = $this->processRequest($url, $TxRqXML); } $resultText = $this->parseXML('<text>', '</text>', $TxRqResponse); $resultCode = $this->parseXML('<resultCode>', '</resultCode>', $TxRqResponse); $resultErrorCode = $this->parseXML('<code>', '</code>', $TxRqResponse); $transauthidar = $this->parseXML('<directResponse>', '</directResponse>', $TxRqResponse); $fieldsAU = preg_split('/,/', $transauthidar); $responsecode = $fieldsAU[0]; if (!$responsecode == "1") { $resultCode = "No"; } if (isset($fieldsAU[4])) { $approval = $fieldsAU[4]; } else { $approval = 0; } if (strlen($approval) < 6) { $approval = $Approval; } if (isset($fieldsAU[6])) { $transno = $fieldsAU[6]; } else { $transno = 0; } if ($this->getDebug()) { $logger->info("TransID = {$transno} \n"); } if ($this->getDebug()) { $logger->info("Approval Code = {$approval} \n"); } $paymentInfo = $this->getInfoInstance(); if ($CustomerProfileID > '0' and $PaymentProfileID > '0') { $token = "{$CustomerProfileID}-{$PaymentProfileID}-{$approval}"; $paymentInfo->setCybersourceToken($token); $paymentInfo->setPoNumber($token); $paymentInfo->getOrder()->setTransactionId(); if ($paymentInfo->getCcSsStartMonth() == "on") { $paymentInfo->setCcSsStartMonth('1'); } else { if ($paymentInfo->getCcSsStartMonth() != "1") { $paymentInfo->setCcSsStartMonth('0'); } } } $result['Status']['transno'] = $transno; $result['Status']['approval'] = $approval; $result['Status']['CustomerProfileID'] = $CustomerProfileID; $result['Status']['PaymentProfileID'] = $PaymentProfileID; $result['Status']['statusCode'] = $resultCode; $result['Status']['code'] = $resultErrorCode; $result['Status']['statusDescription'] = $resultText; if ($this->getDebug()) { $logger->info("STATUS CODE = {$resultErrorCode} - {$resultCode} - {$resultText}"); } return $result; }
/** * canVoid * * @access public * @param string $payment Varien_Object object * @return Mage_Payment_Model_Abstract * @desc checking the transaction id is valid or not and transction id was not settled */ public function canVoid(Varien_Object $payment) { if ($payment->getCcTransId()) { $payment->setTrxtype(self::TRXTYPE_DELAYED_INQUIRY); $payment->setTransactionId($payment->getCcTransId()); $request = $this->_buildBasicRequest($payment); $result = $this->_postRequest($request); if ($this->getConfigData('debug')) { $payment->setCcDebugRequestBody($result->getRequestBody())->setCcDebugResponseSerialized(serialize($result)); } if ($result->getResultCode() == self::RESPONSE_CODE_APPROVED) { if ($result->getTransstate() > 1000) { $payment->setStatus(self::STATUS_ERROR); $payment->setStatusDescription(Mage::helper('paygate')->__('Voided transaction')); } elseif (in_array($result->getTransstate(), $this->_validVoidTransState)) { $payment->setStatus(self::STATUS_VOID); } } else { $payment->setStatus(self::STATUS_ERROR); $payment->setStatusDescription($result->getRespmsg() ? $result->getRespmsg() : Mage::helper('paygate')->__('Error in retrieving the transaction')); } } else { $payment->setStatus(self::STATUS_ERROR); $payment->setStatusDescription(Mage::helper('paygate')->__('Invalid transaction id')); } return $this; }
/** * Build a moneris transaction object the data of moneris * Make sure the transaction object is the appropriate type for the current * step. * * @var Varien_Object $payment * @var string $type */ public function _build(Varien_Object $payment, $type) { $order = $payment->getOrder(); $billing = $order->getBillingAddress(); $shipping = $order->getShippingAddress(); # Should be only used in the developement environment # without it we get duplicate order id. $token = $this->getConfigData('order_token'); $token = empty($token) ? "" : "-" . $token; $transaction = array('type' => $type, 'order_id' => $order->getIncrementId() . $token, 'crypt_type' => self::CRYPT_TYPE); switch ($type) { case self::TRANSACTION_PREAUTH: $transaction = $transaction + array('cust_id' => $billing->getCustomerId(), 'amount' => sprintf("%01.2f", $payment->getAmount()), 'pan' => $this->_cleanCC($payment->getCcNumber()), 'expdate' => $this->_formatExpirationDate($payment->getCcExpYear(), $payment->getCcExpMonth()), 'cvd_value' => $payment->getCcCid(), 'cvd_indicator' => 1); break; case self::TRANSACTION_COMPLETION: $transaction = $transaction + array('comp_amount' => sprintf("%01.2f", $payment->getAmount()), 'txn_number' => $payment->getCcTransId()); break; case self::TRANSACTION_VOID: $transaction = $transaction + array('comp_amount' => sprintf("%01.2f", $payment->getAmount()), 'txn_number' => $payment->getCcTransId()); break; } return new mpgTransaction($transaction); }
public function canVoid(Varien_Object $payment) { if ($payment->getCcTransId()) { $api = $this->getApi()->setTransactionId($payment->getCcTransId())->setPayment($payment); if ($api->canVoid() !== false) { $payment->setStatus(self::STATUS_VOID); } else { $e = $api->getError(); $payment->setStatus(self::STATUS_ERROR); $payment->setStatusDescription($e['message']); } } else { $payment->setStatus(self::STATUS_ERROR); $payment->setStatusDescription(Mage::helper('paypalUk')->__('Invalid transaction id')); } return $this; }
public function capture(Varien_Object $payment, $amount) { $payment->setAmount($amount); if ($payment->getCcTransId()) { $this->setTransactionId($payment->getCcTransId()); $payment->setOpcode(self::OPCODE_CONFIRM_AUTHORIZE); } else { $payment->setOpcode(self::OPCODE_CHARGING); } $request = $this->_buildRequest($payment); $result = $this->_postRequest($request); if (!$result->getError()) { $payment->setStatus(self::STATUS_APPROVED); $payment->setLastTransId($result->getTransaction()); } else { AO::throwException($result->getError()); } return $this; }
/** * Refund the payment transaction * * @param Mage_Sale_Model_Order_Payment $payment * @param flaot $amount * @return Mage_Cybersource_Model_Soap */ public function refund(Varien_Object $payment, $amount) { $error = false; if ($payment->getRefundTransactionId() && $payment->getRefundCybersourceToken() && $amount > 0) { $soapClient = $this->getSoapApi(); $this->iniRequest(); $ccCreditService = new stdClass(); $ccCreditService->run = "true"; $ccCreditService->captureRequestToken = $payment->getCybersourceToken(); $ccCreditService->captureRequestID = $payment->getCcTransId(); $this->_request->ccCreditService = $ccCreditService; $purchaseTotals = new stdClass(); $purchaseTotals->grandTotalAmount = $amount; $this->_request->purchaseTotals = $purchaseTotals; try { $result = $soapClient->runTransaction($this->_request); if ($result->reasonCode == self::RESPONSE_CODE_SUCCESS) { $payment->setLastTransId($result->requestID)->setLastCybersourceToken($result->requestToken); } else { $error = Mage::helper('cybersource')->__('There is an error in processing payment. Please try again or contact us.'); } } catch (Exception $e) { Mage::throwException(Mage::helper('cybersource')->__('Gateway request error: %s', $e->getMessage())); } } else { $error = Mage::helper('cybersource')->__('Error in refunding the payment'); } if ($error !== false) { Mage::throwException($error); } return $this; }
/** * */ protected function _callCapture(Varien_Object $payment) { if ($this->getDebug()) { $writer = new Zend_Log_Writer_Stream($this->getLogPath()); $logger = new Zend_Log($writer); $logger->info('entering _call()'); $logger->info('identificacao: ' . $this->getConfigData('codigo_gateway')); $logger->info('modulo: ' . $this->_modulo); $logger->info('ambiente: ' . $this->getConfigData('ambiente')); $logger->info('tid: ' . $payment->getCcTransId()); } // Generate any needed values $nvpArr = array('identificacao' => $this->getConfigData('codigo_gateway'), 'operacao' => 'Captura', 'modulo' => $this->_modulo, 'ambiente' => $this->getConfigData('ambiente'), 'tid' => $payment->getCcTransId()); if ($this->getDebug()) { $logger->info(var_export($payment->getOrder()->getData(), TRUE)); } $nvpReq = ''; foreach ($nvpArr as $k => $v) { $nvpReq .= '&' . $k . '=' . urlencode($v); } $nvpReq = substr($nvpReq, 1); // DEBUG if ($this->getDebug()) { $logger->info($nvpReq); } // Send the data via HTTP POST and get the response $http = new Varien_Http_Adapter_Curl(); $http->setConfig(array('timeout' => 30)); $http->write(Zend_Http_Client::POST, $this->getGatewayUrl(), '1.1', array(), $nvpReq); $response = $http->read(); if ($http->getErrno()) { $http->close(); $this->setError(array('message' => $http->getError())); return false; } // DEBUG if ($this->getDebug()) { $logger->info($response); } $http->close(); // Strip out header tags $response = preg_split('/^\\r?$/m', $response, 2); $response = trim($response[1]); // Parse the XML object $xmlObj = simplexml_load_string($response); // Build an associative array with returned values $result = array(); $xpath = $xmlObj->xpath('/ars'); $result['ars'] = $xpath !== FALSE ? $xpath[0] : ''; $xpath = $xmlObj->xpath('/tid'); $result['tid'] = $xpath !== FALSE ? $xpath[0] : ''; $xpath = $xmlObj->xpath('/lr'); $result['lr'] = $xpath !== FALSE ? $xpath[0] : ''; $xpath = $xmlObj->xpath('/cap'); $result['cap'] = $xpath !== FALSE ? $xpath[0] : ''; $xpath = $xmlObj->xpath('/free'); $result['free'] = $xpath !== FALSE ? $xpath[0] : ''; return $result; }
/** * Prepare request to gateway * * @link http://www.authorize.net/support/AIM_guide.pdf * @param Mage_Sales_Model_Document $order * @return unknown */ protected function _buildRequest(Varien_Object $payment) { $order = $payment->getOrder(); $this->setStore($order->getStoreId()); if (!$payment->getAnetTransMethod()) { $payment->setAnetTransMethod(self::REQUEST_METHOD_CC); } $request = Mage::getModel('paygate/authorizenet_request')->setXVersion(3.1)->setXDelimData('True')->setXDelimChar(self::RESPONSE_DELIM_CHAR)->setXRelayResponse('False'); if ($order && $order->getIncrementId()) { $request->setXInvoiceNum($order->getIncrementId()); } $request->setXTestRequest($this->getConfigData('test') ? 'TRUE' : 'FALSE'); $request->setXLogin($this->getConfigData('login'))->setXTranKey($this->getConfigData('trans_key'))->setXType($payment->getAnetTransType())->setXMethod($payment->getAnetTransMethod()); if ($payment->getAmount()) { $request->setXAmount($payment->getAmount(), 2); $request->setXCurrencyCode($order->getBaseCurrencyCode()); } switch ($payment->getAnetTransType()) { case self::REQUEST_TYPE_CREDIT: case self::REQUEST_TYPE_VOID: case self::REQUEST_TYPE_PRIOR_AUTH_CAPTURE: $request->setXTransId($payment->getCcTransId()); break; case self::REQUEST_TYPE_CAPTURE_ONLY: $request->setXAuthCode($payment->getCcAuthCode()); break; } 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($billing->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->getTaxAmount())->setXFreight($order->getShippingAmount()); } switch ($payment->getAnetTransMethod()) { case self::REQUEST_METHOD_CC: if ($payment->getCcNumber()) { $request->setXCardNum($payment->getCcNumber())->setXExpDate(sprintf('%02d-%04d', $payment->getCcExpMonth(), $payment->getCcExpYear()))->setXCardCode($payment->getCcCid()); } break; case self::REQUEST_METHOD_ECHECK: $request->setXBankAbaCode($payment->getEcheckRoutingNumber())->setXBankName($payment->getEcheckBankName())->setXBankAcctNum($payment->getEcheckAccountNumber())->setXBankAcctType($payment->getEcheckAccountType())->setXBankAcctName($payment->getEcheckAccountName())->setXEcheckType($payment->getEcheckType()); break; } return $request; }
protected function _call($type, Varien_Object $payment) { $cardsAPI = $this->_initialiseAPI(); $params = array(); $params["customer.username"] = $this->getUsername(); $params["customer.password"] = $this->getPassword(); $params["customer.merchant"] = $this->getMerchantID(); $params["card.expiryYear"] = substr($payment->getCcExpYear(), 2, 2); $params["card.expiryMonth"] = str_pad($payment->getCcExpMonth(), 2, '0', STR_PAD_LEFT); $params["card.currency"] = $payment->getOrder()->getBaseCurrencyCode(); $params["order.amount"] = $this->getAmount() * 100; $params["order.ECI"] = "SSL"; if ($type == self::TRANS_TYPE_CAPTURE) { $params["order.type"] = "capture"; $params["customer.orderNumber"] = $payment->getCcTransId(); $params["card.PAN"] = $payment->getCcNumber(); $params["card.CVN"] = $payment->getCcCid(); } elseif ($type == self::TRANS_TYPE_REFUND) { $params["order.type"] = "refund"; $params["customer.orderNumber"] = $payment->getCcTransId() . "R"; $params["customer.originalOrderNumber"] = $payment->getCcTransId(); } try { $result = $cardsAPI->processCreditCard($params); $orderNumber = $params['customer.orderNumber']; $this->_recordResults($payment, $result, $orderNumber); return $result; } catch (Exception $e) { $this->_log($e->getMessage()); } }