Notifies when payment is done and failed.

@param PaymentBridgeInterface $paymentBridge Payment Bridge
@param PaymentMethodInterface $paymentMethod Payment method

@return PaymentEventDispatcher self Object
347082
public function notifyPaymentOrderFail(
        PaymentBridgeInterface $paymentBridge,
        PaymentMethodInterface $paymentMethod
    ) {
        $paymentOrderFailEvent = new PaymentOrderFailEvent(
            $paymentBridge,
            $paymentMethod
        );

        $this
            ->eventDispatcher
            ->dispatch(
                PaymentCoreEvents::PAYMENT_ORDER_FAIL,
                $paymentOrderFailEvent
            );

        return $this;
    }
158705
public function disableRecurringPayments(string $currencyCode, string $paymentProviderId): BalanceInterface
    {
        $response = $this->client->post(
            $this->getBaseEndpointUri()->withPath("{$this->getBaseEndpointUri()->getPath()}/recurring-setup")->withQuery(http_build_query(['supportedCurrencyId' => $currencyCode])),
            (string) json_encode((object) [
                'providerId' => $paymentProviderId,
                'chargePerUsage' => 'true',
            ])
        );

        return $this->entitySerializer->deserialize(
            (string) $response->getBody(),
            $this->getEntityClass(),
            'json'
        );
    }
1363454
public function log(
        $level,
        $message,
        $paymentMethod,
        array $context = []
    ) {
        if (!$this->active) {
            return $this;
        }

        $this
            ->logger
            ->log(
                $level,
                "[$paymentMethod] - $message",
                $context
            );

        return $this;
    }
199312
private function prepareData(StripeMethod $paymentMethod, $amount)
    {
        /// first check that amounts are the same
        $cartAmount = intval($this->paymentBridge->getAmount());

        /**
         * If both amounts are different, execute Exception.
         */
        if (abs($amount - $cartAmount) > 0.00001) {
            throw new PaymentAmountsNotMatchException();
        }

        /**
         * At this point, order must be created given a cart, and placed in PaymentBridge.
         *
         * So, $this->paymentBridge->getOrder() must return an object
         */
        $this
            ->paymentEventDispatcher
            ->notifyPaymentOrderLoad(
                $this->paymentBridge,
                $paymentMethod
            );

        /**
         * Order Not found Exception must be thrown just here.
         */
        if (!$this->paymentBridge->getOrder()) {
            throw new PaymentOrderNotFoundException();
        }

        /**
         * Order exists right here.
         */
        $this
            ->paymentEventDispatcher
            ->notifyPaymentOrderCreated(
                $this->paymentBridge,
                $paymentMethod
            );

        return new StripeTransaction(
            $paymentMethod->getApiToken(),
            $cartAmount,
            $this->paymentBridge->getCurrency()
        );
    }
1107081
static public function isPaymentMethod($paymentMethod) {
    return ((string) $paymentMethod == Connect2PayClient::PAYMENT_METHOD_CREDITCARD ||
        (string) $paymentMethod == Connect2PayClient::PAYMENT_METHOD_TODITOCASH ||
        (string) $paymentMethod == Connect2PayClient::PAYMENT_METHOD_BANKTRANSFER ||
        (string) $paymentMethod == Connect2PayClient::PAYMENT_METHOD_DIRECTDEBIT ||
        (string) $paymentMethod == Connect2PayClient::PAYMENT_METHOD_WECHAT ||
        (string) $paymentMethod == Connect2PayClient::PAYMENT_METHOD_LINE ||
        (string) $paymentMethod == Connect2PayClient::PAYMENT_METHOD_ALIPAY);
  }
1159614
public function notifyPaymentOrderLoad(
        PaymentBridgeInterface $paymentBridge,
        PaymentMethodInterface $paymentMethod
    ) {
        $paymentOrderLoadEvent = new PaymentOrderLoadEvent(
            $paymentBridge,
            $paymentMethod
        );

        $this
            ->eventDispatcher
            ->dispatch(
                PaymentCoreEvents::PAYMENT_ORDER_LOAD,
                $paymentOrderLoadEvent
            );

        return $this;
    }
289566
protected function validatePaymentTransaction(PaymentTransaction $paymentTransaction)
    {
        $this->validateQueryConfig($paymentTransaction);

        $errorMessage   = '';
        $missedFields   = array();
        $invalidFields  = array();

        foreach (static::$requestFieldsDefinition as $fieldDescription)
        {
            list($fieldName, $propertyPath, $isFieldRequired, $validationRule) = $fieldDescription;

            $fieldValue = PropertyAccessor::getValue($paymentTransaction, $propertyPath, false);

            if (!empty($fieldValue))
            {
                try
                {
                    Validator::validateByRule($fieldValue, $validationRule);
                }
                catch (ValidationException $e)
                {
                    $invalidFields[] = "Field '{$fieldName}' from property path '{$propertyPath}', {$e->getMessage()}.";
                }
            }
            elseif ($isFieldRequired)
            {
                $missedFields[] = "Field '{$fieldName}' from property path '{$propertyPath}' missed or empty.";
            }
        }

        if (!empty($missedFields))
        {
            $errorMessage .= "Some required fields missed or empty in PaymentTransaction: \n" .
                             implode("\n", $missedFields) . "\n";
        }

        if (!empty($invalidFields))
        {
            $errorMessage .= "Some fields invalid in PaymentTransaction: \n" .
                             implode("\n", $invalidFields) . "\n";
        }

        if (!empty($errorMessage))
        {
            throw new ValidationException($errorMessage);
        }
    }
138968
function DoExpressCheckoutPayment($token, $payerId, $options = array()) {
    $values = array_merge($options, array('TOKEN'   => $token,
                                          'PAYERID' => $payerId));
    if (PAYPAL_DEV_MODE == 'true') $this->log('DoExpressCheckout - breakpoint 1 - ['.$token  . ' ' . $payerId . ' ' . "]\n\n[" . print_r($values, true) .']', $token);

    if ($this->_mode == 'payflow') {
      $values['ACTION'] = 'D'; /* ACTION=D denotes DoExpressCheckoutPayment via Payflow */
      $values['TENDER'] = 'P';
      $values['TRXTYPE'] = $this->_trxtype;
      $values['NOTIFYURL'] = zen_href_link('ipn_main_handler.php', '', 'SSL',false,false,true);
    } elseif ($this->_mode == 'nvp') {
      if (!isset($values['PAYMENTACTION']) || $this->checkHasApiCredentials() === FALSE) $values['PAYMENTACTION'] = ($this->_trxtype == 'S' || ($this->checkHasApiCredentials() === FALSE) ? 'Sale' : 'Authorization');
      $values['NOTIFYURL'] = urlencode(zen_href_link('ipn_main_handler.php', '', 'SSL',false,false,true));
    }
    $this->values = $values;
    $this->notify('NOTIFY_PAYPAL_DOEXPRESSCHECKOUTPAYMENT');
    if (PAYPAL_DEV_MODE == 'true') $this->log('DoExpressCheckout - breakpoint 2 '.print_r($this->values, true), $token);
    return $this->_request($this->values, 'DoExpressCheckoutPayment');
  }
905603
public function validateCard(PaylandsMethod $paymentMethod)
    {
        $response = $this->client->retrieveCustomerCards($paymentMethod->getCustomerExternalId());

        foreach ($response['cards'] as $card) {
            if ($paymentMethod->getCardUuid() == $card['uuid']) {
                $paymentMethod
                    ->setPaymentStatus(PaylandsMethod::STATUS_OK)
                    ->setPaymentResult($response);

                return;
            }
        }

        throw new CardNotFoundException(sprintf('Card %s not found for customer %s',
            $paymentMethod->getCardUuid(),
            $paymentMethod->getCustomerExternalId()
        ));
    }
508182
public function getBarePaymentHandler($paymentHandlerId, $languageId = null)
    {
        $cacheKey = $paymentHandlerId;
        if (false === isset($this->cache[$cacheKey])) {
            $paymentHandler = $this->subject->getBarePaymentHandler($paymentHandlerId, $languageId);
            if (null === $paymentHandler) {
                return null;
            }
            $this->cache[$cacheKey] = $paymentHandler->sqlData;

            return $paymentHandler;
        }

        return TdbShopPaymentHandler::getInstanceFromDataRow($this->cache[$cacheKey], $languageId);
    }
63062
public function declinePayment($orderId)
    {
        /**
         * Loads order to validate.
         */
        $this
            ->paymentBridge
            ->findOrder($orderId);

        /**
         * Order Not found Exception must be thrown just here.
         */
        if (!$this->paymentBridge->getOrder()) {
            throw new PaymentOrderNotFoundException();
        }

        /**
         * Payment failed.
         *
         * Paid process has ended with failure
         */
        $this
            ->paymentEventDispatcher
            ->notifyPaymentOrderFail(
                $this->paymentBridge,
                $this
                    ->methodFactory
                    ->create()
            );

        return $this;
    }
642582
protected function triggerEventsOnSuccess(PayoneTransactionStatusUpdateTransfer $transactionStatusUpdateTransfer)
    {
        if (!$transactionStatusUpdateTransfer->getIsSuccess()) {
            return;
        }

        $orderItems = SpySalesOrderItemQuery::create()
            ->useOrderQuery()
            ->useSpyPaymentPayoneQuery()
            ->filterByTransactionId($transactionStatusUpdateTransfer->getTxid())
            ->endUse()
            ->endUse()
            ->find();
        $this->getFactory()->getOmsFacade()->triggerEvent('PaymentNotificationReceived', $orderItems, []);

        if ($transactionStatusUpdateTransfer->getTxaction() === PayoneConstants::PAYONE_TXACTION_APPOINTED) {
            $this->getFactory()->getOmsFacade()->triggerEvent('RedirectResponseAppointed', $orderItems, []);
        }
    }
168608
public function manageMandate(PayoneManageMandateTransfer $manageMandateTransfer)
    {
        /** @var \SprykerEco\Zed\Payone\Business\Payment\MethodMapper\DirectDebit $paymentMethodMapper */
        $paymentMethodMapper = $this->getRegisteredPaymentMethodMapper(PayoneApiConstants::PAYMENT_METHOD_DIRECT_DEBIT);
        $requestContainer = $paymentMethodMapper->mapManageMandate($manageMandateTransfer);
        $this->setStandardParameter($requestContainer);

        $rawResponse = $this->executionAdapter->sendRequest($requestContainer);
        $responseContainer = new ManageMandateResponseContainer($rawResponse);

        $manageMandateTransfer->setErrorCode($responseContainer->getErrorcode());
        $manageMandateTransfer->setCustomerErrorMessage($responseContainer->getCustomermessage());
        $manageMandateTransfer->setStatus($responseContainer->getStatus());
        $manageMandateTransfer->setInternalErrorMessage($responseContainer->getErrormessage());
        $manageMandateTransfer->setMandateIdentification($responseContainer->getMandateIdentification());
        $manageMandateTransfer->setMandateText($responseContainer->getMandateText());
        $manageMandateTransfer->setIban($responseContainer->getIban());
        $manageMandateTransfer->setBic($responseContainer->getBic());

        return $manageMandateTransfer;
    }
1349866
public function isOpenInvoice($paymentMethod)
    {
        if ($this->isKlarna($paymentMethod) ||
            strcmp($paymentMethod, self::RATEPAY) === 0 ||
            $this->isAfterPay($paymentMethod)) {
            return true;
        }

        return false;
    }
473442
public function processPayment(PaylandsMethod $paymentMethod)
    {
        /*
         * At this point, order must be created given a cart, and placed in PaymentBridge.
         *
         * So, $this->paymentBridge->getOrder() must return an object
         */
        $this
            ->paymentEventDispatcher
            ->notifyPaymentOrderLoad(
                $this->paymentBridge,
                $paymentMethod
            );

        /*
         * Order Not found Exception must be thrown just here.
         */
        if (!$this->paymentBridge->getOrder()) {
            throw new PaymentOrderNotFoundException();
        }

        /*
         * Order exists right here.
         */
        $this
            ->paymentEventDispatcher
            ->notifyPaymentOrderCreated(
                $this->paymentBridge,
                $paymentMethod
            );

        /*
         * Try to make the payment transaction
         */
        try {
            $this->paylandsApiAdapter->validateCard($paymentMethod);

            $this->paylandsEventDispatcher->notifyCardValid($paymentMethod);

            if (!$paymentMethod->isOnlyTokenizeCard()) {
                $this->paylandsApiAdapter->createTransaction($paymentMethod);
            }

            /*
             * Payment paid done.
             *
             * Paid process has ended ( No matters result )
             */
            $this
                ->paymentEventDispatcher
                ->notifyPaymentOrderDone(
                    $this->paymentBridge,
                    $paymentMethod
                );

            if (PaylandsMethod::STATUS_OK !== $paymentMethod->getPaymentStatus()) {
                throw new PaymentException(sprintf('Order %s could not be paid',
                    $paymentMethod->getPaymentResult()['order']['uuid']
                ));
            }

            /*
             * Payment paid successfully.
             *
             * Paid process has ended successfully
             */
            $this
                ->paymentEventDispatcher
                ->notifyPaymentOrderSuccess(
                    $this->paymentBridge,
                    $paymentMethod
                );
        } catch (PaymentException $e) {
            /*
             * Payment paid failed.
             *
             * Paid process has ended failed
             */
            $this
                ->paymentEventDispatcher
                ->notifyPaymentOrderFail(
                    $this->paymentBridge,
                    $paymentMethod
                );

            throw $e;
        }

        return $this;
    }
788401
protected function createPaymentMethodContainerFromPayment(SpyPaymentPayone $paymentEntity)
    {
        $paymentMethodContainer = new CreditCardPseudoContainer();

        $pseudoCardPan = $paymentEntity->getSpyPaymentPayoneDetail()->getPseudoCardPan();
        $paymentMethodContainer->setPseudoCardPan($pseudoCardPan);

        $threeDSecure = $this->createThreeDSecureData($paymentEntity);
        $paymentMethodContainer->setThreeDSecure($threeDSecure);

        return $paymentMethodContainer;
    }
594582
public function onPaymentDone(PaymentEvent $event)
    {
        $payment = $event->getPayment();
        if (!$payment instanceof OrderPayment) {
            return;
        }

        $order = $payment->getOrder();
        if ($order->getLocked()) {
            $order->setLocked(false);
            $this->updateOrder($order, $event);
        }

        $returnPath = null;
        $details = $payment->getDetails();
        if (array_key_exists('done_redirect_path', $details)) {
            $returnPath = $details['done_redirect_path'];
        } else {
            $type = $order->getType();
            if ($type === OrderTypes::TYPE_CART) {
                $returnPath = $this->urlGenerator->generate('ekyna_cart_payment');
            } elseif ($type === OrderTypes::TYPE_QUOTE) {
                throw new \BadMethodCallException('Not yet implemented');
            } elseif ($type === OrderTypes::TYPE_ORDER) {
                if ($this->authorization->isGranted('ROLE_ADMIN')) {
                    $returnPath = $this->urlGenerator->generate(
                        'ekyna_order_order_admin_show',
                        array('orderId' => $order->getId())
                    );
                } else {
                    $returnPath = $this->urlGenerator->generate(
                        'ekyna_cart_confirmation',
                        array(
                            'orderKey' => $order->getKey(),
                            'paymentId' => $payment->getId(),
                        )
                    );
                }
            }
        }

        if (null === $returnPath) {
            throw new LogicException('Unable to determine return path.');
        }

        $event->setResponse(new RedirectResponse($returnPath));
    }