/** * @magentoDataFixture Magento/Sales/_files/order.php */ public function testRedirectActionIsContentGenerated() { $this->_order->load('100000001', 'increment_id'); $this->_order->getPayment()->setMethod(\Magento\Paypal\Model\Config::METHOD_WPS); $this->_order->save(); $this->_order->load('100000001', 'increment_id'); $this->_session->setLastRealOrderId($this->_order->getRealOrderId())->setLastQuoteId($this->_order->getQuoteId()); $this->dispatch('paypal/standard/redirect'); $this->assertContains('<form action="https://www.paypal.com/cgi-bin/webscr" id="paypal_standard_checkout"' . ' name="paypal_standard_checkout" method="POST">', $this->getResponse()->getBody()); }
/** * @param $formFields * @return mixed */ protected function setOpenInvoiceData($formFields) { $count = 0; $currency = $this->_order->getOrderCurrencyCode(); foreach ($this->_order->getAllVisibleItems() as $item) { ++$count; $linename = "line" . $count; $formFields['openinvoicedata.' . $linename . '.currencyCode'] = $currency; $formFields['openinvoicedata.' . $linename . '.description'] = str_replace("\n", '', trim($item->getName())); $formFields['openinvoicedata.' . $linename . '.itemAmount'] = $this->_adyenHelper->formatAmount($item->getPrice(), $currency); $formFields['openinvoicedata.' . $linename . '.itemVatAmount'] = $item->getTaxAmount() > 0 && $item->getPriceInclTax() > 0 ? $this->_adyenHelper->formatAmount($item->getPriceInclTax(), $currency) - $this->_adyenHelper->formatAmount($item->getPrice(), $currency) : $this->_adyenHelper->formatAmount($item->getTaxAmount(), $currency); // $product = $item->getProduct(); // Calculate vat percentage $percentageMinorUnits = $this->_adyenHelper->getMinorUnitTaxPercent($item->getTaxPercent()); $formFields['openinvoicedata.' . $linename . '.itemVatPercentage'] = $percentageMinorUnits; $formFields['openinvoicedata.' . $linename . '.numberOfItems'] = (int) $item->getQtyOrdered(); if ($this->_order->getPayment()->getAdditionalInformation(\Adyen\Payment\Observer\AdyenHppDataAssignObserver::BRAND_CODE) == "klarna") { $formFields['openinvoicedata.' . $linename . '.vatCategory'] = "High"; } else { $formFields['openinvoicedata.' . $linename . '.vatCategory'] = "None"; } } $formFields['openinvoicedata.refundDescription'] = "Refund / Correction for " . $formFields['merchantReference']; $formFields['openinvoicedata.numberOfLines'] = $count; return $formFields; }
/** * Saves new order transaction incrementing "try". * * @param \Magento\Sales\Model\Order $order * @param string $payuplOrderId * @param string $payuplExternalOrderId * @param string $status */ public function addNewOrderTransaction(\Magento\Sales\Model\Order $order, $payuplOrderId, $payuplExternalOrderId, $status) { $orderId = $order->getId(); $payment = $order->getPayment(); $payment->setTransactionId($payuplOrderId); $payment->setTransactionAdditionalInfo(\Magento\Sales\Model\Order\Payment\Transaction::RAW_DETAILS, ['order_id' => $payuplExternalOrderId, 'try' => $this->transactionResource->getLastTryByOrderId($orderId) + 1, 'status' => $status]); $payment->setIsTransactionClosed(0); $transaction = $payment->addTransaction('order'); $transaction->save(); $payment->save(); }
/** * Map payment information from IPN to payment object * Returns true if there were changes in information * * @return bool * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ protected function _importPaymentInformation() { $payment = $this->_order->getPayment(); $was = $payment->getAdditionalInformation(); // collect basic information $from = []; foreach ([Info::PAYER_ID, 'payer_email' => Info::PAYER_EMAIL, Info::PAYER_STATUS, Info::ADDRESS_STATUS, Info::PROTECTION_EL, Info::PAYMENT_STATUS, Info::PENDING_REASON] as $privateKey => $publicKey) { if (is_int($privateKey)) { $privateKey = $publicKey; } $value = $this->getRequestData($privateKey); if ($value) { $from[$publicKey] = $value; } } if (isset($from['payment_status'])) { $from['payment_status'] = $this->_filterPaymentStatus($this->getRequestData('payment_status')); } // collect fraud filters $fraudFilters = []; for ($i = 1; $value = $this->getRequestData("fraud_management_pending_filters_{$i}"); $i++) { $fraudFilters[] = $value; } if ($fraudFilters) { $from[Info::FRAUD_FILTERS] = $fraudFilters; } $this->_paypalInfo->importToPayment($from, $payment); /** * Detect pending payment, frauds * TODO: implement logic in one place * @see \Magento\Paypal\Model\Pro::importPaymentInfo() */ if ($this->_paypalInfo->isPaymentReviewRequired($payment)) { $payment->setIsTransactionPending(true); if ($fraudFilters) { $payment->setIsFraudDetected(true); } } if ($this->_paypalInfo->isPaymentSuccessful($payment)) { $payment->setIsTransactionApproved(true); } elseif ($this->_paypalInfo->isPaymentFailed($payment)) { $payment->setIsTransactionDenied(true); } return $was != $payment->getAdditionalInformation(); }
/** * Set entity data to request * * @param \Magento\Sales\Model\Order $order * @param \Magento\Authorizenet\Model\Directpost $paymentMethod * @return $this */ public function setDataFromOrder(\Magento\Sales\Model\Order $order, \Magento\Authorizenet\Model\Directpost $paymentMethod) { $payment = $order->getPayment(); $this->setXType($payment->getAnetTransType()); $this->setXFpSequence($order->getQuoteId()); $this->setXInvoiceNum($order->getIncrementId()); $this->setXAmount($payment->getBaseAmountAuthorized()); $this->setXCurrencyCode($order->getBaseCurrencyCode()); $this->setXTax(sprintf('%.2F', $order->getBaseTaxAmount()))->setXFreight(sprintf('%.2F', $order->getBaseShippingAmount())); //need to use strval() because NULL values IE6-8 decodes as "null" in JSON in JavaScript, //but we need "" for null values. $billing = $order->getBillingAddress(); if (!empty($billing)) { $this->setXFirstName(strval($billing->getFirstname()))->setXLastName(strval($billing->getLastname()))->setXCompany(strval($billing->getCompany()))->setXAddress(strval($billing->getStreetLine(1)))->setXCity(strval($billing->getCity()))->setXState(strval($billing->getRegion()))->setXZip(strval($billing->getPostcode()))->setXCountry(strval($billing->getCountry()))->setXPhone(strval($billing->getTelephone()))->setXFax(strval($billing->getFax()))->setXCustId(strval($billing->getCustomerId()))->setXCustomerIp(strval($order->getRemoteIp()))->setXCustomerTaxId(strval($billing->getTaxId()))->setXEmail(strval($order->getCustomerEmail()))->setXEmailCustomer(strval($paymentMethod->getConfigData('email_customer')))->setXMerchantEmail(strval($paymentMethod->getConfigData('merchant_email'))); } $shipping = $order->getShippingAddress(); if (!empty($shipping)) { $this->setXShipToFirstName(strval($shipping->getFirstname()))->setXShipToLastName(strval($shipping->getLastname()))->setXShipToCompany(strval($shipping->getCompany()))->setXShipToAddress(strval($shipping->getStreetLine(1)))->setXShipToCity(strval($shipping->getCity()))->setXShipToState(strval($shipping->getRegion()))->setXShipToZip(strval($shipping->getPostcode()))->setXShipToCountry(strval($shipping->getCountry())); } $this->setXPoNum(strval($payment->getPoNumber())); return $this; }
/** * */ protected function _createShipment() { $this->_debugData['_createShipment'] = 'Creating shipment for order'; // create shipment for cash payment $payment = $this->_order->getPayment()->getMethodInstance(); if ($this->_order->canShip()) { $itemQty = array(); $shipment = $this->_order->prepareShipment($itemQty); if ($shipment) { $shipment->register(); $shipment->getOrder()->setIsInProcess(true); $comment = __('Shipment created by Adyen'); $shipment->addComment($comment); /** @var \Magento\Framework\DB\Transaction $transaction */ $transaction = $this->_transactionFactory->create(); $transaction->addObject($shipment)->addObject($shipment->getOrder())->save(); $this->_debugData['_createShipment done'] = 'Order is shipped'; } } else { $this->_debugData['_createShipment error'] = 'Order can\'t be shipped'; } }
/** * Create shipment * * @throws bool */ protected function _createShipment() { $this->_adyenLogger->addAdyenNotificationCronjob('Creating shipment for order'); // create shipment for cash payment $payment = $this->_order->getPayment()->getMethodInstance(); if ($this->_order->canShip()) { $itemQty = []; $shipment = $this->_order->prepareShipment($itemQty); if ($shipment) { $shipment->register(); $shipment->getOrder()->setIsInProcess(true); $comment = __('Shipment created by Adyen'); $shipment->addComment($comment); /** @var \Magento\Framework\DB\Transaction $transaction */ $transaction = $this->_transactionFactory->create(); $transaction->addObject($shipment)->addObject($shipment->getOrder())->save(); $this->_adyenLogger->addAdyenNotificationCronjob('Order is shipped'); } } else { $this->_adyenLogger->addAdyenNotificationCronjob('Order can\'t be shipped'); } }
protected function _createInvoice($params) { try { if ($this->_order->canInvoice()) { $payment = $this->_order->getPayment(); $payment->setTransactionId($params['invoice_id']); $payment->setCurrencyCode($params['list_currency']); $payment->setParentTransactionId($params['sale_id']); $payment->setShouldCloseParentTransaction(true); $payment->setIsTransactionClosed(0); $payment->registerCaptureNotification($params['invoice_list_amount'], true); $this->_order->save(); // notify customer $invoice = $payment->getCreatedInvoice(); if ($invoice && !$this->_order->getEmailSent()) { $this->orderSender->send($this->_order); $this->_order->addStatusHistoryComment(__('You notified customer about invoice #%1.', $invoice->getIncrementId()))->setIsCustomerNotified(true)->save(); } } } catch (Exception $e) { throw new Exception(sprintf('Error Creating Invoice: "%s"', $e->getMessage())); } }
protected function _processOrder(\Magento\Sales\Model\Order $order, $response) { //$response = $this->getResponse(); $payment = $order->getPayment(); //$payment->setTransactionId($response->getPnref())->setIsTransactionClosed(0); //TODO: add validation for request data try { $errors = array(); //$this->readConfig(); //$order = Mage::getModel("sales/order")->load($this->getOrderId($answer)); //$order = Mage::getModel("sales/order")->loadByIncrementId($this->getOrderId($answer)); $hashArray = array($response["OutSum"], $response["InvId"], $this->getConfigData('pass_word_2')); $hashCurrent = strtoupper(md5(implode(":", $hashArray))); $correctHash = strcmp($hashCurrent, strtoupper($response['SignatureValue'])) == 0; if (!$correctHash) { $errors[] = "Incorrect HASH (need:" . $hashCurrent . ", got:" . strtoupper($response['SignatureValue']) . ") - fraud data or wrong secret Key"; $errors[] = "Maybe success payment"; } /** * @var $order Mage_Sales_Model_Order */ // if ($this->_transferCurrency != $order->getOrderCurrencyCode()) { // $outSum = round( // $order->getBaseCurrency()->convert($order->getBaseGrandTotal(), $this->_transferCurrency), // 2 // ); // } else { $outSum = round($order->getGrandTotal(), 2); // } if ($outSum != $response["OutSum"]) { $errors[] = "Incorrect Amount: " . $response["OutSum"] . " (need: " . $outSum . ")"; } // if (count($errors) > 0) { // return $errors; // } //return (bool)$correctHash; //$payment->registerCaptureNotification($payment->getBaseAmountAuthorized()); if (!$correctHash) { $payment->setTransactionId($response["InvId"])->setIsTransactionClosed(0); $order->setStatus(Order::STATE_PAYMENT_REVIEW); $order->save(); return "Ok" . $response["InvId"]; } // } catch (Exception $e) { return array("Internal error:" . $e->getMessage()); } }
/** * @param $order Order * @return Card|null */ protected function makeCardInfo(Order $order) { $payment = $order->getPayment(); $this->_logger->debug($payment->convertToJson()); if (!is_subclass_of($payment->getMethodInstance(), '\\Magento\\Payment\\Model\\Method\\Cc')) { return null; } $card = SignifydModel::Make("\\Signifyd\\Models\\Card"); $card->cardHolderName = $payment->getCcOwner(); $card->last4 = $payment->getCcLast4(); $card->expiryMonth = $payment->getCcExpMonth(); $card->expiryYear = $payment->getCcExpYear(); $card->hash = $payment->getCcNumberEnc(); $ccNum = $payment->getData('cc_number'); if ($ccNum && is_numeric($ccNum) && strlen((string) $ccNum) > 6) { $card->bin = substr((string) $ccNum, 0, 6); } $card->billingAddress = $this->formatSignifydAddress($order->getBillingAddress()); return $card; }
/** * Loads the order info from a Magento order model. * * @param Order $order the order model. * @return \NostoOrder */ public function build(Order $order) { $nostoOrder = new \NostoOrder(); try { $nostoCurrency = new NostoCurrencyCode($order->getOrderCurrencyCode()); $nostoOrder->setOrderNumber($order->getId()); $nostoOrder->setExternalRef($order->getRealOrderId()); $nostoOrder->setCreatedDate(new NostoDate(strtotime($order->getCreatedAt()))); $nostoOrder->setPaymentProvider(new NostoOrderPaymentProvider($order->getPayment()->getMethod())); if ($order->getStatus()) { $nostoStatus = new NostoOrderStatus(); $nostoStatus->setCode($order->getStatus()); $nostoStatus->setLabel($order->getStatusLabel()); $nostoOrder->setStatus($nostoStatus); } foreach ($order->getAllStatusHistory() as $item) { if ($item->getStatus()) { $nostoStatus = new NostoOrderStatus(); $nostoStatus->setCode($item->getStatus()); $nostoStatus->setLabel($item->getStatusLabel()); $nostoStatus->setCreatedAt(new NostoDate(strtotime($item->getCreatedAt()))); $nostoOrder->addHistoryStatus($nostoStatus); } } // Set the buyer information $nostoBuyer = new NostoOrderBuyer(); $nostoBuyer->setFirstName($order->getCustomerFirstname()); $nostoBuyer->setLastName($order->getCustomerLastname()); $nostoBuyer->setEmail($order->getCustomerEmail()); $nostoOrder->setBuyer($nostoBuyer); // Add each ordered item as a line item /** @var Item $item */ foreach ($order->getAllVisibleItems() as $item) { $nostoItem = new NostoOrderItem(); $nostoItem->setItemId((int) $this->buildItemProductId($item)); $nostoItem->setQuantity((int) $item->getQtyOrdered()); $nostoItem->setName($this->buildItemName($item)); try { $nostoItem->setUnitPrice(new NostoPrice($this->_priceHelper->getItemFinalPriceInclTax($item))); } catch (\NostoInvalidArgumentException $E) { $nostoItem->setUnitPrice(new NostoPrice(0)); } $nostoItem->setCurrency($nostoCurrency); $nostoOrder->addItem($nostoItem); } // Add discounts as a pseudo line item if (($discount = $order->getDiscountAmount()) < 0) { $nostoItem = new NostoOrderItem(); $nostoItem->setItemId(-1); $nostoItem->setQuantity(1); $nostoItem->setName($this->buildDiscountRuleDescription($order)); $nostoItem->setUnitPrice(new NostoPrice($discount)); $nostoItem->setCurrency($nostoCurrency); $nostoOrder->addItem($nostoItem); } // Add shipping and handling as a pseudo line item if (($shippingInclTax = $order->getShippingInclTax()) > 0) { $nostoItem = new NostoOrderItem(); $nostoItem->setItemId(-1); $nostoItem->setQuantity(1); $nostoItem->setName('Shipping and handling'); $nostoItem->setUnitPrice(new NostoPrice($shippingInclTax)); $nostoItem->setCurrency($nostoCurrency); $nostoOrder->addItem($nostoItem); } } catch (Exception $e) { $this->_logger->error($e, ['exception' => $e]); } return $nostoOrder; }
protected function _checkIpnRequest() { $request = $this->getRequest()->getPost(); $this->_order = $this->_getOrder($request['ordernumber']); // check order ID $orderId = $this->_order->getRealOrderId(); if ($orderId != $request['ordernumber']) { throw new \Magento\Framework\Exception\LocalizedException(__('Order not found')); } $this->_paymentInst = $this->_order->getPayment()->getMethodInstance(); // check merchant ID if ($this->_paymentInst->getConfigData('merchant') != $request['merchant_id']) { throw new \Magento\Framework\Exception\LocalizedException(__('Invalid merchant ID: ' . $request['merchant_id'])); } // failed operation if ('AS000' != $request['responsecode']) { throw new \Magento\Framework\Exception\LocalizedException($this->_paymentInst->getAssistErrors($request['responsecode'])); } // wrong test mode if ($this->_paymentInst->getConfigData('mode') != $request['testmode']) { throw new \Magento\Framework\Exception\LocalizedException(__('Wrong Test Mode.')); } // accept only Approve operations, cancel and capture are processed real time if ('100' != $request['operationtype']) { throw new \Magento\Framework\Exception\LocalizedException(__('Wrong Operation Type. Only Approve is supported by IPN.')); } // check currency if ($this->_order->getBaseCurrencyCode() != $request['ordercurrency']) { throw new \Magento\Framework\Exception\LocalizedException(__('Invalid currency: ' . $request['ordercurrency'])); } // check amount $orderAmount = number_format($this->_order->getGrandTotal(), 2, '.', ''); if ($orderAmount != $request['orderamount']) { throw new \Magento\Framework\Exception\LocalizedException(__('Invalid amount: ' . $request['orderamount'])); } /* if (Mage::helper('assist')->isResponseSecuredMd5()) { $x = array( $this->_paymentInst->getConfigData('merchant'), $request['ordernumber'], $request['amount'], $request['currency'], $request['orderstate'] ); if ($this->_paymentInst->secreyKey(implode("", $x)) != $request['checkvalue']) { Mage::throwException('Incorrect Checkvalue: ' . $request['checkvalue']); } } if (Mage::helper('assist')->isResponseSecuredPgp()) { $y = implode("", array( $this->_paymentInst->getConfigData('merchant'), $request['ordernumber'], $request['amount'], $request['currency'], $request['orderstate'] )); $keyFile = Mage::getBaseDir('var') . DS . 'assist' . DS . $this->_paymentInst->getConfigData('assist_key'); if ($this->_paymentInst->sign($y, $keyFile) != $request['signature']) { Mage::throwException('Incorrect Signature.'); } } */ return $request; }
/** * Check requested payment method * * @param Order $order * @return bool */ protected function checkPaymentMethod(Order $order) { $payment = $order->getPayment(); return in_array($payment->getMethod(), $this->allowedPaymentMethodCodes); }
/** * Operate with order using information from silent post * * @param \Magento\Sales\Model\Order $order * @return void * @throws \Magento\Framework\Exception\LocalizedException * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ protected function _processOrder(\Magento\Sales\Model\Order $order) { $response = $this->getResponse(); $payment = $order->getPayment(); $payment->setTransactionId($response->getPnref())->setIsTransactionClosed(0); $canSendNewOrderEmail = true; if ($response->getResult() == self::RESPONSE_CODE_FRAUDSERVICE_FILTER || $response->getResult() == self::RESPONSE_CODE_DECLINED_BY_FILTER) { $canSendNewOrderEmail = false; $payment->setIsTransactionPending(true)->setIsFraudDetected(true); $fraudMessage = $response->getData('respmsg'); if ($response->getData('fps_prexmldata')) { $xml = new \SimpleXMLElement($response->getData('fps_prexmldata')); $fraudMessage = (string) $xml->rule->triggeredMessage; } $payment->setAdditionalInformation(Info::PAYPAL_FRAUD_FILTERS, $fraudMessage); } if ($response->getData('avsdata') && strstr(substr($response->getData('avsdata'), 0, 2), 'N')) { $payment->setAdditionalInformation(Info::PAYPAL_AVS_CODE, substr($response->getData('avsdata'), 0, 2)); } if ($response->getData('cvv2match') && $response->getData('cvv2match') != 'Y') { $payment->setAdditionalInformation(Info::PAYPAL_CVV_2_MATCH, $response->getData('cvv2match')); } switch ($response->getType()) { case self::TRXTYPE_AUTH_ONLY: $payment->registerAuthorizationNotification($payment->getBaseAmountAuthorized()); break; case self::TRXTYPE_SALE: $payment->registerCaptureNotification($payment->getBaseAmountAuthorized()); break; default: break; } $order->save(); try { if ($canSendNewOrderEmail) { $this->orderSender->send($order); } $quote = $this->quoteRepository->get($order->getQuoteId())->setIsActive(false); $this->quoteRepository->save($quote); } catch (\Exception $e) { throw new \Magento\Framework\Exception\LocalizedException(__('We cannot send the new order email.')); } }
/** * Operate with order using information from silent post * * @param \Magento\Sales\Model\Order $order * @return void * @throws \Magento\Framework\Model\Exception */ protected function _processOrder(\Magento\Sales\Model\Order $order) { $response = $this->getResponse(); $payment = $order->getPayment(); $payment->setTransactionId($response->getPnref())->setIsTransactionClosed(0); $canSendNewOrderEmail = true; if ($response->getResult() == self::RESPONSE_CODE_FRAUDSERVICE_FILTER || $response->getResult() == self::RESPONSE_CODE_DECLINED_BY_FILTER) { $canSendNewOrderEmail = false; $fraudMessage = $this->_getFraudMessage() ? $response->getFraudMessage() : $response->getRespmsg(); $payment->setIsTransactionPending(true)->setIsFraudDetected(true)->setAdditionalInformation('paypal_fraud_filters', $fraudMessage); } if ($response->getAvsdata() && strstr(substr($response->getAvsdata(), 0, 2), 'N')) { $payment->setAdditionalInformation('paypal_avs_code', substr($response->getAvsdata(), 0, 2)); } if ($response->getCvv2match() && $response->getCvv2match() != 'Y') { $payment->setAdditionalInformation('paypal_cvv2_match', $response->getCvv2match()); } switch ($response->getType()) { case self::TRXTYPE_AUTH_ONLY: $payment->registerAuthorizationNotification($payment->getBaseAmountAuthorized()); break; case self::TRXTYPE_SALE: $payment->registerCaptureNotification($payment->getBaseAmountAuthorized()); break; default: break; } $order->save(); try { if ($canSendNewOrderEmail) { $this->orderSender->send($order); } $this->_quoteFactory->create()->load($order->getQuoteId())->setIsActive(false)->save(); } catch (\Exception $e) { throw new \Magento\Framework\Model\Exception(__('We cannot send the new order email.')); } }
/** * @param \Magento\Sales\Model\Order $order * @return bool */ public function validatePaymentMethod(\Magento\Sales\Model\Order $order) { return $order->getPayment()->getMethod() === \Orba\Payupl\Model\Payupl::CODE; }
/** * @param $order Order * @return array */ private function makeCardInfo(Order $order) { $payment = $order->getPayment(); $this->_logger->info($payment->convertToJson()); if (!is_subclass_of($payment->getMethodInstance(), '\\Magento\\Payment\\Model\\Method\\Cc')) { return array(); } return array("cardHolderName" => $payment->getCcOwner(), "last4" => $payment->getCcLast4(), "expiryMonth" => $payment->getCcExpMonth(), "expiryYear" => $payment->getCcExpYear(), "hash" => $payment->getCcNumberEnc(), "bin" => substr((string) $payment->getData('cc_number'), 0, 6), "billingAddress" => $this->formatSignifydAddress($order->getBillingAddress())); }
/** * @param Order $order */ public function validateCoinGateCallback(Order $order) { try { if (!$order || !$order->getIncrementId()) { $request_order_id = filter_input(INPUT_POST, 'order_id') ? filter_input(INPUT_POST, 'order_id') : filter_input(INPUT_GET, 'order_id'); throw new \Exception('Order #' . $request_order_id . ' does not exists'); } $payment = $order->getPayment(); $get_token = filter_input(INPUT_GET, 'token'); $token1 = $get_token ? $get_token : ''; $token2 = $payment->getAdditionalInformation('coingate_order_token'); if ($token2 == '' || $token1 != $token2) { throw new \Exception('Tokens do match.'); } $request_id = filter_input(INPUT_POST, 'id') ? filter_input(INPUT_POST, 'id') : filter_input(INPUT_GET, 'id'); $this->coingate->getOrder($request_id); if (!$this->coingate->success) { throw new \Exception('CoinGate Order #' . $request_id . ' does not exist'); } if (!is_array($this->coingate->response)) { throw new \Exception('Something wrong with callback'); } if ($this->coingate->response['status'] == 'paid') { $order->setState(Order::STATE_PROCESSING, TRUE)->setStatus($order->getConfig()->getStateDefaultStatus(Order::STATE_PROCESSING))->save(); } elseif (in_array($this->coingate->response['status'], array('invalid', 'expired', 'canceled'))) { $order->setState(Order::STATE_CANCELED, TRUE)->setStatus($order->getConfig()->getStateDefaultStatus(Order::STATE_CANCELED))->save(); } } catch (\Exception $e) { exit('Error occurred: ' . $e); } }
/** * Capture order's payment using AIM. * * @param \Magento\Sales\Model\Order $order * @return void */ protected function _captureOrder(\Magento\Sales\Model\Order $order) { $payment = $order->getPayment(); if ($payment->getAdditionalInformation('payment_type') == self::ACTION_AUTHORIZE_CAPTURE) { try { $payment->setTransactionId(null)->setParentTransactionId($this->getResponse()->getXTransId())->capture(null); // set status from config for AUTH_AND_CAPTURE orders. if ($order->getState() == \Magento\Sales\Model\Order::STATE_PROCESSING) { $orderStatus = $this->getConfigData('order_status'); if (!$orderStatus || $order->getIsVirtual()) { $orderStatus = $order->getConfig()->getStateDefaultStatus(\Magento\Sales\Model\Order::STATE_PROCESSING); } if ($orderStatus) { $order->setStatus($orderStatus); } } $order->save(); } catch (\Exception $e) { //if we couldn't capture order, just leave it as NEW order. $this->_logger->logException($e); } } }
/** * Get order amount data with included tax * @param \Magento\Sales\Model\Order $order * @return array */ private function getTaxableAmount(Order $order) { $amount = $this->_formatPrice($order->getPayment()->getBaseAmountAuthorized()); return ['amount' => $amount, 'subtotal' => $amount]; }
/** * @param Order $order */ public function validateKhipuCallback(Order $order) { try { if (!$order || !$order->getIncrementId()) { throw new \Exception('Order #' . $_REQUEST['order_id'] . ' does not exists'); } $payment = $order->getPayment(); $notificationToken = isset($_POST['notification_token']) ? $_POST['notification_token'] : ''; if ($notificationToken == '') { throw new \Exception('Invalid notification token.'); } $configuration = new \Khipu\Configuration(); $configuration->setSecret($this->getConfigData('merchant_secret')); $configuration->setReceiverId($this->getConfigData('merchant_id')); $configuration->setPlatform('magento2-khipu', Payment::KHIPU_MAGENTO_VERSION); $client = new \Khipu\ApiClient($configuration); $payments = new \Khipu\Client\PaymentsApi($client); try { $paymentResponse = $payments->paymentsGet($notificationToken); } catch (\Khipu\ApiException $exception) { throw new \Exception(print_r($exception->getResponseObject(), TRUE)); } if ($paymentResponse->getReceiverId() != $this->getConfigData('merchant_id')) { throw new \Exception('Invalid receiver id'); } if ($paymentResponse->getTransactionId() != $payment->getAdditionalInformation('khipu_order_token')) { throw new \Exception('Invalid transaction id'); } if ($paymentResponse->getStatus() != 'done') { throw new \Exception('Payment not done'); } if ($paymentResponse->getAmount() != number_format($order->getGrandTotal(), $this->getDecimalPlaces($order->getOrderCurrencyCode()), '.', '')) { throw new \Exception('Amount mismatch'); } if ($paymentResponse->getCurrency() != $order->getOrderCurrencyCode()) { throw new \Exception('Currency mismatch'); } $order->setState(Order::STATE_PROCESSING, TRUE)->setStatus($order->getConfig()->getStateDefaultStatus(Order::STATE_PROCESSING))->save(); } catch (\Exception $e) { exit('Error occurred: ' . $e); } }
/** * Check order payment method * * @param \Magento\Sales\Model\Order $order * @return bool */ protected function _isOrderValid($order) { return \Magento\Ogone\Model\Api::PAYMENT_CODE == $order->getPayment()->getMethodInstance()->getCode(); }
/** * Register order cancellation. Return money to customer if needed. * * @param \Magento\Sales\Model\Order $order * @param string $message * @param bool $voidPayment * @return void */ protected function declineOrder(\Magento\Sales\Model\Order $order, $message = '', $voidPayment = true) { try { $response = $this->getResponse(); if ($voidPayment && $response->getXTransId() && strtoupper($response->getXType()) == self::REQUEST_TYPE_AUTH_ONLY) { $order->getPayment()->setTransactionId(null)->setParentTransactionId($response->getXTransId())->void(); } $order->registerCancellation($message)->save(); } catch (\Exception $e) { //quiet decline $this->logger->critical($e); } }
/** * Get payment info block as html * * @param Order $order * @return string */ protected function getPaymentHtml(Order $order) { return $this->paymentHelper->getInfoBlockHtml($order->getPayment(), $this->identityContainer->getStore()->getStoreId()); }
public function startTransaction(Order $order, UrlInterface $url) { $config = new Config($this->_scopeConfig); $config->configureSDK(); $additionalData = $order->getPayment()->getAdditionalInformation(); $bankId = null; if (isset($additionalData['bank_id'])) { $bankId = $additionalData['bank_id']; } $total = $order->getGrandTotal(); $items = $order->getAllVisibleItems(); $orderId = $order->getIncrementId(); $quoteId = $order->getQuoteId(); $currency = $order->getOrderCurrencyCode(); $returnUrl = $url->getUrl('paynl/checkout/finish/'); $exchangeUrl = $url->getUrl('paynl/checkout/exchange/'); $paymentOptionId = $this->getPaymentOptionId(); $arrBillingAddress = $order->getBillingAddress(); if ($arrBillingAddress) { $arrBillingAddress = $arrBillingAddress->toArray(); $enduser = array('initials' => substr($arrBillingAddress['firstname'], 0, 1), 'lastName' => $arrBillingAddress['lastname'], 'phoneNumber' => $arrBillingAddress['telephone'], 'emailAddress' => $arrBillingAddress['email']); $invoiceAddress = array('initials' => substr($arrBillingAddress['firstname'], 0, 1), 'lastName' => $arrBillingAddress['lastname']); $arrAddress = \Paynl\Helper::splitAddress($arrBillingAddress['street']); $invoiceAddress['streetName'] = $arrAddress[0]; $invoiceAddress['houseNumber'] = $arrAddress[1]; $invoiceAddress['zipCode'] = $arrBillingAddress['postcode']; $invoiceAddress['city'] = $arrBillingAddress['city']; $invoiceAddress['country'] = $arrBillingAddress['country_id']; } $arrShippingAddress = $order->getShippingAddress(); if ($arrShippingAddress) { $arrShippingAddress = $arrShippingAddress->toArray(); $shippingAddress = array('initials' => substr($arrShippingAddress['firstname'], 0, 1), 'lastName' => $arrShippingAddress['lastname']); $arrAddress2 = \Paynl\Helper::splitAddress($arrShippingAddress['street']); $shippingAddress['streetName'] = $arrAddress2[0]; $shippingAddress['houseNumber'] = $arrAddress2[1]; $shippingAddress['zipCode'] = $arrShippingAddress['postcode']; $shippingAddress['city'] = $arrShippingAddress['city']; $shippingAddress['country'] = $arrShippingAddress['country_id']; } $data = array('amount' => $total, 'returnUrl' => $returnUrl, 'paymentMethod' => $paymentOptionId, 'bank' => $bankId, 'description' => $orderId, 'extra1' => $orderId, 'extra2' => $quoteId, 'exchangeUrl' => $exchangeUrl, 'currency' => $currency); if (isset($shippingAddress)) { $data['address'] = $shippingAddress; } if (isset($invoiceAddress)) { $data['invoiceAddress'] = $invoiceAddress; } if (isset($enduser)) { $data['enduser'] = $enduser; } $arrProducts = array(); foreach ($items as $item) { $arrItem = $item->toArray(); if ($arrItem['price_incl_tax'] != null) { // taxamount is not valid, because on discount it returns the taxamount after discount $taxAmount = $arrItem['price_incl_tax'] - $arrItem['price']; $product = array('id' => $arrItem['product_id'], 'name' => $arrItem['name'], 'price' => $arrItem['price_incl_tax'], 'qty' => $arrItem['qty_ordered'], 'tax' => $taxAmount); } $arrProducts[] = $product; } //shipping $shippingCost = $order->getShippingInclTax(); $shippingTax = $order->getShippingTaxAmount(); $shippingDescription = $order->getShippingDescription(); $arrProducts[] = array('id' => 'shipping', 'name' => $shippingDescription, 'price' => $shippingCost, 'qty' => 1, 'tax' => $shippingTax); // kortingen $discount = $order->getDiscountAmount(); $discountDescription = $order->getDiscountDescription(); if ($discount != 0) { $arrProducts[] = array('id' => 'discount', 'name' => $discountDescription, 'price' => $discount, 'qty' => 1, 'tax' => $order->getDiscountTaxCompensationAmount() * -1); } $data['products'] = $arrProducts; if ($config->isTestMode()) { $data['testmode'] = 1; } $data['ipaddress'] = $order->getRemoteIp(); $transaction = \Paynl\Transaction::start($data); return $transaction->getRedirectUrl(); }
/** * Get order request data as array * * @param \Magento\Sales\Model\Order $order * @return array */ protected function _getOrderData(\Magento\Sales\Model\Order $order) { $request = array('subtotal' => $this->_formatPrice($this->_formatPrice($order->getPayment()->getBaseAmountAuthorized()) - $this->_formatPrice($order->getBaseTaxAmount()) - $this->_formatPrice($order->getBaseShippingAmount())), 'tax' => $this->_formatPrice($order->getBaseTaxAmount()), 'shipping' => $this->_formatPrice($order->getBaseShippingAmount()), 'invoice' => $order->getIncrementId(), 'address_override' => 'true', 'currency_code' => $order->getBaseCurrencyCode(), 'buyer_email' => $order->getCustomerEmail()); // append to request billing address data if ($billingAddress = $order->getBillingAddress()) { $request = array_merge($request, $this->_getBillingAddress($billingAddress)); } // append to request shipping address data if ($shippingAddress = $order->getShippingAddress()) { $request = array_merge($request, $this->_getShippingAddress($shippingAddress)); } return $request; }
/** * @param $type * @param $message * @param Order $order * @param \WirecardCEE_Stdlib_Return_ReturnAbstract $return * * @return \Magento\Sales\Api\Data\TransactionInterface|null */ public function saveTransaction($type, $message, $order, $return) { $additionalInformation = array(); foreach ($return->getReturned() as $fieldName => $fieldValue) { $additionalInformation[htmlentities($fieldName)] = htmlentities($fieldValue); } $payment = $order->getPayment(); $tid = ''; if ($return instanceof \WirecardCEE_Stdlib_Return_Success) { $tid = $return->getGatewayReferenceNumber(); } /* generate dummy GwRef for pending payments */ if (!strlen($tid)) { $tid = uniqid('tmp_'); } $transaction = $this->_transactionBuilder->setPayment($payment)->setOrder($order)->setTransactionId($tid)->build($type); $transaction->setIsClosed(0); /* must be set as RAW_DETAILS, otherwise they are not displayed in the admin area */ $transaction->setAdditionalInformation(Transaction::RAW_DETAILS, $additionalInformation); $payment->addTransactionCommentsToOrder($transaction, $message); return $transaction; }