/**
  * Creates Payment Data Object
  *
  * @param InfoInterface $paymentInfo
  * @return PaymentDataObjectInterface
  */
 public function create(InfoInterface $paymentInfo)
 {
     if ($paymentInfo instanceof Payment) {
         $data['order'] = $this->orderAdapterFactory->create(['order' => $paymentInfo->getOrder()]);
     } elseif ($paymentInfo instanceof \Magento\Quote\Model\Quote\Payment) {
         $data['order'] = $this->quoteAdapterFactory->create(['quote' => $paymentInfo->getQuote()]);
     }
     $data['payment'] = $paymentInfo;
     return $this->objectManager->create('Magento\\Payment\\Gateway\\Data\\PaymentDataObject', $data);
 }
 /**
  * Payment refund
  *
  * @param \Magento\Payment\Model\InfoInterface $payment
  * @param float $amount
  * @return $this
  * @throws \Magento\Framework\Validator\Exception
  */
 public function refund(\Magento\Payment\Model\InfoInterface $payment, $amount)
 {
     $transactionId = $payment->getParentTransactionId();
     try {
         \Stripe\Charge::retrieve($transactionId)->refund();
     } catch (\Exception $e) {
         $this->debugData(['transaction_id' => $transactionId, 'exception' => $e->getMessage()]);
         $this->_logger->error(__('Payment refunding error.'));
         throw new \Magento\Framework\Validator\Exception(__('Payment refunding error.'));
     }
     $payment->setTransactionId($transactionId . '-' . \Magento\Sales\Model\Order\Payment\Transaction::TYPE_REFUND)->setParentTransactionId($transactionId)->setIsTransactionClosed(1)->setShouldCloseParentTransaction(1);
     return $this;
 }
 /**
  * Update Order Status
  *
  * Used by the Direct Payment method
  *
  * @param \Magento\Payment\Model\InfoInterface $payment
  */
 protected function updateOrderStatus(\Magento\Payment\Model\InfoInterface $payment)
 {
     $additionalInfo = $payment->getTransactionAdditionalInfo();
     $rawDetails = \Magento\Sales\Model\Order\Payment\Transaction::RAW_DETAILS;
     if (array_key_exists($rawDetails, $additionalInfo) && array_key_exists('status', $additionalInfo[$rawDetails])) {
         $status = $additionalInfo[$rawDetails]['status'];
         $order = $payment->getOrder();
         /*
         $configHelper = $this->getModuleHelper()->getMethodConfig(
             $payment->getMethod()
         );
         */
         switch ($status) {
             case \Genesis\API\Constants\Transaction\States::PENDING_ASYNC:
                 // Redirecting to the 3D secure URL
                 if (array_key_exists('redirect_url', $additionalInfo[$rawDetails]) && !empty($additionalInfo[$rawDetails]['redirect_url'])) {
                     $this->getModuleHelper()->setOrderState($order, \Genesis\API\Constants\Transaction\States::PENDING_ASYNC);
                 }
                 break;
             case \Genesis\API\Constants\Transaction\States::APPROVED:
                 if (array_key_exists($rawDetails, $additionalInfo) && array_key_exists('transaction_type', $additionalInfo[$rawDetails])) {
                     $transactionType = $additionalInfo[$rawDetails]['transaction_type'];
                 }
                 $this->getModuleHelper()->setOrderStatusByState($order, $transactionType == \Genesis\API\Constants\Transaction\Types::SALE ? \Magento\Sales\Model\Order::STATE_COMPLETE : \Magento\Sales\Model\Order::STATE_PROCESSING);
                 break;
             default:
                 // Other status. Do nothing.
         }
     }
 }
 protected function setupAuthorizeRequest(array $configData, $vault, $registry, $existingCustomer, array $paymentInfo, array $expectedRequestAttributes, $paymentObject, $storeId, $amount)
 {
     //setup general payment and order information
     $transactionRequest = $this->setupPaymentObject($paymentObject, $storeId);
     //setup config options
     foreach ($configData as $methodName => $value) {
         $this->configMock->expects($this->any())->method($methodName)->willReturn($value);
     }
     //setup payment info instance
     $this->infoInstanceMock->expects($this->any())->method('getAdditionalInformation')->willReturnMap($paymentInfo);
     $this->model->setInfoInstance($this->infoInstanceMock);
     $expectedRequestAttribs = array_merge($transactionRequest, $expectedRequestAttributes);
     $expectedRequestAttribs['amount'] = $amount;
     if ($existingCustomer !== null) {
         $this->vaultMock->expects($this->once())->method('exists')->with(self::CUSTOMER_ID)->willReturn($existingCustomer);
         if ($existingCustomer) {
             unset($expectedRequestAttribs['customer']);
         }
     }
     if (!empty($vault['canSaveCard'])) {
         $this->vaultMock->expects($this->once())->method('canSaveCard')->with(self::AUTH_CC_LAST_4)->willReturn($vault['canSaveCard']);
     }
     if (array_key_exists('registry', $registry)) {
         $this->registryMock->expects($this->once())->method('registry')->with(PaymentMethod::REGISTER_NAME)->willReturn($registry['registry']);
     }
     if (array_key_exists('register', $registry)) {
         $this->registryMock->expects($this->once())->method('register')->with(PaymentMethod::REGISTER_NAME, true);
     }
     return $expectedRequestAttribs;
 }
示例#5
0
 /**
  * Performs authorize transaction
  *
  * @param \Magento\Payment\Model\InfoInterface|Object $payment
  * @param float $amount
  * @return $this
  * @throws InvalidTransitionException
  * @throws LocalizedException
  */
 public function authorize(\Magento\Payment\Model\InfoInterface $payment, $amount)
 {
     $request = $this->buildBasicRequest();
     $order = $payment->getOrder();
     $this->addRequestOrderInfo($request, $order);
     $request = $this->fillCustomerContacts($order, $request);
     $request->setTrxtype(self::TRXTYPE_AUTH_ONLY);
     $request->setOrigid($payment->getAdditionalInformation('pnref'));
     $request->setAmt(round($amount, 2));
     $response = $this->postRequest($request, $this->getConfig());
     $this->processErrors($response);
     try {
         $this->responseValidator->validate($response);
     } catch (LocalizedException $exception) {
         $payment->setParentTransactionId($response->getPnref());
         $this->void($payment);
         throw new LocalizedException(__('Error processing payment, please try again later.'));
     }
     $this->setTransStatus($payment, $response);
     $payment->unsAdditionalInformation('pnref');
     return $this;
 }
示例#6
0
 protected function setupAuthorizeRequest(array $configData, array $paymentInfo, array $expectedRequestAttributes, $paymentObject, $storeId, $amount)
 {
     //setup general payment and order information
     $transactionRequest = $this->setupPaymentObject($paymentObject, $storeId);
     //setup config options
     foreach ($configData as $methodName => $value) {
         $this->configMock->expects($this->any())->method($methodName)->willReturn($value);
     }
     //setup payment info instance
     $this->infoInstanceMock->expects($this->any())->method('getAdditionalInformation')->willReturnMap($paymentInfo);
     $this->model->setInfoInstance($this->infoInstanceMock);
     $expectedRequestAttribs = array_merge($transactionRequest, $expectedRequestAttributes);
     $expectedRequestAttribs['amount'] = $amount;
     return $expectedRequestAttribs;
 }
 /**
  * @covers       \PayStand\PayStandMagento\Model\Directpost::fetchTransactionInfo
  *
  * @param $transactionId
  * @param $resultStatus
  * @param $responseStatus
  * @param $responseCode
  * @return void
  *
  * @dataProvider dataProviderTransaction
  */
 public function testFetchVoidedTransactionInfo($transactionId, $resultStatus, $responseStatus, $responseCode)
 {
     $paymentId = 36;
     $orderId = 36;
     $this->paymentMock->expects(static::once())->method('getId')->willReturn($paymentId);
     $orderMock = $this->getMockBuilder('Magento\\Sales\\Model\\Order')->disableOriginalConstructor()->setMethods(['getId', '__wakeup'])->getMock();
     $orderMock->expects(static::once())->method('getId')->willReturn($orderId);
     $this->paymentMock->expects(static::once())->method('getOrder')->willReturn($orderMock);
     $transactionMock = $this->getMockBuilder('Magento\\Sales\\Model\\Order\\Payment\\Transaction')->disableOriginalConstructor()->getMock();
     $this->transactionRepositoryMock->expects(static::once())->method('getByTransactionId')->with($transactionId, $paymentId, $orderId)->willReturn($transactionMock);
     $document = $this->getTransactionXmlDocument($transactionId, TransactionService::PAYMENT_UPDATE_STATUS_CODE_SUCCESS, $resultStatus, $responseStatus, $responseCode);
     $this->transactionServiceMock->expects(static::once())->method('getTransactionDetails')->with($this->directpost, $transactionId)->willReturn($document);
     // transaction should be closed
     $this->paymentMock->expects(static::once())->method('setIsTransactionDenied')->with(true);
     $this->paymentMock->expects(static::once())->method('setIsTransactionClosed')->with(true);
     $transactionMock->expects(static::once())->method('close');
     $this->directpost->fetchTransactionInfo($this->paymentMock, $transactionId);
 }
 /**
  * @covers \Magento\Authorizenet\Model\Directpost::refund()
  * @return void
  */
 public function testSuccessRefund()
 {
     $card = 1111;
     $this->paymentMock->expects(static::exactly(2))->method('getCcLast4')->willReturn($card);
     $this->paymentMock->expects(static::once())->method('decrypt')->willReturn($card);
     $this->paymentMock->expects(static::exactly(3))->method('getParentTransactionId')->willReturn(self::TRANSACTION_ID . '-capture');
     $this->paymentMock->expects(static::once())->method('getPoNumber')->willReturn(self::INVOICE_NUM);
     $this->paymentMock->expects(static::once())->method('setIsTransactionClosed')->with(true)->willReturnSelf();
     $orderMock = $this->getOrderMock();
     $this->paymentMock->expects(static::exactly(2))->method('getOrder')->willReturn($orderMock);
     $transactionMock = $this->getMockBuilder(Order\Payment\Transaction::class)->disableOriginalConstructor()->setMethods(['getAdditionalInformation'])->getMock();
     $transactionMock->expects(static::once())->method('getAdditionalInformation')->with(Directpost::REAL_TRANSACTION_ID_KEY)->willReturn(self::TRANSACTION_ID);
     $this->transactionRepositoryMock->expects(static::once())->method('getByTransactionId')->willReturn($transactionMock);
     $response = $this->getRefundResponseBody(Directpost::RESPONSE_CODE_APPROVED, Directpost::RESPONSE_REASON_CODE_APPROVED, 'Successful');
     $this->httpClientMock->expects(static::once())->method('getBody')->willReturn($response);
     $this->responseMock->expects(static::once())->method('getXResponseCode')->willReturn(Directpost::RESPONSE_CODE_APPROVED);
     $this->responseMock->expects(static::once())->method('getXResponseReasonCode')->willReturn(Directpost::RESPONSE_REASON_CODE_APPROVED);
     $this->dataHelperMock->expects(static::never())->method('wrapGatewayError');
     $this->directpost->refund($this->paymentMock, self::TOTAL_AMOUNT);
 }
示例#9
0
 /**
  * Retrieve payment information block
  *
  * @param InfoInterface $info
  * @param \Magento\Framework\View\LayoutInterface $layout
  * @return Template
  */
 public function getInfoBlock(InfoInterface $info, LayoutInterface $layout = null)
 {
     $layout = $layout ?: $this->_layout;
     $blockType = $info->getMethodInstance()->getInfoBlockType();
     $block = $layout->createBlock($blockType);
     $block->setInfo($info);
     return $block;
 }
示例#10
0
 public function refund(\Magento\Payment\Model\InfoInterface $payment, $amount)
 {
     if ($amount <= 0) {
         throw new \Magento\Framework\Exception\LocalizedException(__('Invalid amount for refund.'));
     }
     if (!$payment->getParentTransactionId()) {
         throw new \Magento\Framework\Exception\LocalizedException(__('Invalid transaction ID.'));
     }
     $orderNumber = $payment->getAdditionalInformation('tco_order_number');
     $args = array('sale_id' => $orderNumber, 'category' => 5, 'comment' => 'Refund issued by merchant.', 'amount' => $amount, 'currency' => 'vendor');
     $client = $this->_httpClientFactory->create();
     $path = 'sales/refund_invoice';
     $url = $this->getApiUrl();
     $client->setUri($url . $path);
     $client->setConfig(['maxredirects' => 0, 'timeout' => 30]);
     $client->setAuth($this->getConfigData('api_user'), $this->getConfigData('api_pass'));
     $client->setHeaders(['Accept: application/json']);
     $client->setParameterPost($args);
     $client->setMethod(\Zend_Http_Client::POST);
     try {
         $response = $client->request();
         $responseBody = json_decode($response->getBody(), true);
         if (isset($responseBody['errors'])) {
             $this->_logger->critical(sprintf('Error Refunding Invoice: "%s"', $responseBody['errors'][0]['message']));
             throw new \Magento\Framework\Exception\LocalizedException(__($responseBody['errors'][0]['message']));
         } elseif (!isset($responseBody['response_code']) || !isset($responseBody['response_message'])) {
             throw new \Magento\Framework\Exception\LocalizedException(__('Error refunding transaction.'));
         } elseif ($responseBody['response_code'] != 'OK') {
             throw new \Magento\Framework\Exception\LocalizedException(__($responseBody['response_message']));
         }
     } catch (\Exception $e) {
         throw new \Magento\Framework\Exception\LocalizedException(__($e->getMessage()));
     }
     return $this;
 }
 /**
  * @param \Magento\Payment\Model\InfoInterface $payment
  * @param float $amount
  * @return $this
  * @throws LocalizedException
  */
 public function refund(\Magento\Payment\Model\InfoInterface $payment, $amount)
 {
     $senderCustomer = $payment->getAdditionalInformation('destination_customer');
     $customerId = $payment->getOrder()->getCustomerId();
     $customer = $this->customerRepository->getById($customerId);
     $destinationCustomer = $customer->getCustomAttribute('openpay_customer_id')->getValue();
     $paymentLeyend = __('Refund for: ') . __($this->getConfigData('paymentLeyend'))->getText();
     $order = $payment->getOrder();
     $useOrderId = $this->getConfigData('useOrderId');
     $orderId = $order->getIncrementId();
     $params = ['customer_id' => $destinationCustomer, 'amount' => $amount, 'description' => $paymentLeyend, 'order_id' => $useOrderId ? $orderId . '-refund' : null];
     try {
         $transaction = $this->transferAdapter->transfer($senderCustomer, $params);
         $payment->setTransactionId($transaction->getId())->setIsTransactionClosed(0);
         $this->openpayCustomerRepository->clearCustomerCache($senderCustomer);
         $this->openpayCustomerRepository->clearCustomerCache($destinationCustomer);
     } catch (OpenpayException $e) {
         $this->debugData(['request' => $params, 'exception' => $e->getMessage()]);
         $this->_logger->error(__('Payment capturing error.'));
         throw new LocalizedException(__('[' . $e->getErrorCode() . ']' . $e->getMessage()));
     }
     return parent::refund($payment, $amount);
     // TODO: Change the autogenerated stub
 }
示例#12
0
 /**
  * Capture payment
  *
  * @param \Magento\Framework\DataObject|\Magento\Payment\Model\InfoInterface|Payment $payment
  * @param float $amount
  * @return $this
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  */
 public function capture(\Magento\Payment\Model\InfoInterface $payment, $amount)
 {
     $authorizationTransaction = $payment->getAuthorizationTransaction();
     $authorizationPeriod = abs(intval($this->getConfigData('authorization_honor_period')));
     $maxAuthorizationNumber = abs(intval($this->getConfigData('child_authorization_number')));
     $order = $payment->getOrder();
     $isAuthorizationCreated = false;
     if ($payment->getAdditionalInformation($this->_isOrderPaymentActionKey)) {
         $voided = false;
         if (!$authorizationTransaction->getIsClosed() && $this->_isTransactionExpired($authorizationTransaction, $authorizationPeriod)) {
             //Save payment state and configure payment object for voiding
             $isCaptureFinal = $payment->getShouldCloseParentTransaction();
             $payment->setShouldCloseParentTransaction(false);
             $payment->setParentTransactionId($authorizationTransaction->getTxnId());
             $payment->unsTransactionId();
             $payment->setVoidOnlyAuthorization(true);
             $payment->void(new \Magento\Framework\DataObject());
             //Revert payment state after voiding
             $payment->unsAuthorizationTransaction();
             $payment->unsTransactionId();
             $payment->setShouldCloseParentTransaction($isCaptureFinal);
             $voided = true;
         }
         if ($authorizationTransaction->getIsClosed() || $voided) {
             if ($payment->getAdditionalInformation($this->_authorizationCountKey) > $maxAuthorizationNumber - 1) {
                 $this->_exception->create(['phrase' => __('The maximum number of child authorizations is reached.')]);
             }
             $api = $this->_callDoAuthorize($amount, $payment, $authorizationTransaction->getParentTxnId());
             //Adding authorization transaction
             $this->_pro->importPaymentInfo($api, $payment);
             $payment->setTransactionId($api->getTransactionId());
             $payment->setParentTransactionId($authorizationTransaction->getParentTxnId());
             $payment->setIsTransactionClosed(false);
             $formatedPrice = $order->getBaseCurrency()->formatTxt($amount);
             if ($payment->getIsTransactionPending()) {
                 $message = __('We\'ll authorize the amount of %1 as soon as the payment gateway approves it.', $formatedPrice);
             } else {
                 $message = __('The authorized amount is %1.', $formatedPrice);
             }
             $transaction = $this->transactionBuilder->setPayment($payment)->setOrder($order)->setTransactionId($payment->getTransactionId())->setFailSafe(true)->build(Transaction::TYPE_AUTH);
             $payment->addTransactionCommentsToOrder($transaction, $message);
             $payment->setParentTransactionId($api->getTransactionId());
             $isAuthorizationCreated = true;
         }
         //close order transaction if needed
         if ($payment->getShouldCloseParentTransaction()) {
             $orderTransaction = $this->getOrderTransaction($payment);
             if ($orderTransaction) {
                 $orderTransaction->setIsClosed(true);
                 $order->addRelatedObject($orderTransaction);
             }
         }
     }
     if (false === $this->_pro->capture($payment, $amount)) {
         $this->_placeOrder($payment, $amount);
     }
     if ($isAuthorizationCreated && isset($transaction)) {
         $transaction->setIsClosed(true);
     }
     return $this;
 }
示例#13
0
 /**
  * Send authorize request to gateway
  *
  * @param \Magento\Framework\DataObject|\Magento\Payment\Model\InfoInterface $payment
  * @param  float $amount
  * @return void
  * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  */
 public function authorize(\Magento\Payment\Model\InfoInterface $payment, $amount)
 {
     $this->_logger->addDebug('Directpost authorize was hit');
     $payment->setAdditionalInformation('is_transaction_pending', 1);
     $order = $payment->getOrder();
     $order->setState('pending');
     $order->setStatus('pending');
 }
示例#14
0
文件: Info.php 项目: nja78/magento2
 /**
  * Render info item
  *
  * @param array $keys
  * @param \Magento\Payment\Model\InfoInterface $payment
  * @param bool $labelValuesOnly
  * @return array
  */
 protected function _getFullInfo(array $keys, \Magento\Payment\Model\InfoInterface $payment, $labelValuesOnly)
 {
     $result = [];
     foreach ($keys as $key) {
         if (!isset($this->_paymentMapFull[$key])) {
             $this->_paymentMapFull[$key] = [];
         }
         if (!isset($this->_paymentMapFull[$key]['label'])) {
             if (!$payment->hasAdditionalInformation($key)) {
                 $this->_paymentMapFull[$key]['label'] = false;
                 $this->_paymentMapFull[$key]['value'] = false;
             } else {
                 $value = $payment->getAdditionalInformation($key);
                 $this->_paymentMapFull[$key]['label'] = (string) $this->_getLabel($key);
                 $this->_paymentMapFull[$key]['value'] = $this->_getValue($value, $key);
             }
         }
         if (!empty($this->_paymentMapFull[$key]['value'])) {
             if ($labelValuesOnly) {
                 $result[$this->_paymentMapFull[$key]['label']] = $this->_paymentMapFull[$key]['value'];
             } else {
                 $result[$key] = $this->_paymentMapFull[$key];
             }
         }
     }
     return $result;
 }
示例#15
0
 protected function _processResponse(\Magento\Payment\Model\InfoInterface $payment, $response)
 {
     $payment->setAdditionalInformation('3dActive', false);
     switch ($response['resultCode']) {
         case "Authorised":
             //$this->_addStatusHistory($payment, $responseCode, $pspReference, $this->_getConfigData('order_status'));
             $this->_addStatusHistory($payment, $response['resultCode'], $response['pspReference']);
             $payment->setAdditionalInformation('pspReference', $response['pspReference']);
             break;
         case "RedirectShopper":
             // 3d is active so set the param to true checked in Controller/Validate3d
             $payment->setAdditionalInformation('3dActive', true);
             $issuerUrl = $response['issuerUrl'];
             $PaReq = $response['paRequest'];
             $md = $response['md'];
             if (!empty($PaReq) && !empty($md) && !empty($issuerUrl)) {
                 $payment->setAdditionalInformation('issuerUrl', $response['issuerUrl']);
                 $payment->setAdditionalInformation('paRequest', $response['paRequest']);
                 $payment->setAdditionalInformation('md', $response['md']);
             } else {
                 throw new \Magento\Framework\Exception\LocalizedException(__('3D secure is not valid'));
             }
             break;
         case "Refused":
             // refusalReason
             if ($response['refusalReason']) {
                 $refusalReason = $response['refusalReason'];
                 switch ($refusalReason) {
                     case "Transaction Not Permitted":
                         $errorMsg = __('The transaction is not permitted.');
                         break;
                     case "CVC Declined":
                         $errorMsg = __('Declined due to the Card Security Code(CVC) being incorrect. Please check your CVC code!');
                         break;
                     case "Restricted Card":
                         $errorMsg = __('The card is restricted.');
                         break;
                     case "803 PaymentDetail not found":
                         $errorMsg = __('The payment is REFUSED because the saved card is removed. Please try an other payment method.');
                         break;
                     case "Expiry month not set":
                         $errorMsg = __('The expiry month is not set. Please check your expiry month!');
                         break;
                     default:
                         $errorMsg = __('The payment is REFUSED.');
                         break;
                 }
             } else {
                 $errorMsg = __('The payment is REFUSED.');
             }
             if ($errorMsg) {
                 $this->_logger->critical($errorMsg);
                 throw new \Magento\Framework\Exception\LocalizedException(__($errorMsg));
             }
             break;
     }
 }
示例#16
0
文件: Method.php 项目: mage2pro/core
 /**
  * 2016-02-15
  * @override
  * How is a payment method's authorize() used? https://mage2.pro/t/707
  *
  * @see \Magento\Payment\Model\MethodInterface::authorize()
  * https://github.com/magento/magento2/blob/6ce74b2/app/code/Magento/Payment/Model/MethodInterface.php#L249-L257
  * @see \Magento\Payment\Model\Method\AbstractMethod::authorize()
  * https://github.com/magento/magento2/blob/6ce74b2/app/code/Magento/Payment/Model/Method/AbstractMethod.php#L603-L619
  * @param II $payment
  * @param float $amount
  * @return $this
  */
 public final function authorize(II $payment, $amount)
 {
     /**
     * 2016-09-05
     * Отныне валюта платёжных транзакций настраивается администратором опцией
     * «Mage2.PRO» → «Payment» → <...> → «Payment Currency»
     * @see \Df\Payment\Settings::currency()
     *
     * 2016-08-19
     * Со вчерашнего для мои платёжные модули выполняют платёжные транзакции
     * не в учётной валюте системы, а в валюте заказа (т.е., витринной валюте).
     *
     * Однако это привело к тому, что операция авторизации
     * стала помечать заказы (платежи) как «Suspected Fraud» (STATUS_FRAUD).
     * Это происходит из-за кода метода
     * @see \Magento\Sales\Model\Order\Payment\Operations\AuthorizeOperation::authorize()
     				$isSameCurrency = $payment->isSameCurrency();
     				if (!$isSameCurrency || !$payment->isCaptureFinal($amount)) {
     					$payment->setIsFraudDetected(true);
     				}
     *
     * Метод @see \Magento\Sales\Model\Order\Payment::isSameCurrency() работает так:
     				return
     			!$this->getCurrencyCode()
     			|| $this->getCurrencyCode() == $this->getOrder()->getBaseCurrencyCode()
     		;
     * По умолчанию $this->getCurrencyCode() возвращает null,
     * и поэтому isSameCurrency() возвращает true.
     * Magento, получается, думает, что платёж выполняется в учёной валюте системы,
     * но вызов $payment->isCaptureFinal($amount) вернёт false,
     * потому что $amount — размер платежа в учётной валюте системы, а метод устроен так:
     * @see \Magento\Sales\Model\Order\Payment::isCaptureFinal()
     			$total = $this->getOrder()->getTotalDue();
     			return
     			$this->amountFormat($total, true)
     		==
     			$this->amountFormat($amountToCapture, true)
     	;
     * Т.е. метод сравнивает размер подлежащей оплате стоимости заказа в валюте заказа
     * с размером текущего платежа, который в учётной валюте системы,
     * и поэтому вот метод возвращает false.
     *
     * Самым разумным решением этой проблемы мне показалось
     * ручное убирание флага IsFraudDetected
     */
     if ($payment instanceof OP) {
         $payment->setIsFraudDetected(false);
     }
     $this->charge($this->cFromBase($amount), $capture = false);
     return $this;
 }
示例#17
0
 /**
  * @param InfoInterface $payment
  * @param string $transactionId
  * @return DataObject
  * @throws LocalizedException
  */
 protected function transactionInquiryRequest(InfoInterface $payment, $transactionId)
 {
     $request = $this->buildBasicRequest();
     $request->setTrxtype(self::TRXTYPE_DELAYED_INQUIRY);
     $transactionId = $payment->getCcTransId() ? $payment->getCcTransId() : $transactionId;
     $request->setOrigid($transactionId);
     $response = $this->postRequest($request, $this->getConfig());
     return $response;
 }
示例#18
0
 /**
  * Perform the payment review
  *
  * @param \Magento\Payment\Model\InfoInterface $payment
  * @param string $action
  * @return bool
  */
 public function reviewPayment(\Magento\Payment\Model\InfoInterface $payment, $action)
 {
     $api = $this->getApi()->setTransactionId($payment->getLastTransId());
     // check whether the review is still needed
     $api->callGetTransactionDetails();
     $this->importPaymentInfo($api, $payment);
     if (!Info::isPaymentReviewRequired($payment)) {
         return false;
     }
     // perform the review action
     $api->setAction($action)->callManagePendingTransactionStatus();
     $api->callGetTransactionDetails();
     $this->importPaymentInfo($api, $payment);
     return true;
 }
示例#19
0
 /**
  * Capture payment
  *
  * @param InfoInterface|Payment $payment
  * @param float $amount
  * @return $this
  * @throws \Magento\Framework\Exception\LocalizedException
  * @throws \Magento\Framework\Exception\State\InvalidTransitionException
  */
 public function capture(InfoInterface $payment, $amount)
 {
     /** @var Payment $payment */
     $token = $payment->getAdditionalInformation(self::PNREF);
     parent::capture($payment, $amount);
     if ($token && !$payment->getAuthorizationTransaction()) {
         $this->createPaymentToken($payment, $token);
     }
     return $this;
 }
示例#20
0
 /**
  * Captures specified amount, override the method in Braintree CC method as transaction through PayPal does not
  * can't be cloned
  *
  * @param InfoInterface $payment
  * @param float $amount
  * @return $this
  * @throws LocalizedException
  */
 public function capture(InfoInterface $payment, $amount)
 {
     try {
         /** @var \Magento\Sales\Model\Order\Payment $payment */
         if ($payment->getCcTransId()) {
             $result = $this->braintreeTransaction->submitForSettlement($payment->getCcTransId(), $amount);
             $this->_debug([$payment->getCcTransId() . ' - ' . $amount]);
             $this->_debug($this->_convertObjToArray($result));
             if ($result->success) {
                 $payment->setIsTransactionClosed(false)->setShouldCloseParentTransaction(true);
             } else {
                 throw new LocalizedException($this->errorHelper->parseBraintreeError($result));
             }
         } else {
             $this->braintreeAuthorize($payment, $amount, true);
         }
     } catch (\Exception $e) {
         $this->_logger->critical($e);
         throw new LocalizedException(__('There was an error capturing the transaction: %1.', $e->getMessage()));
     }
     return $this;
 }
示例#21
0
 /**
  * Fetch transaction details info
  *
  * Update transaction info if there is one placing transaction only
  *
  * @param \Magento\Payment\Model\InfoInterface $payment
  * @param string $transactionId
  * @return array
  */
 public function fetchTransactionInfo(\Magento\Payment\Model\InfoInterface $payment, $transactionId)
 {
     $transaction = $this->transactionRepository->getByTransactionId($transactionId, $payment->getId(), $payment->getOrder()->getId());
     $response = $this->getTransactionResponse($transactionId);
     if ($response->getXResponseCode() == self::RESPONSE_CODE_APPROVED) {
         if ($response->getTransactionStatus() == 'voided') {
             $payment->setIsTransactionDenied(true);
             $payment->setIsTransactionClosed(true);
             $transaction->close();
         } else {
             $transaction->setAdditionalInformation(self::TRANSACTION_FRAUD_STATE_KEY, false);
             $payment->setIsTransactionApproved(true);
         }
     } elseif ($response->getXResponseReasonCode() == self::RESPONSE_REASON_CODE_PENDING_REVIEW_DECLINED) {
         $payment->setIsTransactionDenied(true);
     }
     $this->addStatusCommentOnUpdate($payment, $response, $transactionId);
     return [];
 }
示例#22
0
 /**
  * Format price with currency sign
  * @param  \Magento\Payment\Model\InfoInterface $payment
  * @param float $amount
  * @return string
  */
 protected function formatPrice($payment, $amount)
 {
     return $payment->getOrder()->getBaseCurrency()->formatTxt($amount);
 }
 /**
  * If gateway actions are locked return true
  *
  * @param  \Magento\Payment\Model\InfoInterface $payment
  * @return bool
  */
 protected function isGatewayActionsLocked($payment)
 {
     return $payment->getAdditionalInformation(self::GATEWAY_ACTIONS_LOCKED_STATE_KEY);
 }
示例#24
0
 public function refund(\Magento\Payment\Model\InfoInterface $payment, $amount)
 {
     $ttid = $payment->getParentTransactionId();
     try {
         $monetra = new MonetraInterface($this->getMonetraConfigData());
         $response = $monetra->refund($ttid, $amount);
     } catch (MonetraException $e) {
         $this->_logger->critical("Error occurred while attempting Monetra refund. Details: " . $e->getMessage());
         throw new LocalizedException(__($this->_scopeConfig->getValue('payment/monetra_client_ticket/user_facing_error_message')));
     }
     if ($response['code'] !== 'AUTH') {
         $this->_logger->info(sprintf('Monetra refund failed for TTID %d. Verbiage: %s', $response['ttid'], $response['verbiage']));
         throw new LocalizedException(__('Refund request failed. Details: ' . $response['verbiage']));
     }
     return $this;
 }
示例#25
0
 /**
  * Returns request object with needed data for API request to PayPal to get form URL.
  *
  * @param \Magento\Payment\Model\InfoInterface $payment
  * @return \Magento\Paypal\Model\Hostedpro\Request
  */
 protected function _buildFormUrlRequest(\Magento\Payment\Model\InfoInterface $payment)
 {
     $order = $payment->getOrder();
     $request = $this->_buildBasicRequest()->setOrder($order)->setPaymentMethod($this)->setAmount($order);
     return $request;
 }
示例#26
0
 /**
  * @param InfoInterface $payment
  * @return array
  */
 protected function getTransactionsToVoid(InfoInterface $payment)
 {
     $transactionIds = [];
     $invoice = $this->_registry->registry('current_invoice');
     if ($invoice && $invoice->getId() && $invoice->getTransactionId()) {
         $transactionIds[] = $this->braintreeHelper->clearTransactionId($invoice->getTransactionId());
     } else {
         $collection = $this->salesTransactionCollectionFactory->create()->addFieldToSelect('txn_id')->addOrderIdFilter($payment->getOrder()->getId())->addTxnTypeFilter([PaymentTransaction::TYPE_AUTH, PaymentTransaction::TYPE_CAPTURE]);
         $fetchedIds = $collection->getColumnValues('txn_id');
         foreach ($fetchedIds as $transactionId) {
             $txnId = $this->braintreeHelper->clearTransactionId($transactionId);
             if (!in_array($txnId, $transactionIds)) {
                 $transactionIds[] = $txnId;
             }
         }
     }
     return $transactionIds;
 }
示例#27
0
 /**
  * Processes reference transactions
  *      - Capture
  *      - Refund
  *      - Void
  *
  * @param \Magento\Payment\Model\InfoInterface $payment
  * @param $amount
  * @throws \Exception
  */
 protected function processRefTransaction(\Magento\Payment\Model\InfoInterface $payment, $amount)
 {
     $transactionType = $this->getTransactionType();
     $order = $payment->getOrder();
     switch ($transactionType) {
         case \Genesis\API\Constants\Transaction\Types::CAPTURE:
             $data = array('transaction_id' => $this->getModuleHelper()->genTransactionId(), 'remote_ip' => $order->getRemoteIp(), 'reference_id' => $this->getReferenceCaptureTxnId($payment), 'currency' => $order->getBaseCurrencyCode(), 'amount' => $amount);
             break;
         case \Genesis\API\Constants\Transaction\Types::REFUND:
             $data = array('transaction_id' => $this->getModuleHelper()->genTransactionId(), 'remote_ip' => $order->getRemoteIp(), 'reference_id' => $this->getReferenceRefundTxnId($payment), 'currency' => $order->getBaseCurrencyCode(), 'amount' => $amount);
             break;
         case \Genesis\API\Constants\Transaction\Types::VOID:
             $data = array('transaction_id' => $this->getModuleHelper()->genTransactionId(), 'remote_ip' => $order->getRemoteIp(), 'reference_id' => $this->getReferenceVoidTxnId($payment));
             break;
         default:
             throw new \Exception(__('Unsupported transaction (' . $transactionType . ').'));
     }
     $responseObject = $this->processReferenceTransaction($transactionType, $payment, $data);
     if ($responseObject->status == \Genesis\API\Constants\Transaction\States::APPROVED) {
         $this->getMessageManager()->addSuccess($responseObject->message);
     } else {
         throw new \Exception(__($responseObject->message));
     }
 }
示例#28
0
 /**
  * Perform the payment review
  *
  * @param InfoInterface $payment
  * @param string $action
  * @return bool
  */
 public function reviewPayment(InfoInterface $payment, $action)
 {
     $request = $this->buildBasicRequest();
     $transactionId = $payment->getCcTransId() ? $payment->getCcTransId() : $payment->getLastTransId();
     $request->setTrxtype(self::TRXTYPE_ACCEPT_DENY);
     $request->setOrigid($transactionId);
     $request->setUpdateaction($action);
     $response = $this->postRequest($request, $this->getConfig());
     $payment->setAdditionalInformation((array) $response->getData());
     $this->processErrors($response);
     if (!$this->_isTransactionUnderReview($response->getOrigresult())) {
         $payment->setTransactionId($response->getOrigpnref())->setIsTransactionClosed(0);
         if ($response->getOrigresult() == self::RESPONSE_CODE_APPROVED) {
             $payment->setIsTransactionApproved(true);
         } elseif ($response->getOrigresult() == self::RESPONSE_CODE_DECLINED_BY_MERCHANT) {
             $payment->setIsTransactionDenied(true);
         }
     }
     $rawData = $response->getData();
     return $rawData ? $rawData : [];
 }
 /**
  * Void Payment
  * @param \Magento\Payment\Model\InfoInterface $payment
  * @return $this
  * @throws \Magento\Framework\Webapi\Exception
  */
 public function void(\Magento\Payment\Model\InfoInterface $payment)
 {
     /** @var \Magento\Sales\Model\Order $order */
     $order = $payment->getOrder();
     $this->getLogger()->debug('Void transaction for order #' . $order->getIncrementId());
     $referenceTransaction = $this->getModuleHelper()->lookUpVoidReferenceTransaction($payment);
     if ($referenceTransaction->getTxnType() == \Magento\Sales\Model\Order\Payment\Transaction::TYPE_AUTH) {
         $authTransaction = $referenceTransaction;
     } else {
         $authTransaction = $this->getModuleHelper()->lookUpAuthorizationTransaction($payment);
     }
     if (!isset($authTransaction) || !isset($referenceTransaction)) {
         $errorMessage = 'Void transaction for order #' . $order->getIncrementId() . ' cannot be finished (No Authorize / Capture Transaction exists)';
         $this->getLogger()->error($errorMessage);
         $this->getModuleHelper()->throwWebApiException($errorMessage);
     }
     try {
         $this->getModuleHelper()->setTokenByPaymentTransaction($authTransaction);
         $data = array('transaction_id' => $this->getModuleHelper()->genTransactionId(), 'remote_ip' => $order->getRemoteIp(), 'reference_id' => $referenceTransaction->getTxnId());
         $responseObject = $this->processReferenceTransaction(\Genesis\API\Constants\Transaction\Types::VOID, $payment, $data);
         if ($responseObject->status == \Genesis\API\Constants\Transaction\States::APPROVED) {
             $this->getMessageManager()->addSuccess($responseObject->message);
         } else {
             $this->getModuleHelper()->throwWebApiException($responseObject->message);
         }
         unset($data);
     } catch (\Exception $e) {
         $this->getLogger()->error($e->getMessage());
         $this->getModuleHelper()->maskException($e);
     }
     return $this;
 }
 /**
  * @inheritdoc
  */
 public function capture(\Magento\Payment\Model\InfoInterface $payment, $amount)
 {
     if (!$payment instanceof OrderPaymentInterface) {
         throw new \DomainException('Not implemented');
     }
     /** @var $payment Payment */
     if ($payment->getAuthorizationTransaction()) {
         throw new \DomainException('Capture can not be performed through vault');
     }
     $this->attachTokenExtensionAttribute($payment);
     $commandExecutor = $this->commandManagerPool->get($this->getVaultProvider()->getCode());
     $commandExecutor->executeByCode(VaultPaymentInterface::VAULT_SALE_COMMAND, $payment, ['amount' => $amount]);
     $payment->setMethod($this->getVaultProvider()->getCode());
 }