@param TdbPkgShopPaymentIpnMessage $oMessage

@throws TPkgShopPaymentIPNException_InvalidPaymentHandlerGroupInRequest
@throws TPkgShopPaymentIPNException_OrderNotFound
@throws TPkgShopPaymentIPNException_RequestError
511659
public function parseRequest(TdbPkgShopPaymentIpnMessage $oMessage)
    {
        if (false === $this->isIPNRequest()) {
            throw new TPkgShopPaymentIPNException_RequestError($this, "handleIPN called with an invalid URL (URL: {$this->getRequestURL(
            )})", 0);
        }

        $aParts = explode(self::URL_IPN_IDENTIFIER, $this->requestURL);
        if (2 !== count($aParts)) {
            throw new TPkgShopPaymentIPNException_RequestError($this, "handleIPN called with an invalid URL (URL: {$this->getRequestURL(
            )})", 0);
        }

        $sData = substr(
            $this->requestURL,
            stripos($this->requestURL, self::URL_IPN_IDENTIFIER) + strlen(self::URL_IPN_IDENTIFIER)
        );

        if ('' === empty($sData)) {
            throw new TPkgShopPaymentIPNException_RequestError($this, "handleIPN called with an invalid URL (URL: {$this->getRequestURL(
            )})", 0);
        }

        $sPaymentGroupIdentifier = null;
        $sOrderCmsIdent = null;
        if (false !== strpos($sData, '__')) {
            $sPaymentGroupIdentifier = substr($sData, 0, strpos($sData, '__'));
            $sOrderCmsIdent = substr($sData, strpos($sData, '__') + 2);
        } else {
            $sPaymentGroupIdentifier = $sData;
        }

        if (null !== $sPaymentGroupIdentifier) {
            $this->paymentHandlerGroup = null;
            $oPaymentHandlerGroup = TdbShopPaymentHandlerGroup::GetNewInstance();
            if (false === $oPaymentHandlerGroup->LoadFromField('ipn_group_identifier', $sPaymentGroupIdentifier)) {
                if (false === $oPaymentHandlerGroup->LoadFromField('system_name', $sPaymentGroupIdentifier)) {
                    $oPaymentHandlerGroup = null;
                }
            }

            // cast to correct object type
            if (null !== $oPaymentHandlerGroup) {
                $this->paymentHandlerGroup = TdbShopPaymentHandlerGroup::GetNewInstance($oPaymentHandlerGroup->sqlData);
            }
        }
        if (null === $this->paymentHandlerGroup) {
            throw new TPkgShopPaymentIPNException_InvalidPaymentHandlerGroupInRequest($this, "no payment handler group found for URL (URL: {$this->getRequestURL(
            )})", 0);
        }

        // we have a payment group - we may need to transform the raw data using it (because the encoding may be non utf8 for exampel)
        $oMessage->SaveFieldsFast(array('shop_payment_handler_group_id' => $this->paymentHandlerGroup->id));

        // once we have the group we may need to convert the request data
        if ('UTF-8' !== strtoupper($this->getPaymentHandlerGroup()->fieldIpnPayloadCharacterCharset)) {
            $this->requestPayload = $this->convertCharset(
                $this->requestPayload,
                $this->getPaymentHandlerGroup()->fieldIpnPayloadCharacterCharset
            );
        }

        $this->requestPayload = $this->paymentHandlerGroup->processRawRequestData($this->requestPayload);

        $oMessage->SaveFieldsFast(
            array('payload' => serialize($this->requestPayload))
        ); // note: we need to serialize the data since savefieldsfast does NO data transformation before saving

        if (null !== $sOrderCmsIdent) {
            $oOrder = TdbShopOrder::GetNewInstance();
            if (true === $oOrder->LoadFromField('cmsident', $sOrderCmsIdent)) {
                $this->order = $oOrder;
            } else {
                throw new TPkgShopPaymentIPNException_OrderNotFound($sOrderCmsIdent, $this, "order [{$sOrderCmsIdent}] passed via URL not found (URL: {$this->getRequestURL(
                )})", 0);
            }
        } else {
            $this->order = $this->getPaymentHandlerGroup()->getOrderFromRequestData($this->getRequestPayload());
            if (null === $this->order) {
                throw new TPkgShopPaymentIPNException_OrderNotFound($sOrderCmsIdent, $this, "Order not found using payment group [{$this->getPaymentHandlerGroup(
                )->id} class: ".get_class($this->getPaymentHandlerGroup()).'] for request ['.print_r(
                    $this->getRequestPayload(),
                    true
                )."] (URL: {$this->getRequestURL()})", 0);
            }
        }

        $oMessage->SaveFieldsFast(array('shop_order_id' => $this->getOrder()->id));

        $oPaymentHandler = $this->getOrder()->GetPaymentHandler();

        if (null === $oPaymentHandler || false === ($oPaymentHandler instanceof IPkgShopPaymentIPNPaymentHandler)) {
            throw new TPkgShopPaymentIPNException_SystemError_PaymentHanlderDoesNotSupportIPN($this, "Payment handler in order ({$this->getOrder(
            )->id}) must be an instance of IPkgShopPaymentIPNPaymentHandler", 0);
        }

        $this->paymentHandler = $oPaymentHandler;

        // add trigger
        $this->addTrigger($oMessage);
    }
104694
protected function getTransactionFromRequest(TPkgShopPaymentIPNRequest $oRequest)
    {
        $payload = $oRequest->getRequestPayload();

        /** @var $localIdObject IAmazonReferenceId */
        $localIdObject = $payload['amazonLocalReferenceId'];

        $transactionId = $localIdObject->getTransactionId();

        if (null === $transactionId) {
            throw new AmazonIPNTransactionException(AmazonIPNTransactionException::ERROR_NO_TRANSACTION,
                'there was no transaction connected to the IPN even thought that was expected', array('request' => $oRequest));
        }

        $transaction = \TdbPkgShopPaymentTransaction::GetNewInstance();
        if (false === $transaction->Load($transactionId)) {
            throw new AmazonIPNTransactionException(AmazonIPNTransactionException::ERROR_TRANSACTION_NOT_FOUND,
                'transaction id connected to the IPN is not in the database!', array(
                    'request' => $oRequest,
                    'transactionId' => $transactionId,
                ));
        }

        if ($transaction->fieldShopOrderId !== $oRequest->getOrder()->id) {
            throw new AmazonIPNTransactionException(AmazonIPNTransactionException::ERROR_TRANSACTION_DOES_NOT_MATCH_ORDER,
                'transaction found for the IPN is connected to another order!', array(
                    'request' => $oRequest,
                    'transaction' => $transaction,
                ));
        }

        return $transaction;
    }
857363
protected function addBcc(Mail\Message $oMessage)
    {
        if (isset($this->aRendererConfig['mail_bcc']) && is_array($this->aRendererConfig['mail_bcc'])) {
            foreach ($this->aRendererConfig['mail_bcc'] as $sBccAddress) {
                // Avoid sending email copy to "to" AND bcc
                $bFound = false;
                foreach ($oMessage->getTo() as $oTo) {
                    if ($oTo->getEmail() == $sBccAddress) {
                        $bFound = true;
                        break;
                    }
                }
                if (!$bFound) {
                    $oAddressListBcc = new Mail\AddressList();
                    $oAddressListBcc->add(
                        new Mail\Address($sBccAddress)
                    );
                    $oMessage->addBcc($oAddressListBcc);
                }
            }
        }

        return $this;
    }
406378
public function check( $what = MShop_Order_Item_Base_Abstract::PARTS_ALL )
	{
		$this->_checkParts( $what );

		$this->_notifyListeners( 'check.before', $what );

		if( ( $what & MShop_Order_Item_Base_Abstract::PARTS_PRODUCT ) && ( count($this->_products) < 1 ) ) {
			throw new MShop_Order_Exception( sprintf( 'Basket empty' ) );
		}

		$this->_notifyListeners( 'check.after', $what );
	}
300893
function _doCapt($oID, $amt = 0, $currency = 'USD') {
    global $db, $messageStack;

    //@TODO: Read current order status and determine best status to set this to
    $new_order_status = MODULE_PAYMENT_AUTHORIZENET_ECHECK_ORDER_STATUS_ID;
    if ($new_order_status == 0) $new_order_status = 1;

    $proceedToCapture = true;
    $captureNote = strip_tags(zen_db_input($_POST['captnote']));
    if (isset($_POST['captconfirm']) && $_POST['captconfirm'] == 'on') {
    } else {
      $messageStack->add_session(MODULE_PAYMENT_AUTHORIZENET_ECHECK_TEXT_CAPTURE_CONFIRM_ERROR, 'error');
      $proceedToCapture = false;
    }
    if (isset($_POST['btndocapture']) && $_POST['btndocapture'] == MODULE_PAYMENT_AUTHORIZENET_ECHECK_ENTRY_CAPTURE_BUTTON_TEXT) {
      $captureAmt = (float)$_POST['captamt'];
/*
      if ($captureAmt == 0) {
        $messageStack->add_session(MODULE_PAYMENT_AUTHORIZENET_ECHECK_TEXT_INVALID_CAPTURE_AMOUNT, 'error');
        $proceedToCapture = false;
      }
*/
    }
    if (isset($_POST['captauthid']) && trim($_POST['captauthid']) != '') {
      // okay to proceed
    } else {
      $messageStack->add_session(MODULE_PAYMENT_AUTHORIZENET_ECHECK_TEXT_TRANS_ID_REQUIRED_ERROR, 'error');
      $proceedToCapture = false;
    }
    /**
     * Submit capture request to Authorize.net
     */
    if ($proceedToCapture) {
      // Populate an array that contains all of the data to be sent to Authorize.net
      unset($submit_data);
      $submit_data = array(
                           'x_type' => 'PRIOR_AUTH_CAPTURE',
                           'x_amount' => number_format($captureAmt, 2),
                           'x_trans_id' => strip_tags(trim($_POST['captauthid'])),
//                         'x_invoice_num' => $new_order_id,
//                         'x_po_num' => $order->info['po_number'],
//                         'x_freight' => $order->info['shipping_cost'],
//                         'x_tax_exempt' => 'FALSE', /* 'TRUE' or 'FALSE' */
//                         'x_tax' => $order->info['tax'],
                           );

      $response = $this->_sendRequest($submit_data);
      $response_code = $response[0];
      $response_text = $response[3];
      $response_alert = $response_text . ($this->commError == '' ? '' : ' Communications Error - Please notify webmaster.');
      $this->reportable_submit_data['Note'] = $captureNote;
      $this->_debugActions($response);

      if ($response_code != '1' || ($response[0]==1 && $response[2] == 311) ) {
        $messageStack->add_session($response_alert, 'error');
      } else {
        // Success, so save the results
        $sql_data_array = array('orders_id' => (int)$oID,
                                'orders_status_id' => (int)$new_order_status,
                                'date_added' => 'now()',
                                'comments' => 'FUNDS COLLECTED. Auth Code: ' . $response[4] . "\n" . 'Trans ID: ' . $response[6] . "\n" . ' Amount: ' . ($response[9] == 0.00 ? 'Full Amount' : $response[9]) . "\n" . 'Time: ' . date('Y-m-D h:i:s') . "\n" . $captureNote,
                                'customer_notified' => 0
                             );
        zen_db_perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);
        $db->Execute("update " . TABLE_ORDERS  . "
                      set orders_status = '" . (int)$new_order_status . "'
                      where orders_id = '" . (int)$oID . "'");
        $messageStack->add_session(sprintf(MODULE_PAYMENT_AUTHORIZENET_ECHECK_TEXT_CAPT_INITIATED, ($response[9] == 0.00 ? 'Full Amount' : $response[9]), $response[6], $response[4]), 'success');
        return true;
      }
    }
    return false;
  }
662630
protected function throwNewInvalidArgumentException ($errorMsg) {
		$selfClass = version_compare(PHP_VERSION, '5.5', '>') ? self::class : __CLASS__;
		$str = '['.$selfClass.'] ' . $errorMsg . ' ('
			. 'form id: `'.$this->id . '`, '
			. 'form type: `'.get_class($this->form).'`'
		.')';
		throw new \InvalidArgumentException($str);
	}
174245
public function RemoveInvalidVouchers($sMessangerName, $oBasket = null)
    {
        // since the min value of the basket for which a voucher may work is affected by other vouchers,
        // we need to remove the vouchers first, and then add them one by one back to the basket
        // we suppress the add messages, but keep the negative messages

        if (is_null($oBasket)) {
            $oBasket = TShopBasket::GetInstance();
        }
        $oMessageManager = TCMSMessageManager::GetInstance();

        // get copy of vouchers
        $aVoucherList = $this->_items;
        $this->Destroy();
        $bInvalidVouchersFound = false;
        foreach ($aVoucherList as $iVoucherKey => $oVoucher) {
            /** @var $oVoucher TdbShopVoucher */
            $cVoucherAllowUseCode = $oVoucher->AllowUseOfVoucher();
            if (TdbShopVoucher::ALLOW_USE == $cVoucherAllowUseCode) {
                $this->AddItem($oVoucher);
            } else {
                $bInvalidVouchersFound = true;
                $this->RemoveInvalidVoucherHook($oVoucher, $oBasket);
                // send message that the voucher was removed
                $aMessageData = $oVoucher->GetObjectPropertiesAsArray();
                $aMessageData['iRemoveReasoneCode'] = $cVoucherAllowUseCode;
                $oMessageManager->AddMessage($sMessangerName, 'VOUCHER-ERROR-NO-LONGER-VALID-FOR-BASKET', $aMessageData);
            }
        }

        if ($bInvalidVouchersFound) {
            // recalculate the basket
            $oBasket->RecalculateBasket();
        }
    }
1286360
public function ValidateBasketContents($sMessageManager = null)
    {
        /*
         * do not validate basket if returning from an interrupted payment call since the order
         * creation has already begun (items saved, stock reduced). revalidating may remove items from the basket due to zero stock
         * which is of course not intended since the stock has been reserved via the creation process of the order
         *
         */
        if (TdbShopPaymentHandler::ExecutePaymentInterrupted()) {
            return true;
        }
        if (is_null($sMessageManager)) {
            $sMessageManager = MTShopBasketCore::MSG_CONSUMER_NAME;
        }
        $this->GetBasketArticles()->Refresh();
        $bIsValid = $this->GetBasketArticles()->ValidateBasketContents($sMessageManager);
        /**
         * validate the vouchers as they were stored in the session and
         * maybe could be used by an other order (when vouchers with the same code exist).
         */
        $bBasketVouchersValidated = $this->CheckBasketVoucherAvailable($sMessageManager);
        if (!$bIsValid) {
            $this->RecalculateBasket();
        }

        return $bIsValid;
    }
527223
public function validateOrder($oBasket, $oUser)
    {
        // validating stock
        $iValidState = $this->validateStock($oBasket);

        if (!$iValidState) {
            // validating delivery
            $iValidState = $this->validateDelivery($oBasket);
        }

        if (!$iValidState) {
            // validating payment
            $iValidState = $this->validatePayment($oBasket);
        }

        if (!$iValidState) {
            //0003110 validating delivery address, it is not be changed during checkout process
            $iValidState = $this->validateDeliveryAddress($oUser);
        }

        if (!$iValidState) {
            // validating minimum price
            $iValidState = $this->validateBasket($oBasket);
        }

        return $iValidState;
    }
440050
protected function SendFailureSettlementMail(TdbShopOrder &$oOrder)
    {
        $bSendMail = false;
        $oMail = TdbDataMailProfile::GetProfile('payment_datatrans_error_settlement');
        if (!is_null($oMail)) {
            $sInfo = TGlobal::OutHTML(TGlobal::Translate('chameleon_system_shop.payment_data_trans.settlement_failure_mail_info',
                    array(
                        '%ordernumber%' => $oOrder->fieldOrdernumber,
                        '%ref%' => $this->GetRefNoParameter(false),
                    )
                ));
            $oMail->AddData('sInfo', $sInfo);
            $bSendMail = $oMail->SendUsingObjectView('emails', 'Customer');
        }

        return $bSendMail;
    }
714499
protected function addAvailabilityErrorToCheckoutResponse(CheckoutResponseTransfer $checkoutResponse, string $sku): void
    {
        $checkoutErrorTransfer = $this->createCheckoutErrorTransfer();

        $checkoutErrorTransfer
            ->setErrorCode($this->conditionalAvailabilityConfig->getProductUnavailableErrorCode())
            ->setMessage(static::CHECKOUT_PRODUCT_UNAVAILABLE_TRANSLATION_KEY)
            ->setErrorType(
                $this->conditionalAvailabilityConfig->getAvailabilityErrorType()
            )
            ->setParameters([
                $this->conditionalAvailabilityConfig->getAvailabilityProductSkuParameter() => $sku,
            ]);

        $checkoutResponse
            ->addError($checkoutErrorTransfer)
            ->setIsSuccess(false);
    }
1032824
public function setPaymentMethod($method)
    {
        try {
            if ($method instanceof PagSeguroDirectPaymentMethods) {
                $this->paymentMethod = $method;
            } else {
                $this->paymentMethod = new PagSeguroDirectPaymentMethods($method);
            }
        } catch (Exception $e) {
            die($e->getMessage());
        }
    }
968431
public function onCharge($order)
    {
        if (!isset($this->omnipay))
            throw new ShopException('Omnipay gateway not set.', 0);

        try {

            $response = $this->omnipay->purchase(array_merge([
                'amount'    => $order->total,
                'currency'  => Config::get('shop.currency'),
                'card'      => $this->isCreditCard ? $this->creditCard : [],
                'returnUrl' => $this->callbackSuccess,
                'cancelUrl' => $this->callbackFail,
            ], $this->options))->send();

            if ($response->isSuccessful()) {

                $this->transactionId = $response->getTransactionReference();

                $this->detail = 'Success';


            } elseif ($response->isRedirect()) {

                $this->statusCode = 'pending';

                $this->approvalUrl = $response->getRedirectUrl();

                $this->detail = sprintf('Pending approval: %s', $response->getRedirectUrl());

            } else {

                throw new GatewayException($response->getMessage(), 1);

            }

            return true;

        } catch (Exception $e) {

            throw new ShopException(
                $e->getMessage(),
                1000,
                $e
            );

        }

        return false;
    }
191618
public function onCallbackSuccess($order, $data = null)
    {
        $paymentId  = is_array($data) ? $data['paymentId'] : $data->paymentId;

        $payerId    = is_array($data) ? $data['PayerID'] : $data->PayerID;

        $this->statusCode = 'failed';

        $this->detail = sprintf('Payment failed. Ref: %s', $paymentId);

        // Begin paypal
        try {

            $this->setContext();

            $payment = Payment::get($paymentId, $this->apiContext);
            
            $execution = new PaymentExecution();

            $execution->setPayerId($payerId);

            $payment->execute($execution, $this->apiContext);

            $payment = Payment::get($paymentId, $this->apiContext);

            $this->statusCode = 'completed';

            $this->transactionId = $payment->id;

            $this->detail = 'Success';

        } catch (PayPalConnectionException $e) {

            $response = json_decode($e->getData());

            throw new GatewayException(
                sprintf(
                    '%s: %s',
                    $response->name,
                    isset($response->message) ? $response->message : 'Paypal payment Failed.'
                ),
                1001,
                $e
            );

        } catch (\Exception $e) {

            throw new GatewayException(
                $e->getMessage(),
                1000,
                $e
            );

        }
    }
901972
protected function ExecuteDataTransPaymentCall(TdbShopOrder &$oOrder)
    {
        $sXMLSettlement = $this->GetXMLSettlement();
        $ch = curl_init();
        $settlementurl = trim($this->GetTestLiveModeParameter('settlementurl'));
        curl_setopt($ch, CURLOPT_URL, $settlementurl);
        curl_setopt($ch, CURLOPT_VERBOSE, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, 'xmlRequest='.$sXMLSettlement);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        $sResponse = curl_exec($ch);
        $sCurlError = curl_error($ch);
        $bPaymentOk = $this->SettlementResponseSuccess($sResponse);
        if (!$bPaymentOk) {
            if (!empty($sCurlError)) {
                TTools::WriteLogEntrySimple('Payment DataTrans: curl failed to ['.$this->GetConfigParameter('settlementurl')."] using xml [{$sXMLSettlement}] with error: ".$sCurlError, 1, __FILE__, __LINE__);
            }
            $iFailure = $this->GetConfigParameter('failure_settlement');
            if ('1' === $iFailure) {
                if ($this->SendFailureSettlementMail($oOrder)) {
                    $bPaymentOk = true;
                } else {
                    TTools::WriteLogEntrySimple('Payment DataTrans: Es konnte keine Abbuchungsfehlere-mail versand werden', 1, __FILE__, __LINE__);
                }
            }
        }
        curl_close($ch);

        return $bPaymentOk;
    }
1342560
public function SendOrderNotification($sSendToMail = null, $sSendToName = null)
    {
        $bOrderSend = false;

        if (is_null($sSendToMail)) {
            $sSendToMail = $this->fieldUserEmail;
        }
        if (is_null($sSendToName)) {
            $sSendToName = $this->fieldAdrBillingFirstname.' '.$this->fieldAdrBillingLastname;
        }

        $oMail = $this->GetOrderNotificationEmailProfile(self::MAIL_CONFIRM_ORDER);

        TCMSImage::ForceNonSSLURLs(true); // force image urls to non ssl for use in order email
        if (is_null($oMail)) {
            $bOrderSend = TGlobal::Translate('chameleon_system_shop.order_notification.error_mail_template_not_found', array('%emailTemplate%' => self::MAIL_CONFIRM_ORDER));
        } else {
            $aMailData = $this->sqlData;
            $aMailData = $this->AddOrderNotificationEmailData($aMailData);
            $aMailData = $this->AddOrderNotificationEmailComplexData($aMailData);
            $oMail->AddDataArray($aMailData);
            $aOrderDetails = $this->GetSQLWithTablePrefix();
            $oMail->AddDataArray($aOrderDetails);
            $oMail->ChangeToAddress($sSendToMail, $sSendToName);
            $bOrderSend = $oMail->SendUsingObjectView('emails', 'Customer');
            $this->SaveOrderNotificationDataToOrder($bOrderSend, $oMail, $sSendToMail);
        }
        TCMSImage::ForceNonSSLURLs(false); // reset - force non ssl urls

        return $bOrderSend;
    }
1311307
public function processCancel(Session $session, CancelMessage $msg)
    {
        if ($this->getCallerSession() !== $session) {
            Logger::warning($this, 'session attempted to cancel call they did not own.');
            return false;
        }

        if ($this->getCalleeSession() === null) {
            // this call has not been sent to a callee yet (it is in a queue)
            // we can just kill it and say it was canceled
            $errorMsg                             = ErrorMessage::createErrorMessageFromMessage($msg, 'wamp.error.canceled');
            $details                              = $errorMsg->getDetails() ?: (object)[];
            $details->_thruway_removed_from_queue = true;
            $session->sendMessage($errorMsg);
            return true;
        }

        $details = (object)[];
        if ($this->getCalleeSession()->getHelloMessage() instanceof HelloMessage) {
            $details = $this->getCalleeSession()->getHelloMessage()->getDetails();
        }
        $calleeSupportsCancel = false;
        if (isset($details->roles->callee->features->call_canceling)
            && is_scalar($details->roles->callee->features->call_canceling)) {
            $calleeSupportsCancel = (bool)$details->roles->callee->features->call_canceling;
        }

        if (!$calleeSupportsCancel) {
            $errorMsg = ErrorMessage::createErrorMessageFromMessage($msg);
            $errorMsg->setErrorURI('wamp.error.not_supported');
            $session->sendMessage($errorMsg);
            return false;
        }

        $this->setCancelMessage($msg);

        $this->canceling = true;

        $calleeSession = $this->getCalleeSession();

        $interruptMessage = new InterruptMessage($this->getInvocationRequestId(), (object)[]);
        $calleeSession->sendMessage($interruptMessage);
        $this->setInterruptMessage($interruptMessage);

        if (isset($msg->getOptions()->mode) && is_scalar($msg->getOptions()->mode) && $msg->getOptions()->mode === 'killnowait') {
            $errorMsg = ErrorMessage::createErrorMessageFromMessage($msg, 'wamp.error.canceled');
            $session->sendMessage($errorMsg);

            return true;
        }

        return false;
    }