Places the order after a PAYMENT_SUCCESSFUL from
@see initiateAction or
@see checkStatusAction
@return string
338808
public function placeOrderAction()
    {
        $quote = (Mage::getModel('checkout/type_onepage') !== false) ? Mage::getModel('checkout/type_onepage')->getQuote() : Mage::getModel('checkout/session')->getQuote();
        $service = Mage::getModel('sales/service_quote', $quote);

        $quote->getPayment()->setMethod('adyen_pos_cloud');
        $quote->collectTotals()->save();
        try {
            $service->submitAll();
            $order = $service->getOrder();
            $order->save();

            $result = self::ORDER_SUCCESS;

            // add order information to the session
            $session = Mage::getSingleton('checkout/session');
            $session->setLastOrderId($order->getId());
            $session->setLastRealOrderId($order->getIncrementId());
            $session->setLastSuccessQuoteId($order->getQuoteId());
            $session->setLastQuoteId($order->getQuoteId());
            $session->unsAdyenRealOrderId();
            $session->setQuoteId($session->getAdyenQuoteId(true));
            $session->getQuote()->setIsActive(false)->save();
        } catch (Exception $e) {
            Mage::logException($e);
            $result = self::ORDER_ERROR;
        }

        $this->getResponse()->setHeader('Content-type', 'application/json');
        $this->getResponse()->setBody($result);
        return $result;
    }
883534
function ec_step1() {
    global $order, $order_totals, $db, $doPayPal;

    // if cart is empty due to timeout on login or shopping cart page, go to timeout screen
    if ($_SESSION['cart']->count_contents() == 0) {
      $message = 'Logging out due to empty shopping cart.  Is session started properly? ... ' . "\nSESSION Details:\n" . print_r($_SESSION, TRUE) . 'GET:' . "\n" . print_r($_GET, TRUE);
      include_once(DIR_WS_MODULES . 'payment/paypal/paypal_functions.php');
      ipn_debug_email($message);
      zen_redirect(zen_href_link(FILENAME_TIME_OUT, '', 'SSL'));
    }

    // init new order object
    require(DIR_WS_CLASSES . 'order.php');
    $order = new order;

    // load the selected shipping module so that shipping taxes can be assessed
    require(DIR_WS_CLASSES . 'shipping.php');
    $shipping_modules = new shipping($_SESSION['shipping']);

    // load OT modules so that discounts and taxes can be assessed
    require(DIR_WS_CLASSES . 'order_total.php');
    $order_total_modules = new order_total;
    $order_totals = $order_total_modules->pre_confirmation_check();
    $order_totals = $order_total_modules->process();

    $doPayPal = $this->paypal_init();
    $options = array();

    // build line item details
    $options = $this->getLineItemDetails($this->selectCurrency());

    // Set currency and amount
    $options['CURRENCYCODE'] = $this->selectCurrency();
    $order_amount = $this->calc_order_amount($order->info['total'], $options['CURRENCYCODE']);

    // Determine the language to use when visiting the PP site
    $lc_code = $this->getLanguageCode();
    if ($lc_code != '') $options['LOCALECODE'] = $lc_code;

    // Allow delayed payments such as eCheck?
    if (defined('MODULE_PAYMENT_PAYPALEC_ALLOWEDPAYMENT') && MODULE_PAYMENT_PAYPALEC_ALLOWEDPAYMENT == 'Instant Only') $options['ALLOWEDPAYMENTMETHOD'] = 'InstantPaymentOnly';

    //Gift Options
    $options['GIFTMESSAGEENABLE'] = 0;
    $options['GIFTRECEIPTEENABLE'] = 0;
    $options['GIFTWRAPENABLE'] = 0;
    $options['GIFTWRAPNAME'] = '';
    $options['GIFTWRAPAMOUNT'] = 0;

    $options['BUYEREMAILOPTINENABLE'] = 0;

    $options['CUSTOMERSERVICENUMBER'] = (defined('STORE_TELEPHONE_CUSTSERVICE') && STORE_TELEPHONE_CUSTSERVICE != '') ? substr(STORE_TELEPHONE_CUSTSERVICE, 0, 16) : '';

    // Store Name to appear on PayPal page
    $options['BRANDNAME'] = (defined('MODULE_PAYMENT_PAYPALWPP_BRANDNAME') && strlen(MODULE_PAYMENT_PAYPALWPP_BRANDNAME) > 3) ? substr(MODULE_PAYMENT_PAYPALWPP_BRANDNAME, 0, 127) : substr(STORE_NAME, 0, 127);

    // Payment Transaction/Authorization Mode
    $options['PAYMENTACTION'] = (MODULE_PAYMENT_PAYPALWPP_TRANSACTION_MODE == 'Auth Only') ? 'Authorization' : 'Sale';
    // for future:
    if (MODULE_PAYMENT_PAYPALWPP_TRANSACTION_MODE == 'Order') $options['PAYMENTACTION'] = 'Order';

    $options['ALLOWNOTE'] = 1;  // allow customer to enter a note on the PayPal site, which will be copied to order comments upon return to store.
    $options['SOLUTIONTYPE'] = 'Sole';  // Use 'Mark' for normal Express Checkout, 'Sole' for auctions or alternate flow
    $options['LANDINGPAGE'] = 'Billing';  // "Billing" or "Login" selects the style of landing page on PayPal site during checkout

    // Set the return URL if they click "Submit" on PayPal site
    $return_url = str_replace('&amp;', '&', zen_href_link('ipn_main_handler.php', 'type=ec', 'SSL', true, true, true));
    // Select the return URL if they click "cancel" on PayPal site or click to return without making payment or login
    $cancel_url = str_replace('&amp;', '&', zen_href_link(($_SESSION['customer_first_name'] != '' && $_SESSION['customer_id'] != '' ? FILENAME_CHECKOUT_SHIPPING : FILENAME_SHOPPING_CART), 'ec_cancel=1', 'SSL'));

    // debug
    $val = $_SESSION; unset($val['navigation']);
    $this->zcLog('ec_step1 - 1', 'Checking to see if we are in markflow' . "\n" . 'cart contents: ' . $_SESSION['cart']->get_content_type() . "\n\nNOTE: " . '$this->showPaymentPage = ' . (int)$this->showPaymentPage . "\nCustomer ID: " . (int)$_SESSION['customer_id'] . "\nSession Data: " . print_r($val, true));

    /**
     * Check whether shipping is required on this order or not.
     * If not, tell PayPal to skip all shipping options
     * ie: don't ask for any shipping info if cart content is strictly virtual and customer is already logged-in
     * (if not logged in, we need address information only to build the customer record)
     */
    if ($_SESSION['cart']->get_content_type() == 'virtual' && isset($_SESSION['customer_id']) && $_SESSION['customer_id'] > 0) {
      $this->zcLog('ec-step1-addr_check', "cart contents is virtual and customer is logged in ... therefore options['NOSHIPPING']=1");
      $options['NOSHIPPING'] = 1;
    } else {
      $this->zcLog('ec-step1-addr_check', "cart content is not all virtual (or customer is not logged in) ... therefore will be submitting address details");
      $options['NOSHIPPING'] = 0;
      // If we are in a "mark" flow and the customer has a usable address, set the addressoverride variable to 1. This will
      // override the shipping address in PayPal with the shipping address that is selected in Zen Cart.
      // @TODO: consider using address-validation against Paypal's addresses via API
      if (MODULE_PAYMENT_PAYPALWPP_CONFIRMED_ADDRESS != 'Yes' && ($address_arr = $this->getOverrideAddress()) !== false) {
        $address_error = false;
        foreach(array('entry_firstname','entry_lastname','entry_street_address','entry_city','entry_postcode','zone_code','countries_iso_code_2') as $val) {
          if ($address_arr[$val] == '') $address_error = true;
          if ($address_error == true) $this->zcLog('ec-step1-addr_check2', '$address_error = true because ' .$val . ' is blank.');
        }
        if ($address_error == false) {
          // set the override var
          $options['ADDROVERRIDE'] = 1;

          // set the address info
          $options['SHIPTONAME']    = substr($address_arr['entry_firstname'] . ' ' . $address_arr['entry_lastname'], 0, 32);
          $options['SHIPTOSTREET']  = substr($address_arr['entry_street_address'], 0, 100);
          if ($address_arr['entry_suburb'] != '') $options['SHIPTOSTREET2'] = substr($address_arr['entry_suburb'], 0, 100);
          $options['SHIPTOCITY']    = substr($address_arr['entry_city'], 0, 40);
          $options['SHIPTOZIP']     = substr($address_arr['entry_postcode'], 0, 20);
          $options['SHIPTOSTATE']   = substr($address_arr['zone_code'], 0, 40);
          $options['SHIPTOCOUNTRYCODE'] = substr($address_arr['countries_iso_code_2'], 0, 2);
          $options['SHIPTOPHONENUM'] = substr($address_arr['entry_telephone'], 0, 20);
        }
      }
      $this->zcLog('ec-step1-addr_check3', 'address details from override check:'.($address_arr == FALSE ? ' <NONE FOUND>' : print_r($address_arr, true)));

      // Do we require a "confirmed" shipping address ?
      if (MODULE_PAYMENT_PAYPALWPP_CONFIRMED_ADDRESS == 'Yes') {
        $options['REQCONFIRMSHIPPING'] = 1;
      }
    }
    // if we know customer's email address, supply it, so as to pre-fill the signup box at PayPal (useful for new PayPal accounts only)
    if (!empty($_SESSION['customer_first_name']) && !empty($_SESSION['customer_id'])) {
      $sql = "select * from " . TABLE_CUSTOMERS . " where customers_id = :custID ";
      $sql = $db->bindVars($sql, ':custID', $_SESSION['customer_id'], 'integer');
      $zc_getemail = $db->Execute($sql);
      if ($zc_getemail->RecordCount() > 0 && $zc_getemail->fields['customers_email_address'] != '') {
        $options['EMAIL'] = $zc_getemail->fields['customers_email_address'];
      }
      if ($zc_getemail->RecordCount() > 0 && $zc_getemail->fields['customers_telephone'] != '' && (!isset($options['ADDROVERRIDE']) || isset($options['ADDROVERRIDE']) && $options['ADDROVERRIDE'] != 1)) {
        $options['SHIPTOPHONENUM'] = $zc_getemail->fields['customers_telephone'];
      }
    }

    if (!isset($options['AMT'])) $options['AMT'] = number_format($order_amount, 2);

    $this->zcLog('ec_step1 - 2 -submit', print_r(array_merge($options, array('RETURNURL' => $return_url, 'CANCELURL' => $cancel_url)), true));

    /**
     * Ask PayPal for the token with which to initiate communications
     */
    $response = $doPayPal->SetExpressCheckout($return_url, $cancel_url, $options);


  $submissionCheckOne = TRUE;
  $submissionCheckTwo = TRUE;
  if ($submissionCheckOne) {
    // If there's an error on line-item details, remove tax values and resubmit, since the most common cause of 10413 is tax mismatches
    if ($response['L_ERRORCODE0'] == '10413') {
      $this->zcLog('ec_step1 - 3 - removing tax portion', 'Tax Subtotal does not match sum of taxes for line-items. Tax details removed from line-item submission data.' . "\n" . print_r($options, true));
          //echo '1st submission REJECTED. {'.$response['L_ERRORCODE0'].'}<pre>'.print_r($options, true) . urldecode(print_r($response, true));
      $tsubtotal = 0;
      foreach ($options as $key=>$value) {
        if (substr($key, 0, 8) == 'L_TAXAMT') {
          $tsubtotal += preg_replace('/[^0-9.\-]/', '', $value);
          unset($options[$key]);
        }
      }
      $options['TAXAMT'] = $tsubtotal;
      $amt = preg_replace('/[^0-9.%]/', '', $options['AMT']);
//      echo 'oldAMT:'.$amt;
//      echo ' newTAXAMT:'.$tsubtotal;
      $taxamt = preg_replace('/[^0-9.%]/', '', $options['TAXAMT']);
      $shipamt = preg_replace('/[^0-9.%]/', '', $options['SHIPPINGAMT']);
      $itemamt = preg_replace('/[^0-9.%]/', '', $options['ITEMAMT']);
      $calculatedAmount = $itemamt + $taxamt + $shipamt;
      if ($amt != $calculatedAmount) $amt = $calculatedAmount;
//      echo ' newAMT:'.$amt;
      $options['AMT'] = $amt;
      $response = $doPayPal->SetExpressCheckout($return_url, $cancel_url, $options);
//echo '<br>2nd submission. {'.$response['L_ERRORCODE0'].'}<pre>'.print_r($options, true);
    }
    if ($submissionCheckTwo) {
    if ($response['L_ERRORCODE0'] == '10413') {
      $this->zcLog('ec_step1 - 4 - removing line-item details', 'PayPal designed their own mathematics rules. Dumbing it down for them.' . "\n" . print_r($options, true));
//echo '2nd submission REJECTED. {'.$response['L_ERRORCODE0'].'}<pre>'.print_r($options, true) . urldecode(print_r($response, true));
      foreach ($options as $key=>$value) {
        if (substr($key, 0, 2) == 'L_') {
          unset($options[$key]);
        }
      }
      $amt = preg_replace('/[^0-9.%]/', '', $options['AMT']);
      $taxamt = preg_replace('/[^0-9.%]/', '', $options['TAXAMT']);
      $shipamt = preg_replace('/[^0-9.%]/', '', $options['SHIPPINGAMT']);
      $itemamt = preg_replace('/[^0-9.%]/', '', $options['ITEMAMT']);
      $calculatedAmount = $itemamt + $taxamt + $shipamt;
      if ($amt != $calculatedAmount) $amt = $calculatedAmount;
      $options['AMT'] = $amt;
      $response = $doPayPal->SetExpressCheckout($return_url, $cancel_url, $options);
//echo '<br>3rd submission. {'.$response['L_ERRORCODE0'].'}<pre>'.print_r($options, true);
    }
   }
  }

    /**
     * Determine result of request for token -- if error occurred, the errorHandler will redirect accordingly
     */
    $error = $this->_errorHandler($response, 'SetExpressCheckout');

    // Success, so read the EC token
    $_SESSION['paypal_ec_token'] = preg_replace('/[^0-9.A-Z\-]/', '', urldecode($response['TOKEN']));

    // prepare to redirect to PayPal so the customer can log in and make their selections
    $paypal_url = $this->getPayPalLoginServer();

    // Set the name of the displayed "continue" button on the PayPal site.
    // 'commit' = "Pay Now"  ||  'continue' = "Review Payment"
    $orderReview = true;
    if ($_SESSION['paypal_ec_markflow'] == 1) $orderReview = false;
    $userActionKey = "&useraction=" . ((int)$orderReview == false ? 'commit' : 'continue');

    // This is where we actually redirect the customer's browser to PayPal. Upon return from PayPal, they go to ec_step2
    header("HTTP/1.1 302 Object Moved");
    zen_redirect($paypal_url . "?cmd=_express-checkout&token=" . $_SESSION['paypal_ec_token'] . $userActionKey);

    // this should never be reached:
    return $error;
  }
421742
protected function getOrderPaymentStatusPayments()
    {
        $status = 'completed';
        $paymentList = $this->getOrder()->getPaymentList();

        if ($paymentList->hasPendingPayment()) {
            $status = 'pending';
        } elseif ($paymentList->hasFailedPayment()) {
            $status = 'failed';
        }

        return $status;
    }
897120
function after_process() {
    global $insert_id, $db, $order;
    // FMF
    if ($this->fmfResponse != '') {
      $detailedMessage = $insert_id . "\n" . $this->fmfResponse . "\n" . MODULES_PAYMENT_PAYPALDP_TEXT_EMAIL_FMF_INTRO . "\n" . print_r($this->fmfErrors, TRUE);
      zen_mail(STORE_NAME, STORE_OWNER_EMAIL_ADDRESS, MODULES_PAYMENT_PAYPALDP_TEXT_EMAIL_FMF_SUBJECT . ' (' . $insert_id . ')', $detailedMessage, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, array('EMAIL_MESSAGE_HTML'=>nl2br($detailedMessage)), 'paymentalert');
    }

    // add a new OSH record for this order's PP details
    $commentString = "Transaction ID: :transID: " .
                     (isset($this->responsedata['PPREF']) ? "\nPPRef: " . $this->responsedata['PPREF'] : "") .
                     (isset($this->responsedata['AUTHCODE'])? "\nAuthCode: " . $this->responsedata['AUTHCODE'] : "") .
                                 "\nPayment Type: :pmtType: " .
                     ($this->payment_time != '' ? "\nTimestamp: :pmtTime: " : "") .
                                 "\nPayment Status: :pmtStatus: " .
                     (isset($this->responsedata['auth_exp']) ? "\nAuth-Exp: " . $this->responsedata['auth_exp'] : "") .
                     ($this->avs != 'N/A' ? "\nAVS Code: ".$this->avs."\nCVV2 Code: ".$this->cvv2 : '') .
                     (trim($this->amt) != '' ? "\nAmount: :orderAmt: " : "");
    $commentString = $db->bindVars($commentString, ':transID:', $this->transaction_id, 'noquotestring');
    $commentString = $db->bindVars($commentString, ':pmtType:', $this->payment_type, 'noquotestring');
    $commentString = $db->bindVars($commentString, ':pmtTime:', $this->payment_time, 'noquotestring');
    $commentString = $db->bindVars($commentString, ':pmtStatus:', $this->payment_status, 'noquotestring');
    $commentString = $db->bindVars($commentString, ':orderAmt:', $this->amt, 'noquotestring');

    $sql_data_array= array(array('fieldName'=>'orders_id', 'value'=>$insert_id, 'type'=>'integer'),
                           array('fieldName'=>'orders_status_id', 'value'=>$order->info['order_status'], 'type'=>'integer'),
                           array('fieldName'=>'date_added', 'value'=>'now()', 'type'=>'noquotestring'),
                           array('fieldName'=>'customer_notified', 'value'=>0, 'type'=>'integer'),
                           array('fieldName'=>'comments', 'value'=>$commentString, 'type'=>'string'));
    $db->perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);

    // 3D-Secure
    if ($this->requiresLookup($order->info['cc_type']) == true) {
      // CardinalCommerce Liability Protection Status
      // Inserts 'PROTECTED' or 'NOT PROTECTED' status, ECI, CAVV values in the order status history comments
      $auth_proc_status = $this->determine3DSecureProtection($order->info['cc_type'], $_SESSION['3Dsecure_auth_eci']);
      $commentString = "3D-Secure: " . $auth_proc_status . "\n" . 'ECI Value = ' . $_SESSION['3Dsecure_auth_eci'] . "\n" . 'CAVV Value = ' . $_SESSION['3Dsecure_auth_cavv'];
      $sql_data_array= array(array('fieldName'=>'orders_id', 'value'=> $insert_id, 'type'=>'integer'),
                             array('fieldName'=>'orders_status_id', 'value'=> $order->info['order_status'], 'type'=>'integer'),
                             array('fieldName'=>'date_added', 'value'=>'now()', 'type'=>'noquotestring'),
                             array('fieldName'=>'customer_notified', 'value'=> -1, 'type'=>'integer'),
                             array('fieldName'=>'comments', 'value'=> $commentString, 'type'=>'string'));
      $db->perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);
    }

    // store the PayPal order meta data -- used for later matching and back-end processing activities
    $paypal_order = array('order_id' => $insert_id,
                          'txn_type' => $this->transactiontype,
                          'module_name' => $this->code,
                          'module_mode' => MODULE_PAYMENT_PAYPALDP_MERCHANT_COUNTRY,
                          'reason_code' => $this->reasoncode,
                          'payment_type' => $this->payment_type,
                          'payment_status' => $this->payment_status,
                          'pending_reason' => $this->pendingreason,
                          'invoice' => urldecode($_SESSION['paypal_ec_token'] . $this->responsedata['PPREF']),
                          'first_name' => $_SESSION['paypal_ec_payer_info']['payer_firstname'],
                          'last_name' => $_SESSION['paypal_ec_payer_info']['payer_lastname'],
                          'payer_business_name' => $_SESSION['paypal_ec_payer_info']['payer_business'],
                          'address_name' => $_SESSION['paypal_ec_payer_info']['ship_name'],
                          'address_street' => $_SESSION['paypal_ec_payer_info']['ship_street_1'],
                          'address_city' => $_SESSION['paypal_ec_payer_info']['ship_city'],
                          'address_state' => $_SESSION['paypal_ec_payer_info']['ship_state'],
                          'address_zip' => $_SESSION['paypal_ec_payer_info']['ship_postal_code'],
                          'address_country' => $_SESSION['paypal_ec_payer_info']['ship_country'],
                          'address_status' => $_SESSION['paypal_ec_payer_info']['ship_address_status'],
                          'payer_email' => $_SESSION['paypal_ec_payer_info']['payer_email'],
                          'payer_id' => $_SESSION['paypal_ec_payer_id'],
                          'payer_status' => $_SESSION['paypal_ec_payer_info']['payer_status'],
                          'payment_date' => trim(preg_replace('/[^0-9-:]/', ' ', $this->payment_time)),
                          'business' => '',
                          'receiver_email' => (MODULE_PAYMENT_PAYPALWPP_PFVENDOR != '' ? MODULE_PAYMENT_PAYPALWPP_PFVENDOR : str_replace('_api1', '', MODULE_PAYMENT_PAYPALWPP_APIUSERNAME)),
                          'receiver_id' => '',
                          'txn_id' => $this->transaction_id,
                          'parent_txn_id' => '',
                          'num_cart_items' => (float)$this->numitems,
                          'mc_gross' => (float)$this->amt,
                          'mc_fee' => (float)urldecode($this->feeamt),
                          'mc_currency' => $this->responsedata['CURRENCYCODE'],
                          'settle_amount' => (float)urldecode($this->responsedata['SETTLEAMT']),
                          'settle_currency' => $this->responsedata['CURRENCYCODE'],
                          'exchange_rate' => (urldecode($this->responsedata['EXCHANGERATE']) > 0 ? urldecode($this->responsedata['EXCHANGERATE']) : 1.0),
                          'notify_version' => '0',
                          'verify_sign' =>'',
                          'date_added' => 'now()',
                          'memo' => (sizeof($this->fmfErrors) > 0 ? 'FMF Details ' . print_r($this->fmfErrors, TRUE) : '{Record generated by payment module}'),
                         );
    zen_db_perform(TABLE_PAYPAL, $paypal_order);

    // Unregister the paypal session variables, making it necessary to start again for another purchase
    unset($_SESSION['paypal_ec_temp']);
    unset($_SESSION['paypal_ec_token']);
    unset($_SESSION['paypal_ec_payer_id']);
    unset($_SESSION['paypal_ec_payer_info']);
    unset($_SESSION['paypal_ec_final']);
    unset($_SESSION['paypal_ec_markflow']);
    $this->clear_3DSecure_session_vars(TRUE);
  }
857697
function before_process() {
    global $order, $order_totals, $db, $messageStack, $lp_avs, $lp_trans_num;
    $myorder = array();

    // Calculate the next expected order id
    $last_order_id = $db->Execute("select * from " . TABLE_ORDERS . " order by orders_id desc limit 1");
    $new_order_id = $last_order_id->fields['orders_id'];
    $new_order_id = ($new_order_id + 1);
    // add randomized suffix to order id to produce uniqueness ... since it's unwise to submit the same order-number twice to the gateway
    $new_order_id = (string)$new_order_id . '-' . zen_create_random_value(6);

    // Build Info to send to Gateway
    $myorder["result"] = "LIVE";
    switch (MODULE_PAYMENT_LINKPOINT_API_TRANSACTION_MODE_RESPONSE) {
      case "TESTING: Successful": $myorder["result"] = "GOOD"; break;
      case "TESTING: Decline"   : $myorder["result"] = "DECLINE"; break;
      case "TESTING: Duplicate" : $myorder["result"] = "DUPLICATE"; break;
    }

    // "oid" - Order ID number must be unique. If not set, gateway will assign one.
    //$oid = zen_create_random_value(16, 'digits'); // Create a UID for the order
    $myorder["oid"] = $new_order_id; //"";    // time(); ????

    // prepare totals for submission
    $surcharges = 0;
    $creditsApplied = 0;
    global $order_totals;
    reset($order_totals);
    $myorder['subtotal'] = $myorder['tax'] = $myorder['shipping'] = $myorder['chargetotal'] = 0;
    for ($i=0, $n=sizeof($order_totals); $i<$n; $i++) {
      if ($order_totals[$i]['code'] == '') continue;
      if (in_array($order_totals[$i]['code'], array('ot_total','ot_subtotal','ot_tax','ot_shipping'))) {
        if ($order_totals[$i]['code'] == 'ot_subtotal') $myorder["subtotal"]    = round($order_totals[$i]['value'],2);
        if ($order_totals[$i]['code'] == 'ot_tax')      $myorder["tax"]        += round($order_totals[$i]['value'],2);
        if ($order_totals[$i]['code'] == 'ot_shipping') $myorder["shipping"]    = round($order_totals[$i]['value'],2);
        if ($order_totals[$i]['code'] == 'ot_total')    $myorder["chargetotal"] = round($order_totals[$i]['value'],2);
      } else {
        global $$order_totals[$i]['code'];
        if (substr($order_totals[$i]['text'], 0, 1) == '-' || (isset($$order_totals[$i]['code']->credit_class) && $$order_totals[$i]['code']->credit_class == true)) {
          $creditsApplied += round($order_totals[$i]['value'],2);
        } else {
          $surcharges += round($order_totals[$i]['value'],2);
        }
      }
    }
    foreach(array('subtotal', 'tax', 'chargetotal', 'shipping') as $i) {
      if (isset($myorder[$i])) $myorder[$i] = number_format($myorder[$i], 2, '.', '');
    }

    if ($surcharges == 0 && $creditsApplied == 0 && $order->info['total'] >= $order->info['subtotal'] && sizeof($order->products) <= 20) {
    // itemized contents
      $num_line_items = 0;
      reset($order->products);
      for ($i=0, $n=sizeof($order->products); $i<$n; $i++) {
        $num_line_items++;
        $myorder["items"][$num_line_items]['id']          = $order->products[$i]['id'];

        $myorder["items"][$num_line_items]['description'] = substr(htmlentities($order->products[$i]['name'], ENT_QUOTES, 'UTF-8'), 0, 128);
        $myorder["items"][$num_line_items]['quantity']    = $order->products[$i]['qty'];
        $myorder["items"][$num_line_items]['price']       = number_format(zen_add_tax($order->products[$i]['final_price'], $order->products[$i]['tax']), 2, '.', '');
        // check and adjust for fractional quantities, which cannot be submitted as line-item details
        $q = $order->products[$i]['qty']; $q1 = strval($q); $q2 = (int)$q; $q3 = strval($q2);
        if ($q1 != $q3 || $myorder["items"][$num_line_items]['quantity'] * $myorder["items"][$num_line_items]['price'] != number_format($order->products[$i]['qty'] * $order->products[$i]['final_price'], 2, '.', '')) {
          $myorder["items"][$num_line_items]['quantity']    = 1;
          $myorder["items"][$num_line_items]['price']       = number_format(zen_round(zen_add_tax($order->products[$i]['final_price'], $order->products[$i]['tax']), $decimals) * $order->products[$i]['qty'], 2, '.', '');
          $myorder["items"][$num_line_items]['description'] = '(' . $order->products[$i]['qty'] . ' x )' . substr($myorder["items"][$num_line_items]['description'], 115);
        }

        if (isset($order->products[$i]['attributes'])) {
          $options_text_length = 0;
          for ($j=0, $m=sizeof($order->products[$i]['attributes']); $j<$m; $j++) {
            $options_text_length += strlen($order->products[$i]['attributes'][$j]['option'] . $order->products[$i]['attributes'][$j]['value']);
          }
          if ($options_text_length < 128) {
            for ($j=0, $m=sizeof($order->products[$i]['attributes']); $j<$m; $j++) {
              $myorder["items"][$num_line_items]['options' . $j]['name'] = substr(htmlentities($order->products[$i]['attributes'][$j]['option'], ENT_QUOTES, 'UTF-8'), 0, 128);
              $myorder["items"][$num_line_items]['options' . $j]['value'] = substr(htmlentities($order->products[$i]['attributes'][$j]['value'], ENT_QUOTES, 'UTF-8'), 0, 128);
            }
          }
        }
        // track one-time charges
        if ($order->products[$i]['onetime_charges'] != 0 ) {
          $num_line_items++;
          $myorder["items"][$num_line_items]['id']          = 'OTC';
          $myorder["items"][$num_line_items]['description'] = 'One Time Charges';
          $myorder["items"][$num_line_items]['quantity']    = 1;
          $myorder["items"][$num_line_items]['price']       = number_format(zen_add_tax($order->products[$i]['onetime_charges'], $order->products[$i]['tax']), 2, '.', '');
        }
      }
/*
        // deal with surcharges/fees
        $num_line_items++;
        $myorder["items"][$num_line_items]['id']          = 'Surcharge';
        $myorder["items"][$num_line_items]['description'] = $order_totals[$i]['title'];
        $myorder["items"][$num_line_items]['quantity']    = 1;
        $myorder["items"][$num_line_items]['price']       = number_format($order_totals[$i]['value'], 2, '.', '');
        $myorder["subtotal"] += $surcharges;
*/

     // FirstData can't accept more than 20 line-item submissions per transaction
      if ($num_line_items > 20) {
        unset($myorder["items"]);
        $num_line_items = 0;
      }
      // Verify that the line-item math works
      for ($i=1, $n=$num_line_items; $i <= $n; $i++) {
        $sum2 += ($myorder["items"][$i]['quantity'] * $myorder["items"][$i]['price']);
      }
      if (strval($sum2) != strval($myorder['subtotal'])) {
        unset($myorder['items']);
        $num_line_items = 0;
      }
    }

    // Subtotal Sanity Check in case there are addon modules affecting calculations
    $sum1 = strval($myorder['subtotal'] + $myorder['shipping'] + $myorder['tax']);
    if ($sum1 > $myorder['chargetotal']) {
      foreach(array('subtotal', 'tax', 'shipping', 'items') as $i) {
        if (isset($myorder[$i])) unset($myorder[$i]);
      }
    } elseif ($sum1 < $myorder['chargetotal']) {
      if ($num_line_items > 0 && $num_line_items < 20 && isset($myorder['items'])) {
        $num_line_items++;
        $myorder["items"][$num_line_items]['id']          = 'Adj';
        $myorder["items"][$num_line_items]['description'] = 'Rounding Adjustment';
        $myorder["items"][$num_line_items]['quantity']    = 1;
        $myorder["items"][$num_line_items]['price']       = number_format($myorder['chargetotal'] - $sum1, 2, '.', '');
        $myorder['subtotal'] += round($myorder['chargetotal'] - $sum1, 2);
        $myorder['subtotal'] = number_format($myorder['subtotal'], 2, '.', '');
      } else {
        foreach(array('subtotal', 'tax', 'shipping', 'items') as $i) {
          if (isset($myorder[$i])) unset($myorder[$i]);
        }
      }
    }
    // clean up zeros
    foreach(array('subtotal', 'tax', 'shipping') as $i) {
      if (isset($myorder[$i]) && $myorder[$i] == 0) unset($myorder[$i]);
    }

    $myorder["ip"]  = current(explode(':', str_replace(',', ':', zen_get_ip_address())));
    $myorder["ponumber"]    = "";

    // CARD INFO
    $myorder["cardnumber"]   = $_POST['cc_number'];
    $myorder["cardexpmonth"] = $_POST['cc_expires_month'];
    $myorder["cardexpyear"]  = $_POST['cc_expires_year'];
    $myorder["cvmindicator"] = "provided";
    $myorder["cvmvalue"]     = $_POST['cc_cvv'];

    // BILLING INFO
    $myorder["userid"]   = $_SESSION['customer_id'];
    $myorder["customerid"] = $_SESSION['customer_id'];
    $myorder["name"]     = htmlentities($_POST['cc_owner'], ENT_QUOTES, 'UTF-8'); //$order->billing['firstname'] . ' ' . $order->billing['lastname']);
    $myorder["company"]  = htmlentities($order->billing['company'], ENT_QUOTES, 'UTF-8');
    $myorder["address1"] = htmlentities($order->billing['street_address'], ENT_QUOTES, 'UTF-8');
    $myorder["address2"] = htmlentities($order->billing['suburb'], ENT_QUOTES, 'UTF-8');
    $myorder["city"]     = $order->billing['city'];
    $myorder["state"]    = $order->billing['state'];
    $myorder["country"]  = $order->billing['country']['iso_code_2'];
    $myorder["phone"]    = $order->customer['telephone'];
    //$myorder["fax"]      = $order->customer['fax'];
    $myorder["email"]    = $order->customer['email_address'];
    $myorder["addrnum"]  = $order->billing['street_address'];   // Required for AVS. If not provided, transactions will downgrade.
    $myorder["zip"]      = $order->billing['postcode']; // Required for AVS. If not provided, transactions will downgrade.

    // SHIPPING INFO
    $myorder["sname"]     = htmlentities($order->delivery['firstname'] . ' ' . $order->delivery['lastname'], ENT_QUOTES, 'UTF-8');
    $myorder["saddress1"] = htmlentities($order->delivery['street_address'], ENT_QUOTES, 'UTF-8');
    $myorder["saddress2"] = htmlentities($order->delivery['suburb'], ENT_QUOTES, 'UTF-8');
    $myorder["scity"]     = $order->delivery['city'];
    $myorder["sstate"]    = $order->delivery['state'];
    $myorder["szip"]      = $order->delivery['postcode'];
    $myorder["scountry"]  = $order->delivery['country']['iso_code_2'];

    // MISC
    $myorder["comments"] = "Website Order";
    // $myorder["referred"] = "";
    $myorder["ordertype"]  = (MODULE_PAYMENT_LINKPOINT_API_AUTHORIZATION_MODE == 'Authorize Only' ? 'PREAUTH': 'SALE');
    $this->payment_status = $myorder["ordertype"];

    // send request to gateway
    $result = $this->_sendRequest($myorder);

    // alert to customer if communication failure
    if (!is_array($result)) {
      $messageStack->add_session('checkout_payment', MODULE_PAYMENT_LINKPOINT_API_TEXT_FAILURE_MESSAGE, 'error');
      zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL', true, false));
    }

    // resubmit without subtotals if subtotal error occurs
    if ($result["r_approved"] != "APPROVED" && !($result["r_approved"] == "SUBMITTED" && $result["r_message"] == 'APPROVED')) {
      if (in_array(substr($result['r_error'],0,10), array('SGS-002301', 'SGS-010503', 'SGS-005003'))) {
        foreach(array('items', 'subtotal', 'tax', 'shipping') as $i) {
          if (isset($myorder[$i])) unset($myorder[$i]);
        }
        $myorder["oid"] .= '-b';
        $myorder["chargetotal"] = ($myorder["chargetotal"] - 0.01);
        $result = $this->_sendRequest($myorder);
        if (!is_array($result)) {
          $messageStack->add_session('checkout_payment', MODULE_PAYMENT_LINKPOINT_API_TEXT_FAILURE_MESSAGE, 'error');
          zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL', true, false));
        }
      }
    }

// PARSE Results
    $all_response_info = '';
    foreach($result as $key=>$value) {
      $all_response_info .= ' ' .$key . '='.$value;
    }
    if ($this->code_debug) $messageStack->add_session('header', $all_response_info, 'caution');

    $chargetotal = $myorder["chargetotal"];

// prepare transaction logging info
    $cust_info = '';
    $cc_number = substr($myorder["cardnumber"], 0, 4) . str_repeat('X', abs(strlen($myorder["cardnumber"]) - 8)) . substr($myorder["cardnumber"], -4);
    foreach($myorder as $key=>$value) {
      if ($key != 'cardnumber') {
        if ($key == 'cvmvalue') {
          $value = '****';
        }
        if ($key == 'cardexpmonth') {
          $cc_month = $value;
        }
        if ($key == 'cardexpyear') {
          $cc_year = $value;
        }
        if (is_array($value)) $value = print_r($value, true);
        if (!in_array($key, array('keyfile', 'configfile', 'transactionorigin', 'terminaltype', 'host', 'port'))) $cust_info .= ' ' .$key . '=' . $value . ';';
      } else {
        $cust_info .= ' ' .$key . '=' . $cc_number . ';';
      }
    }
    // store last 4 digits of CC number
//    $order->info['cc_number'] = str_repeat('X', (strlen($myorder["cardnumber"]) - 4)) . substr($myorder["cardnumber"], -4);
    // store first and last 4 digits of CC number ... which is the Visa-standards-compliant approach, same as observed by Linkpoint's services
    $order->info['cc_number'] = $cc_number;

    $order->info['cc_type'] = $_POST['cc_type'];
    $order->info['cc_owner'] = $_POST['cc_owner'];
    $order->info['cc_cvv'] = '***';
    $order->info['cc_expires'] = '';// $_POST['cc_expires'];


    $lp_trans_num = $result['r_ordernum'];
    $transaction_tax = $result['r_tax']; // The calculated tax for the order, when the ordertype is calctax.
    $transaction_shipping = $result['r_shipping']; // The calculated shipping charges for the order, when the ordertype is calcshipping.
    $this->response_codes = $result['r_avs']; // AVS Response for transaction

    // these are used to update the order-status-history upon order completion
    $this->transaction_id = $result['r_tdate'] . ' Order Number/Code: ' . $result['r_ordernum'];
    $this->auth_code = $result['r_code']; // The approval code for this transaction.

//  Store Transaction history in Database
    $sql_data_array= array(array('fieldName'=>'lp_trans_num', 'value' => $result['r_ordernum'], 'type'=>'string'), // The order number associated with this transaction.
                           array('fieldName'=>'order_id', 'value' => $result['r_ordernum'], 'type'=>'integer'),
                           array('fieldName'=>'approval_code', 'value' => $result['r_code'], 'type'=>'string'), // The approval code for this transaction.
                           array('fieldName'=>'transaction_response_time', 'value' => $result['r_time'], 'type'=>'string'), // The time+date of the transaction server response.
                           array('fieldName'=>'r_error', 'value' => $result['r_error'], 'type'=>'string'),
                           array('fieldName'=>'customer_id', 'value' => $_SESSION['customer_id'] , 'type'=>'integer'),
                           array('fieldName'=>'avs_response', 'value' => $result['r_avs'], 'type'=>'string'), // AVS Response for transaction
                           array('fieldName'=>'transaction_result', 'value' => $result['r_approved'], 'type'=>'string'), // Transaction result: APPROVED, DECLINED, or FRAUD.
                           array('fieldName'=>'message', 'value' => $result['r_message'] . "\n" . $all_response_info, 'type'=>'string'), // Any message returned by the processor; e.g., CALL VOICE CENTER.
                           array('fieldName'=>'transaction_time', 'value' => $result['r_tdate'], 'type'=>'string'), // A server time-date stamp for this transaction.
                           array('fieldName'=>'transaction_reference_number', 'value' => $result['r_ref'], 'type'=>'string'), // Reference number returned by the CC processor.
                           array('fieldName'=>'fraud_score', 'value' => $result['r_score'], 'type'=>'integer'), // LinkShield fraud risk score.
                           array('fieldName'=>'cc_number', 'value' => $cc_number, 'type'=>'string'),
                           array('fieldName'=>'cust_info', 'value' => $cust_info, 'type'=>'string'),
                           array('fieldName'=>'chargetotal', 'value' => $chargetotal, 'type'=>'string'),
                           array('fieldName'=>'cc_expire', 'value' => $cc_month . '/' . $cc_year, 'type'=>'string'),
                           array('fieldName'=>'ordertype', 'value' => $myorder['ordertype'], 'type'=>'string'), // transaction type: PREAUTH or SALE
                           array('fieldName'=>'date_added', 'value' => 'now()', 'type'=>'noquotestring'));
    if (MODULE_PAYMENT_LINKPOINT_API_STORE_DATA == 'True') {
      $db->perform(TABLE_LINKPOINT_API, $sql_data_array);
    }

  //  Begin check of specific error conditions
    if ($result["r_approved"] != "APPROVED" && !($result["r_approved"] == "SUBMITTED" && $result["r_message"] == 'APPROVED')) {
      if (substr($result['r_error'],0,10) == 'SGS-020005') $messageStack->add_session('checkout_payment', $result['r_error'], 'error');  // Error (Merchant config file is missing, empty or cannot be read)
      if (substr($result['r_error'],0,10) == 'SGS-005000') $messageStack->add_session('checkout_payment', MODULE_PAYMENT_LINKPOINT_API_TEXT_GENERAL_ERROR . '<br />' . $result['r_error'], 'error'); // The server encountered a database error
      if (substr($result['r_error'],0,10) == 'SGS-000001' || strstr($result['r_error'], 'D:Declined') || strstr($result['r_error'], 'R:Referral')) $messageStack->add_session('checkout_payment', MODULE_PAYMENT_LINKPOINT_API_TEXT_DECLINED_MESSAGE . '<br />' . $result['r_error'], 'error');
      if (substr($result['r_error'],0,10) == 'SGS-005005' || strstr($result['r_error'], 'Duplicate transaction')) $messageStack->add_session('checkout_payment', MODULE_PAYMENT_LINKPOINT_API_TEXT_DUPLICATE_MESSAGE . '<br />' . $result['r_error'], 'error');
      if (substr($result['r_error'],0,10) == 'SGS-002301') $messageStack->add_session('checkout_payment', 'Subtotal miscalculation. Please notify the storeowner.' . '<br />' . $result['r_error'], 'error');
    }
  //  End specific error conditions

  //  Begin Transaction Status does not equal APPROVED
    if ($result["r_approved"] != "APPROVED") {
      // alert to customer:
      $messageStack->add_session('checkout_payment', MODULE_PAYMENT_LINKPOINT_API_TEXT_DECLINED_MESSAGE, 'caution');
      zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL', true, false));
    }
  //  End Transaction Status does not equal APPROVED

    $avs_meanings = array();
    $avs_meanings['YY'] = ' - Street Address and Zip Code match.';
    $avs_meanings['YN'] = ' - Street Address matches but Zip Code does NOT match.';
    $avs_meanings['YX'] = ' - Street Address matches, but Zip Code comparison unavailable.';
    $avs_meanings['NY'] = ' - Street Address DOES NOT match, but Zip Code matches.';
    $avs_meanings['XY'] = ' - Street Address check not available, but Zip Code matches.';
    $avs_meanings['NN'] = ' - Street Address DOES NOT MATCH and Zip Code DOES NOT MATCH.';
    $avs_meanings['NX'] = ' - Street Address DOES NOT MATCH and Zip Code comparison unavailable.';
    $avs_meanings['XN'] = ' - Street Address check not available. Zip Code DOES NOT MATCH.';
    $avs_meanings['XX'] = ' - No validation for address or zip code could be performed (not available from issuing bank).';

    // Possible Fraud order. Allow transaction to process, but notify shop for owner to take appropriate action on order
    if (($result["r_approved"] == "APPROVED") && (substr($result['r_code'], 17, 2) != "YY")  && MODULE_PAYMENT_LINKPOINT_API_FRAUD_ALERT == 'Yes') {
      //DEBUG: $messageStack->add_session('header', 'possible fraud situation--> ' . $result['r_code'], 'caution');
      $message = 'Potential Fraudulent Order - Bad Address - Action Required' . "\n" .
                 'This alert occurs because the "Approval Code" below does not contain the expected YY response.' . "\n" .
                 'Thus, you might want to verify the address with the customer prior to shipping, or be sure to use Registered Mail with Signature Required in case they file a chargeback.' . "\n\n" .
                 'Customer Name: ' . $order->customer['firstname'] . ' ' . $order->customer['lastname'] . "\n\n" .
                 'AVS Result: ' . $result['r_avs'] . $avs_meanings[substr($result['r_avs'],0,2)] . "\n\n" .
                 'Order Number: ' . $lp_trans_num . "\n" .
                 'Transaction Date and Time: ' . $result['r_time'] . "\n" .
                 'Approval Code: ' . $result['r_code'] . "\n" .
                 'Reference Number: ' . $result['r_ref'] . "\n\n" .
                 'Error Message: ' . $result['r_error'] . "\n\n" .
                 'Transaction Result: ' . $result['r_approved'] . "\n\n" .
                 'Message: ' . $result['r_message'] . "\n\n" .
                 'Fraud Score: ' . ($result['r_score'] == '' ? 'Not Enabled' : $result['r_score']) . "\n\n" .
                 'AVS CODE MEANINGS: ' . "\n" .
                 'YY** = Street Address and Zip Code match.' . "\n" .
                 'YN** = Street Address matches but Zip Code does NOT match.' . "\n" .
                 'YX** = Street Address matches, but Zip Code comparison unavailable.' . "\n" .
                 'NY** = Street Address DOES NOT match, but Zip Code matches.' . "\n" .
                 'XY** = Street Address check not available, but Zip Code matches.' . "\n" .
                 'NN** = Street Address DOES NOT MATCH and Zip Code DOES NOT MATCH.' . "\n" .
                 'NX** = Street Address DOES NOT MATCH and Zip Code comparison unavailable.' . "\n" .
                 'XN** = Street Address check not available. Zip Code DOES NOT MATCH.' . "\n" .
                 'XX** = Neither validation is available.' . "\n";
      $html_msg['EMAIL_MESSAGE_HTML'] = nl2br($result['r_message']);
      zen_mail(STORE_NAME, STORE_OWNER_EMAIL_ADDRESS, 'Potential Fraudulent Order - Bad Address - Action Required - ' . $lp_trans_num, $message, STORE_NAME, EMAIL_FROM, $html_msg, 'fraudalert');
    }
  // end fraud alert
  }
654657
private function initDoubleBeforeSave()
	{

		$type = new Type($this->payment->type, $this->payment->toArray());

		switch ($type->sid()) {

			case Type::COMPLETE:
			case Type::REFUND:

				$payment = self::find(
					$this->payment->term,
					$this->payment->order,
					$this->payment->irn,
					$this->payment->rrn,
					$type->sid(),
					array(Status::SUCCESS)
				);

				if ($payment) {
					$this->payment = $payment;
				}

				break;

		}

	}
648761
protected function submitOrderCheckout()
    {
        if (!$this->isPosted('save')) {
            return null;
        }

        $errors = array();

        foreach (array('payment', 'shipping') as $type) {

            $address_errors = $this->validateAddressCheckout($type);

            if (!empty($address_errors)) {
                $errors = gplcart_array_merge($errors, $address_errors);
            }

            if (empty($address_errors)) {
                $this->addAddressCheckout($type);
            }
        }

        $order_errors = $this->validateOrderCheckout();
        $errors = gplcart_array_merge($errors, $order_errors);

        if (empty($errors)) {
            $this->addOrderCheckout();
        } else {
            $this->setError(null, $errors);
        }
    }
876755
protected function setFormDataAfterCheckout()
    {
        if (empty($this->data_cart)) {
            return null;
        }

        $this->data_form['cart'] = $this->data_cart;

        $this->setFormDataAddressCheckout();

        if (empty($this->data_form['addresses'])) {
            $this->show_shipping_address_form = true;
        }

        $this->data_form['default_payment_method'] = false;
        $this->data_form['default_shipping_method'] = false;
        $this->data_form['same_payment_address'] = $this->same_payment_address;
        $this->data_form['get_payment_methods'] = $this->isPosted('get_payment_methods');
        $this->data_form['get_shipping_methods'] = $this->isPosted('get_shipping_methods');
        $this->data_form['show_login_form'] = $this->show_login_form;
        $this->data_form['show_payment_address_form'] = $this->show_payment_address_form;
        $this->data_form['show_shipping_address_form'] = $this->show_shipping_address_form;
        $this->data_form['show_payment_methods'] = !$this->data_form['has_dynamic_payment_methods'];
        $this->data_form['show_shipping_methods'] = !$this->data_form['has_dynamic_shipping_methods'];

        $submitted = array('order' => $this->getSubmitted());

        $this->data_form['context_templates'] = array(
            'payment' => $this->getPaymentMethodTemplate('context', $submitted['order'], $this->payment),
            'shipping' => $this->getShippingMethodTemplate('context', $submitted['order'], $this->shipping),
        );

        $this->data_form = gplcart_array_merge($this->data_form, $submitted);

        $this->setFormDataRequestServicesCheckout('payment');
        $this->setFormDataRequestServicesCheckout('shipping');
        $this->setFormDataCalculatedCheckout();
        $this->setFormDataPanesCheckout();
    }
839635
protected function transactionSucceed()
	{
		return $this->getTable()->whereId($this->transactionId)->update([
			'status' => Enum::TRANSACTION_SUCCEED,
			'tracking_code' => $this->trackingCode,
			'card_number' => $this->cardNumber,
			'payment_date' => Carbon::now(),
			'updated_at' => Carbon::now(),
		]);
	}
215792
protected function submitEditCheckout()
    {
        $this->setSubmitted('order');

        $this->setAddressFormCheckout();
        $this->submitAddAddressCheckout();

        if ($this->isPosted('checkout_login') && empty($this->uid)) {
            $this->show_login_form = true;
        }

        $this->same_payment_address = (bool) $this->getPosted('same_payment_address', true, false, 'bool');

        if ($this->isPosted('update')) {
            $this->setMessage($this->text('Form has been updated'), 'success', false);
        }

        $this->submitLoginCheckout();

        if ($this->isPosted('checkout_anonymous')) {
            $this->show_login_form = false;
        }

        $this->validateCouponCheckout();
        $this->submitCartCheckout();
        $this->submitOrderCheckout();
    }
773551
public function confirmAction()
	{
		$context = $this->getContext();
		$client = \Aimeos\Client\Html::create( $context, 'checkout/confirm' );

		$view = $context->getView();
		$param = array_merge( \TYPO3\CMS\Core\Utility\GeneralUtility::_GET(), \TYPO3\CMS\Core\Utility\GeneralUtility::_POST() );
		$helper = new \Aimeos\MW\View\Helper\Param\Standard( $view, $param );
		$view->addHelper( 'param', $helper );

		$client->setView( $view );
		$client->process();

		$this->response->addAdditionalHeaderData( (string) $client->getHeader() );

		return $client->getBody();
	}
1254932
public function processPayment()
    {
        $bankwireMethod = $this
            ->methodFactory
            ->create();

        /**
         * 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,
                $bankwireMethod
            );

        /**
         * 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,
                $bankwireMethod
            );

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

        return $this;
    }
564206
public function confirmOrderReference()
    {
        $confirmOrderReferenceRequest 
            = new OffAmazonPaymentsService_Model_ConfirmOrderReferenceRequest();
        $confirmOrderReferenceRequest
            ->setAmazonOrderReferenceId($this->_amazonOrderReferenceId);
        $confirmOrderReferenceRequest->setSellerId($this->_sellerId);
       
        return $this->_service->confirmOrderReference($confirmOrderReferenceRequest);
    }
200370
public function sync()
    {
        $response = ['success' => true, 'message' => 'Done.'];

        // Initialise a return hash containing results of our sync attempt
        $this->searchWebsiteAccounts();

        foreach ($this->accounts as $account) {
            $orders = $account->getOrders();
            $ordersForSingleSync = $account->getOrdersForSingleSync();
            $numOrders = count($orders);
            $numOrdersForSingleSync = count($ordersForSingleSync);
            $website = $account->getWebsites();
            $this->countOrders += $numOrders;
            $this->countOrders += $numOrdersForSingleSync;
            //create bulk
            if ($numOrders) {
                $this->helper->log('--------- Order sync ---------- : ' . $numOrders);
                //queue order into importer
                $this->importerFactory->create()
                    ->registerQueue(
                        \Dotdigitalgroup\Email\Model\Importer::IMPORT_TYPE_ORDERS,
                        $orders,
                        \Dotdigitalgroup\Email\Model\Importer::MODE_BULK,
                        $website[0]
                    );
            }
            //create single
            if ($numOrdersForSingleSync) {
                $this->createSingleImports($ordersForSingleSync, $website);
            }

            //mark the orders as imported
            $this->orderResource->setImported($this->orderIds);

            unset($this->accounts[$account->getApiUsername()]);
        }

        /**
         * Add guests to contact table.
         */
        if (! empty($this->guests)) {
            $orderEmails = array_keys($this->guests);
            $guestsEmailFound = $this->contactCollectionFactory->create()
                ->addFieldToFilter('email', ['in' => $orderEmails])
                ->getColumnValues('email');
            //remove the contacts that already exists
            foreach ($guestsEmailFound as $email) {
                unset($this->guests[strtolower($email)]);
            }

            //insert new guests contacts
            $this->contactResource->insertGuests($this->guests);
            //mark the existing contacts with is guest in bulk
            $this->contactResource->updateContactsAsGuests($guestsEmailFound);
        }

        if ($this->countOrders) {
            $response['message'] = 'Orders updated ' . $this->countOrders;
        }

        return $response;
    }
504448
public function finish()
    {
        // Check the users details are set, if not, send them to the cart
        $billing_data = Session::get("Checkout.BillingDetailsForm.data");
        $delivery_data = Session::get("Checkout.DeliveryDetailsForm.data");

        if (!Checkout::config()->simple_checkout && !is_array($billing_data) && !is_array($delivery_data)) {
            return $this->redirect($this->Link('index'));
        }
        
        // Check permissions for guest checkout
        if (!Member::currentUserID() && !Checkout::config()->guest_checkout) {
            return $this->redirect($this->Link('index'));
        }
            
        if (Checkout::config()->simple_checkout) {
            $title = _t('Checkout.SelectPaymentMethod', "Select Payment Method");
        } else {
            $title = _t('Checkout.SeelctPostagePayment', "Select Postage and Payment Method");
        }

        $this->customise(array(
            'Title'     => $title,
            'Form'      => $this->PostagePaymentForm()
        ));

        $this->extend("onBeforeFinish");

        return $this->renderWith(array(
            'Checkout_finish',
            'Checkout',
            'Page'
        ));
    }
54387
public function PostProcessExternalPaymentHandlerHook()
    {
        $bPaymentTransmitOk = parent::PostProcessExternalPaymentHandlerHook();
        if ($bPaymentTransmitOk) {
            $oGlobal = TGlobal::instance();
            $aUserData = $oGlobal->GetUserData();
            $sToken = $oGlobal->GetUserData('token');
            if (empty($sToken) && !is_null($this->sPayPalToken)) {
                $sToken = $this->sPayPalToken;
            } // recover token from session if not return from paypal
            if (!empty($sToken)) { // ignore request without a token (paypal would sometimes generate 2 reqeusts via browser redirect - one with and one without payload. we need to ignore the one without)
                $this->sPayPalToken = $sToken;
                // now fetch the details
                $this->aCheckoutDetails = $this->ExecutePayPalCall('GetExpressCheckoutDetails', array('TOKEN' => $this->sPayPalToken));
            }
        }

        return $bPaymentTransmitOk;
    }
12640
function update_status() {
    global $order, $db;

    if ( ($this->enabled == true) && ((int)MODULE_PAYMENT_PAYPAL_ZONE > 0) ) {
      $check_flag = false;
      $check_query = $db->Execute("select zone_id from " . TABLE_ZONES_TO_GEO_ZONES . " where geo_zone_id = '" . MODULE_PAYMENT_PAYPAL_ZONE . "' and zone_country_id = '" . $order->billing['country']['id'] . "' order by zone_id");
      while (!$check_query->EOF) {
        if ($check_query->fields['zone_id'] < 1) {
          $check_flag = true;
          break;
        } elseif ($check_query->fields['zone_id'] == $order->billing['zone_id']) {
          $check_flag = true;
          break;
        }
        $check_query->MoveNext();
      }

      if ($check_flag == false) {
        $this->enabled = false;
      }
    }
  }