function update_status()
 {
     global $order;
     if ($this->enabled === true && (!defined('MODULE_ORDER_TOTAL_PAYPALINSTALLMENT_FEE_STATUS') || MODULE_ORDER_TOTAL_PAYPALINSTALLMENT_FEE_STATUS == 'false')) {
         $this->enabled = false;
     }
     if ($this->enabled === true && $order->billing['country']['iso_code_2'] != 'DE') {
         $this->enabled = false;
     }
     if ($this->enabled === true && ($_SESSION['customers_status']['customers_status_show_price_tax'] != '1' || $_SESSION['customers_status']['customers_status_add_tax_ot'] != '0')) {
         $this->enabled = false;
     }
     if ($this->enabled === true) {
         if (!class_exists('order_total')) {
             require_once DIR_WS_CLASSES . 'order_total.php';
         }
         $order_total_modules = new order_total();
         $order_totals = $order_total_modules->process();
         $this->total_amount = 0;
         for ($i = 0, $n = count($order_totals); $i < $n; $i++) {
             if ($order_totals[$i]['code'] == 'ot_total') {
                 $this->total_amount = $order_totals[$i]['value'];
             }
         }
         $this->presentment_array = $this->get_presentment($this->total_amount, $order->info['currency'], $order->billing['country']['iso_code_2']);
         if (count($this->presentment_array) < 1) {
             $this->enabled = false;
         }
     }
 }
Beispiel #2
0
 /**
  * Get zen-cart order totals.
  *
  * @param  ShoppingCart $shoppingCart The current shopping cart.
  * @return array        zencart order totals.
  */
 protected function getZenTotals(ShoppingCart $shoppingCart)
 {
     global $order, $shipping_modules;
     // save
     $otmp = $order;
     $smtmp = $shipping_modules;
     $order = new \order();
     if (!isset($shipping_modules)) {
         $ssm = array();
         if (null != ($shippingMethod = $shoppingCart->getSelectedShippingMethod())) {
             $ssm = array('id' => $shippingMethod->getShippingId(), 'title' => $shippingMethod->getName(), 'cost' => $shippingMethod->getCost());
         }
         $shipping_modules = new \shipping($ssm);
     }
     $zenTotals = new \order_total();
     $zenTotals->collect_posts();
     $zenTotals->pre_confirmation_check();
     $zenTotals->process();
     // restore
     $order = $otmp;
     $shipping_modules = $smtmp;
     return $zenTotals;
 }
     }
     $products_name = '<table border="0" cellspacing="0" cellpadding="0" width="100%">' . "\n" . '  <tr>' . "\n" . '	<td rowspan="2" width="90">' . $products_image . '</td>' . "\n" . '	<td colspan="2">' . $products_name . '</td>' . "\n" . '  </tr>' . "\n" . '  <tr>' . "\n" . '	<td valign="bottom">' . ($products[$i]['type'] > 1 ? '&nbsp;' : '<a href="' . tep_href_link(FILENAME_SHOPPING_CART, 'action=move_product&to=postpone&products_id=' . $products[$i]['id']) . '">' . tep_image_button('button_postpone.gif', IMAGE_BUTTON_POSTPONE) . '</a>') . '</td>' . "\n" . '	<td valign="bottom" align="right"><a href="' . tep_href_link(FILENAME_SHOPPING_CART, 'action=remove_product&products_id=' . $products[$i]['id']) . '">' . tep_image_button('button_delete.gif', IMAGE_BUTTON_DELETE) . '</a></td>' . "\n" . '  </tr>' . "\n" . '</table>' . "\n";
     $info_box_contents[$cur_row][] = array('params' => 'class="productListing-data-first"', 'text' => $products_name);
     $info_box_contents[$cur_row][] = array('align' => 'center', 'params' => 'class="productListing-data"', 'text' => ($products[$i]['quantity'] > 1 ? $products[$i]['quantity'] . 'x' : '') . (tep_not_null($products[$i]['filename']) ? '-' : $products[$i]['weight'] * 1000 . TEXT_WEIGHT_GRAMMS));
     $info_box_contents[$cur_row][] = array('align' => 'center', 'params' => 'class="productListing-data" nowrap="nowrap"', 'text' => $currencies->display_price($products[$i]['price'], tep_get_tax_rate($products[$i]['tax_class_id'])));
     $info_box_contents[$cur_row][] = array('align' => 'center', 'params' => 'class="productListing-data"', 'text' => $qty_field . tep_draw_hidden_field('products_id[]', $products[$i]['id']));
     $info_box_contents[$cur_row][] = array('align' => 'center', 'params' => 'class="productListing-data-last" align="right" nowrap="nowrap"', 'text' => '<div class="row_product_price">' . $currencies->display_price($products[$i]['final_price'], tep_get_tax_rate($products[$i]['tax_class_id']), $products[$i]['quantity']) . '</div>');
     $cur_row = sizeof($info_box_contents);
     $info_box_contents[$cur_row][] = array('align' => 'center', 'params' => 'colspan="5" class="row_btwh"', 'text' => tep_draw_separator('pixel_trans.gif', '1', '1'));
 }
 if (MODULE_ORDER_TOTAL_INSTALLED) {
     require DIR_WS_CLASSES . 'order.php';
     $order = new order();
     require DIR_WS_CLASSES . 'order_total.php';
     $order_total_modules = new order_total();
     $order_total_array = $order_total_modules->process();
     reset($order_total_array);
     while (list(, $order_total_row) = each($order_total_array)) {
         //		if ( ($order_total_row['code']=='ot_total' && !in_array('ot_discount', $order_total_modules->classes) && !in_array('ot_tax', $order_total_modules->classes)) || $order_total_row['code']=='ot_shipping' ) continue;
         $cur_row++;
         if ($order_total_row['code'] == 'ot_subtotal') {
             $total_weight = $cart->show_weight() * 1000;
             if ($total_weight > 2000) {
                 $total_weight_text = round($total_weight / 1000, 2) . TEXT_WEIGHT_KILOGRAMMS;
             } else {
                 $total_weight_text = $total_weight . TEXT_WEIGHT_GRAMMS;
             }
             $info_box_contents[$cur_row][] = array('align' => 'left', 'params' => 'class="productListing-heading-first"', 'text' => $order_total_row['title']);
             $info_box_contents[$cur_row][] = array('align' => 'center', 'params' => 'class="productListing-heading"', 'text' => $total_weight_text);
             $info_box_contents[$cur_row][] = array('align' => 'center', 'params' => 'class="productListing-heading"', 'text' => '&nbsp;');
             $info_box_contents[$cur_row][] = array('align' => 'center', 'params' => 'class="productListing-heading"', 'text' => $cart->count_contents());
 function paypal_express_auth_call()
 {
     // aufruf aus cart_actions.php
     // 1. Call um die Token ID zu bekommen
     // Steuer, Artikel usw bei eingeloggt
     // Stand: 03.05.2012
     global $xtPrice, $order;
     // Session säubern
     unset($_SESSION['reshash']);
     unset($_SESSION['nvpReqArray']);
     // Shipping:
     if (!isset($_SESSION['sendto'])) {
         $_SESSION['sendto'] = $_SESSION['customer_default_address_id'];
     } else {
         // verify the selected shipping address
         $check_address_query = xtc_db_query("select count(*) as total from " . TABLE_ADDRESS_BOOK . " where customers_id = '" . (int) $_SESSION['customer_id'] . "' and address_book_id = '" . (int) $_SESSION['sendto'] . "'");
         $check_address = xtc_db_fetch_array($check_address_query);
         if ($check_address['total'] != '1') {
             $_SESSION['sendto'] = $_SESSION['customer_default_address_id'];
         }
     }
     // Shipping beim 1. Call auf jeden Fall löschen falls Änderungen im WK
     if (isset($_SESSION['shipping'])) {
         unset($_SESSION['shipping']);
     }
     // Shipping END
     require DIR_WS_CLASSES . 'order.php';
     $order = new order();
     require DIR_WS_CLASSES . 'order_total.php';
     $order_total_modules = new order_total();
     $order_totals = $order_total_modules->process();
     $order_tax = 0;
     $order_discount = 0;
     $order_gs = 0;
     $order_fee = 0;
     $order_shipping = 0;
     for ($i = 0, $n = sizeof($order_totals); $i < $n; $i++) {
         switch ($order_totals[$i]['code']) {
             case 'ot_discount':
                 $order_discount += $order_totals[$i]['value'];
                 break;
             case 'ot_coupon':
             case 'ot_coupon':
                 $order_gs += $order_totals[$i]['value'] < 0 ? $order_totals[$i]['value'] : $order_totals[$i]['value'] * -1;
                 break;
             case 'ot_gv':
                 $order_gs += $order_totals[$i]['value'] < 0 ? $order_totals[$i]['value'] : $order_totals[$i]['value'] * -1;
                 break;
                 ///  customers bonus
             ///  customers bonus
             case 'ot_bonus_fee':
                 $order_gs += $order_totals[$i]['value'] < 0 ? $order_totals[$i]['value'] : $order_totals[$i]['value'] * -1;
                 break;
             case 'ot_payment':
                 if ($order_totals[$i]['value'] < 0) {
                     // Rabatt aus Fremd Modul
                     $order_discount += $order_totals[$i]['value'];
                 } else {
                     $order_fee += $order_totals[$i]['value'];
                 }
                 break;
             case 'ot_cod_fee':
                 $order_fee += $order_totals[$i]['value'];
                 break;
             case 'ot_ps_fee':
                 $order_fee += $order_totals[$i]['value'];
                 break;
             case 'ot_loworderfee':
                 $order_fee += $order_totals[$i]['value'];
         }
     }
     // AMT
     $paymentAmount = $_SESSION['cart']->show_total() + $order_discount + $order_gs + $order_fee;
     // Durch Kupon oder irgendwas auf unter 0 -> Kein PP Express sinnvoll
     if ($paymentAmount <= 0) {
         $_SESSION['reshash']['FORMATED_ERRORS'] = PAYPAL_AMMOUNT_NULL;
         $this->payPalURL = $this->EXPRESS_CANCEL_URL;
         return $this->payPalURL;
     }
     if ($_SESSION['customers_status']['customers_status_show_price_tax'] == 0 && $_SESSION['customers_status']['customers_status_add_tax_ot'] == 1) {
         $order_tax = $_SESSION['cart']->show_tax(false);
     }
     // Vorläufige Versandkosten
     if (PAYPAL_EXP_VORL != '' && PAYPAL_EXP_VERS != 0) {
         $paymentAmount += PAYPAL_EXP_VERS;
     }
     // AMT
     $paymentAmount = round($paymentAmount, $xtPrice->get_decimal_places($order->info['currency']));
     // Summen der Order
     $order_tax = round($order_tax, $xtPrice->get_decimal_places($order->info['currency']));
     $order_discount = round($order_discount, $xtPrice->get_decimal_places($order->info['currency']));
     $order_gs = round($order_gs, $xtPrice->get_decimal_places($order->info['currency']));
     $order_fee = round($order_fee, $xtPrice->get_decimal_places($order->info['currency']));
     $nvp_products = $this->paypal_get_products($paymentAmount, $order_tax, $order_discount, $order_fee, $order_shipping, $order_gs, True);
     $paymentAmount = urlencode(number_format($paymentAmount, $xtPrice->get_decimal_places($order->info['currency']), '.', ','));
     $currencyCodeType = urlencode($order->info['currency']);
     // Payment Type
     $paymentType = 'Sale';
     $returnURL = urlencode($this->EXPRESS_RETURN_URL);
     $cancelURL = urlencode($this->EXPRESS_CANCEL_URL);
     $gpsucssesURL = urlencode($this->GIROPAY_SUCCESS_URL);
     $gpcancelURL = urlencode($this->EXPRESS_CANCEL_URL);
     $bankpending = urlencode($this->BANKTXN_PENDING_URL);
     if (isset($_SESSION['sendto']) && isset($_SESSION['customer_id'])) {
         // User eingeloggt
         $sh_name = urlencode($this->mn_iconv($_SESSION['language_charset'], "UTF-8", $order->delivery['firstname'] . ' ' . $order->delivery['lastname']));
         $sh_street = urlencode($this->mn_iconv($_SESSION['language_charset'], "UTF-8", $order->delivery['street_address']));
         $sh_street_2 = '';
         $sh_city = urlencode($this->mn_iconv($_SESSION['language_charset'], "UTF-8", $order->delivery['city']));
         $sh_zip = urlencode($order->delivery['postcode']);
         $sh_state = urlencode($this->state_code($order->delivery['state']));
         $sh_countrycode = urlencode($order->delivery['country']['iso_code_2']);
         $sh_countryname = urlencode($this->mn_iconv($_SESSION['language_charset'], "UTF-8", $order->delivery['country']['title']));
         $sh_phonenum = urlencode($this->mn_iconv($_SESSION['language_charset'], "UTF-8", $order->customer['telephone']));
         if ($_SESSION['paypal_express_new_customer'] != 'true') {
             $address = "&SHIPTONAME=" . $sh_name . "&SHIPTOSTREET=" . $sh_street . "&SHIPTOSTREET2=" . $sh_street2 . "&SHIPTOCITY=" . $sh_city . "&SHIPTOZIP=" . $sh_zip . "&SHIPTOSTATE=" . $sh_state . "&SHIPTOCOUNTRYCODE=" . $sh_countrycode . "&SHIPTOCOUNTRYNAME=" . $sh_countryname . "&PHONENUM=" . $sh_phonenum;
         }
     }
     // String zusammenbauen
     $nvpstr = "&AMT=" . $paymentAmount . "&CURRENCYCODE=" . $currencyCodeType . "&PAYMENTACTION=" . $paymentType . "&LOCALECODE=" . $_SESSION['language_code'] . "&RETURNURL=" . $returnURL . "&CANCELURL=" . $cancelURL . "&GIROPAYSUCCESSURL=" . $gpsucssesURL . "&GIROPAYCANCELURL=" . $gpcancelURL . "&BANKTXNPENDINGURL=" . $bankpending . "&HDRIMG=" . $this->Image . "&HDRBORDERCOLOR=" . $this->BorderColor . "&HDRBACKCOLOR=" . $this->BackColor . "&CUSTOM=" . '' . $address . "&ALLOWNOTE=0" . "&ADDROVERRIDE=0";
     // Artikel Details mitgeben
     $nvpstr .= $nvp_products;
     // Make the call to PayPal to set the Express Checkout token
     // If the API call succeded, then redirect the buyer to PayPal
     // to begin to authorize payment.  If an error occured, show the
     // resulting errors
     $resArray = $this->hash_call("SetExpressCheckout", $nvpstr);
     $_SESSION['reshash'] = $resArray;
     $ack = strtoupper($resArray["ACK"]);
     if ($ack == "SUCCESS") {
         $token = urldecode($resArray["TOKEN"]);
         $this->payPalURL = $this->EXPRESS_URL . '' . $token;
         return $this->payPalURL;
     } else {
         if (PAYPAL_ERROR_DEBUG == 'true') {
             $this->build_error_message($_SESSION['reshash']);
         } else {
             $_SESSION['reshash']['FORMATED_ERRORS'] = PAYPAL_NOT_AVIABLE;
         }
         $this->payPalURL = $this->EXPRESS_CANCEL_URL;
         return $this->payPalURL;
     }
 }
Beispiel #5
0
/**
 * Process a <new-order-notification>.
 *
 * If the email user does not exist, create the user and log in.
 *
 * If the user does not exist as a Google Checkout user, add them
 * to the google_checkout table to match the buyer_id and customer_id.
 *
 * Add the order to the logged-in user.
 *
 * TODO(eddavisson): This function is way too long. Split into pieces.
 */
function process_new_order_notification($google_response, $google_checkout)
{
    global $order, $currencies, $languages_id;
    list($root, $gc_data) = $google_response->GetParsedXML();
    // Check if the order was already processed.
    $google_order = tep_db_fetch_array(tep_db_query("select orders_id " . " from " . $google_checkout->table_order . " " . " where google_order_number = " . $gc_data[$root]['google-order-number']['VALUE']));
    // Check if order was alread processed.
    if ($google_order['orders_id'] != '') {
        //Send ACK http 200 to avoid notification resend.
        $google_response->log->logError(sprintf(GOOGLECHECKOUT_ERR_DUPLICATED_ORDER, $gc_data[$root]['google-order-number']['VALUE'], $google_order['orders_id']));
        $google_response->SendAck();
    }
    // Check if the email exists.
    $customer_exists = tep_db_fetch_array(tep_db_query("select customers_id from " . TABLE_CUSTOMERS . " where customers_email_address = '" . gc_make_sql_string($gc_data[$root]['buyer-billing-address']['email']['VALUE']) . "'"));
    // Check if the GC buyer id exists
    $customer_info = tep_db_fetch_array(tep_db_query("select gct.customers_id from " . $google_checkout->table_name . " gct " . " inner join " . TABLE_CUSTOMERS . " tc on gct.customers_id = tc.customers_id " . " where gct.buyer_id = " . gc_make_sql_string($gc_data[$root]['buyer-id']['VALUE'])));
    $new_user = false;
    // Ignore session to avoid mix of Cart-GC sessions/emails
    // GC email is the most important one
    if ($customer_exists['customers_id'] != '') {
        $customer_id = $customer_exists['customers_id'];
        tep_session_register('customer_id');
    } else {
        if ($customer_info['customers_id'] != '') {
            $customer_id = $customer_info['customers_id'];
            tep_session_register('customer_id');
        } else {
            list($firstname, $lastname) = explode(' ', gc_make_sql_string($gc_data[$root]['buyer-billing-address']['contact-name']['VALUE']), 2);
            $sql_data_array = array('customers_firstname' => $firstname, 'customers_lastname' => $lastname, 'customers_email_address' => $gc_data[$root]['buyer-billing-address']['email']['VALUE'], 'customers_telephone' => $gc_data[$root]['buyer-billing-address']['phone']['VALUE'], 'customers_fax' => $gc_data[$root]['buyer-billing-address']['fax']['VALUE'], 'customers_default_address_id' => 0, 'customers_password' => tep_encrypt_password(gc_make_sql_string($gc_data[$root]['buyer-id']['VALUE'])), 'customers_newsletter' => $gc_data[$root]['buyer-marketing-preferences']['email-allowed']['VALUE'] == 'true' ? 1 : 0);
            if (ACCOUNT_DOB == 'true') {
                $sql_data_array['customers_dob'] = 'now()';
            }
            tep_db_perform(TABLE_CUSTOMERS, $sql_data_array);
            $customer_id = tep_db_insert_id();
            tep_session_register('customer_id');
            tep_db_query("insert into " . TABLE_CUSTOMERS_INFO . "\n        (customers_info_id, customers_info_number_of_logons,\n        customers_info_date_account_created)\n        values ('" . (int) $customer_id . "', '0', now())");
            tep_db_query("insert into " . $google_checkout->table_name . " " . " values ( " . $customer_id . ", " . $gc_data[$root]['buyer-id']['VALUE'] . ")");
            $new_user = true;
        }
    }
    // The user exists and is logged in.
    // Check database to see if the address exist.
    $address_book = tep_db_query("select address_book_id, entry_country_id, entry_zone_id from " . TABLE_ADDRESS_BOOK . "\n          where  customers_id = '" . $customer_id . "'\n              and entry_street_address = '" . gc_make_sql_string($gc_data[$root]['buyer-shipping-address']['address1']['VALUE']) . "'\n              and entry_suburb = '" . gc_make_sql_string($gc_data[$root]['buyer-shipping-address']['address2']['VALUE']) . "'\n              and entry_postcode = '" . gc_make_sql_string($gc_data[$root]['buyer-shipping-address']['postal-code']['VALUE']) . "'\n              and entry_city = '" . gc_make_sql_string($gc_data[$root]['buyer-shipping-address']['city']['VALUE']) . "'");
    // If not, add the address as the default.
    if (!tep_db_num_rows($address_book)) {
        $buyer_state = $gc_data[$root]['buyer-shipping-address']['region']['VALUE'];
        $zone_answer = tep_db_fetch_array(tep_db_query("select zone_id, zone_country_id from " . TABLE_ZONES . " where zone_code = '" . $buyer_state . "'"));
        list($firstname, $lastname) = explode(' ', gc_make_sql_string($gc_data[$root]['buyer-shipping-address']['contact-name']['VALUE']), 2);
        $sql_data_array = array('customers_id' => $customer_id, 'entry_gender' => '', 'entry_company' => $gc_data[$root]['buyer-shipping-address']['company-name']['VALUE'], 'entry_firstname' => $firstname, 'entry_lastname' => $lastname, 'entry_street_address' => $gc_data[$root]['buyer-shipping-address']['address1']['VALUE'], 'entry_suburb' => $gc_data[$root]['buyer-shipping-address']['address2']['VALUE'], 'entry_postcode' => $gc_data[$root]['buyer-shipping-address']['postal-code']['VALUE'], 'entry_city' => $gc_data[$root]['buyer-shipping-address']['city']['VALUE'], 'entry_state' => $buyer_state, 'entry_country_id' => $zone_answer['zone_country_id'], 'entry_zone_id' => $zone_answer['zone_id']);
        tep_db_perform(TABLE_ADDRESS_BOOK, $sql_data_array);
        $address_id = tep_db_insert_id();
        tep_db_query("update " . TABLE_CUSTOMERS . "\n        set customers_default_address_id = '" . (int) $address_id . "'\n        where customers_id = '" . (int) $customer_id . "'");
        $customer_default_address_id = $address_id;
        $customer_country_id = $zone_answer['zone_country_id'];
        $customer_zone_id = $zone_answer['zone_id'];
    } else {
        $customer_default_address_id = $address_book['address_book_id'];
        $customer_country_id = $address_book['entry_country_id'];
        $customer_zone_id = $address_book['entry_zone_id'];
    }
    $customer_first_name = $gc_data[$root]['buyer-billing-address']['contact-name']['VALUE'];
    tep_session_register('customer_default_address_id');
    tep_session_register('customer_country_id');
    tep_session_register('customer_zone_id');
    tep_session_register('customer_first_name');
    // Customer exists, is logged and address book is up to date.
    list($shipping, $shipping_cost, $shipping_method_name, $shipping_method_code) = get_shipping_info($google_checkout, $gc_data[$root]);
    $tax_amt = $gc_data[$root]['order-adjustment']['total-tax']['VALUE'];
    //$order_total = $gc_data[$root]['order-total']['VALUE'];
    require DIR_WS_CLASSES . 'order.php';
    $order = new order();
    // Load the selected shipping module.
    $payment_method = $google_checkout->title;
    if (MODULE_PAYMENT_GOOGLECHECKOUT_MODE == 'https://sandbox.google.com/checkout/') {
        $payment_method .= " - SANDBOX";
    }
    //$method_name = '';
    //if (!empty($shipping)) {
    //  require (DIR_WS_CLASSES . 'shipping.php');
    //  $shipping_modules = new shipping($shipping);
    //  list ($a, $method_name) = explode(': ', $shipping, 2);
    //}
    // Set up order info.
    list($order->customer['firstname'], $order->customer['lastname']) = explode(' ', $gc_data[$root]['buyer-billing-address']['contact-name']['VALUE'], 2);
    $order->customer['company'] = $gc_data[$root]['buyer-billing-address']['company-name']['VALUE'];
    $order->customer['street_address'] = $gc_data[$root]['buyer-billing-address']['address1']['VALUE'];
    $order->customer['suburb'] = $gc_data[$root]['buyer-billing-address']['address2']['VALUE'];
    $order->customer['city'] = $gc_data[$root]['buyer-billing-address']['city']['VALUE'];
    $order->customer['postcode'] = $gc_data[$root]['buyer-billing-address']['postal-code']['VALUE'];
    $order->customer['state'] = $gc_data[$root]['buyer-billing-address']['region']['VALUE'];
    $order->customer['country']['title'] = $gc_data[$root]['buyer-billing-address']['country-code']['VALUE'];
    $order->customer['telephone'] = $gc_data[$root]['buyer-billing-address']['phone']['VALUE'];
    $order->customer['email_address'] = $gc_data[$root]['buyer-billing-address']['email']['VALUE'];
    $order->customer['format_id'] = 2;
    list($order->delivery['firstname'], $order->delivery['lastname']) = explode(' ', $gc_data[$root]['buyer-shipping-address']['contact-name']['VALUE'], 2);
    $order->delivery['company'] = $gc_data[$root]['buyer-shipping-address']['company-name']['VALUE'];
    $order->delivery['street_address'] = $gc_data[$root]['buyer-shipping-address']['address1']['VALUE'];
    $order->delivery['suburb'] = $gc_data[$root]['buyer-shipping-address']['address2']['VALUE'];
    $order->delivery['city'] = $gc_data[$root]['buyer-shipping-address']['city']['VALUE'];
    $order->delivery['postcode'] = $gc_data[$root]['buyer-shipping-address']['postal-code']['VALUE'];
    $order->delivery['state'] = $gc_data[$root]['buyer-shipping-address']['region']['VALUE'];
    $order->delivery['country']['title'] = $gc_data[$root]['buyer-shipping-address']['country-code']['VALUE'];
    $order->delivery['format_id'] = 2;
    list($order->billing['firstname'], $order->billing['lastname']) = explode(' ', $gc_data[$root]['buyer-billing-address']['contact-name']['VALUE'], 2);
    $order->billing['company'] = $gc_data[$root]['buyer-billing-address']['company-name']['VALUE'];
    $order->billing['street_address'] = $gc_data[$root]['buyer-billing-address']['address1']['VALUE'];
    $order->billing['suburb'] = $gc_data[$root]['buyer-billing-address']['address2']['VALUE'];
    $order->billing['city'] = $gc_data[$root]['buyer-billing-address']['city']['VALUE'];
    $order->billing['postcode'] = $gc_data[$root]['buyer-billing-address']['postal-code']['VALUE'];
    $order->billing['state'] = $gc_data[$root]['buyer-billing-address']['region']['VALUE'];
    $order->billing['country']['title'] = $gc_data[$root]['buyer-billing-address']['country-code']['VALUE'];
    $order->billing['format_id'] = 2;
    $order->info['payment_method'] = $payment_method;
    $order->info['payment_module_code'] = $google_checkout->code;
    $order->info['shipping_method'] = $shipping_method_name;
    $order->info['shipping_module_code'] = $shipping_method_code;
    $order->info['cc_type'] = '';
    $order->info['cc_owner'] = '';
    $order->info['cc_number'] = '';
    $order->info['cc_expires'] = '';
    $order->info['order_status'] = GC_STATE_NEW;
    $order->info['tax'] = $tax_amt;
    $order->info['currency'] = $gc_data[$root]['order-total']['currency'];
    $order->info['currency_value'] = 1;
    //$customers_ip_address'] = $gc_data[$root]['shopping-cart']['merchant-private-data']['ip-address']['VALUE'];
    $order->info['comments'] = GOOGLECHECKOUT_STATE_NEW_ORDER_NUM . $gc_data[$root]['google-order-number']['VALUE'] . "\n" . GOOGLECHECKOUT_STATE_NEW_ORDER_MC_USED . (@$gc_data[$root]['order-adjustment']['merchant-calculation-successful']['VALUE'] == 'true' ? 'True' : 'False') . ($new_user ? "\n" . GOOGLECHECKOUT_STATE_NEW_ORDER_BUYER_USER . $gc_data[$root]['buyer-billing-address']['email']['VALUE'] . "\n" . GOOGLECHECKOUT_STATE_NEW_ORDER_BUYER_PASS . $gc_data[$root]['buyer-id']['VALUE'] : '');
    $coupons = gc_get_arr_result(@$gc_data[$root]['order-adjustment']['merchant-codes']['coupon-adjustment']);
    //$gift_cert = get_arr_result(@$gc_data[$root]['order-adjustment']['merchant-codes']['gift-certificate-adjustment']);
    $items = gc_get_arr_result($gc_data[$root]['shopping-cart']['items']['item']);
    // Get Coustoms OT
    $custom_order_totals_total = 0;
    $custom_order_totals = array();
    $order->products = array();
    foreach ($items as $item) {
        if (isset($item['merchant-private-item-data']['item']['VALUE'])) {
            $order->products[] = unserialize(base64_decode($item['merchant-private-item-data']['item']['VALUE']));
        } else {
            if ($item['merchant-private-item-data']['order_total']['VALUE']) {
                $order_total = unserialize(base64_decode($item['merchant-private-item-data']['order_total']['VALUE']));
                $custom_order_totals[] = $order_total;
                $order_total_value = $order_total['value'] * (strrpos($order_total['text'], '-') === false ? 1 : -1);
                $custom_order_totals_total += $currencies->get_value($gc_data[$root]['order-total']['currency']) * $order_total_value;
            } else {
                // For invoices.
                $order->products[] = array('qty' => $item['quantity']['VALUE'], 'name' => $item['item-name']['VALUE'], 'model' => $item['item-description']['VALUE'], 'tax' => 0, 'tax_description' => @$item['tax-table-selector']['VALUE'], 'price' => $item['unit-price']['VALUE'], 'final_price' => $item['unit-price']['VALUE'], 'onetime_charges' => 0, 'weight' => 0, 'products_priced_by_attribute' => 0, 'product_is_free' => 0, 'products_discount_type' => 0, 'products_discount_type_from' => 0, 'id' => @$item['merchant-item-id']['VALUE']);
            }
        }
    }
    $cart = new shoppingCart();
    $prod_attr = gc_get_prattr($order->products);
    foreach ($prod_attr as $product_id => $item_data) {
        //$products_id, $qty = '1', $attributes = '
        $cart->add_cart($product_id, $item_data['qty'], $item_data['attr']);
    }
    // Update values so that order_total modules get the correct values.
    $order->info['total'] = $gc_data[$root]['order-total']['VALUE'];
    $order->info['subtotal'] = $gc_data[$root]['order-total']['VALUE'] - ($shipping_cost + $tax_amt) + @$coupons[0]['applied-amount']['VALUE'] - $custom_order_totals_total;
    $order->info['coupon_code'] = @$coupons[0]['code']['VALUE'];
    $order->info['shipping_method'] = $shipping;
    $order->info['shipping_cost'] = $shipping_cost;
    $order->info['tax_groups']['tax'] = $tax_amt;
    $order->info['currency'] = $gc_data[$root]['order-total']['currency'];
    $order->info['currency_value'] = 1;
    require DIR_WS_CLASSES . 'order_total.php';
    $order_total_modules = new order_total();
    // Disable OT sent as items in the GC cart
    foreach ($order_total_modules->modules as $order_total_code => $order_total) {
        if (!in_array(substr($order_total, 0, strrpos($order_total, '.')), $google_checkout->ignore_order_total)) {
            unset($order_total_modules->modules[$order_total_code]);
        }
    }
    $order_totals = $order_total_modules->process();
    // Not necessary, since order totals are already disabled.
    //foreach($order_totals as $order_total_code => $order_total){
    //  if(!in_array($order_total['code'], $google_checkout->ignore_order_total)){
    //    unset($order_totals[$order_total_code]);
    //  }
    //}
    // Merge all order totals.
    $order_totals = array_merge($order_totals, $custom_order_totals);
    if (isset($gc_data[$root]['order-adjustment']['merchant-codes']['coupon-adjustment'])) {
        $order_totals[] = array('code' => 'ot_coupon', 'title' => "<b>" . MODULE_ORDER_TOTAL_COUPON_TITLE . " " . @$coupons[0]['code']['VALUE'] . ":</b>", 'text' => $currencies->format(@$coupons[0]['applied-amount']['VALUE'] * -1, false, @$coupons[0]['applied-amount']['currency']), 'value' => @$coupons[0]['applied-amount']['VALUE'], 'sort_order' => 280);
    }
    function order_total_compare($a, $b)
    {
        if ($a['sort_order'] == $b['sort_order']) {
            return 0;
        } else {
            return $a['sort_order'] < $b['sort_order'] ? -1 : 1;
        }
    }
    usort($order_totals, "order_total_compare");
    $sql_data_array = array('customers_id' => $customer_id, 'customers_name' => $order->customer['firstname'] . ' ' . $order->customer['lastname'], 'customers_company' => $order->customer['company'], 'customers_street_address' => $order->customer['street_address'], 'customers_suburb' => $order->customer['suburb'], 'customers_city' => $order->customer['city'], 'customers_postcode' => $order->customer['postcode'], 'customers_state' => $order->customer['state'], 'customers_country' => $order->customer['country']['title'], 'customers_telephone' => $order->customer['telephone'], 'customers_email_address' => $order->customer['email_address'], 'customers_address_format_id' => $order->customer['format_id'], 'delivery_name' => $order->delivery['firstname'] . ' ' . $order->delivery['lastname'], 'delivery_company' => $order->delivery['company'], 'delivery_street_address' => $order->delivery['street_address'], 'delivery_suburb' => $order->delivery['suburb'], 'delivery_city' => $order->delivery['city'], 'delivery_postcode' => $order->delivery['postcode'], 'delivery_state' => $order->delivery['state'], 'delivery_country' => $order->delivery['country']['title'], 'delivery_address_format_id' => $order->delivery['format_id'], 'billing_name' => $order->billing['firstname'] . ' ' . $order->billing['lastname'], 'billing_company' => $order->billing['company'], 'billing_street_address' => $order->billing['street_address'], 'billing_suburb' => $order->billing['suburb'], 'billing_city' => $order->billing['city'], 'billing_postcode' => $order->billing['postcode'], 'billing_state' => $order->billing['state'], 'billing_country' => $order->billing['country']['title'], 'billing_address_format_id' => $order->billing['format_id'], 'payment_method' => $order->info['payment_method'], 'cc_type' => $order->info['cc_type'], 'cc_owner' => $order->info['cc_owner'], 'cc_number' => $order->info['cc_number'], 'cc_expires' => $order->info['cc_expires'], 'date_purchased' => 'now()', 'orders_status' => $order->info['order_status'], 'currency' => $order->info['currency'], 'currency_value' => $order->info['currency_value']);
    tep_db_perform(TABLE_ORDERS, $sql_data_array);
    $insert_id = tep_db_insert_id();
    for ($i = 0, $n = sizeof($order_totals); $i < $n; $i++) {
        $sql_data_array = array('orders_id' => $insert_id, 'title' => $order_totals[$i]['title'], 'text' => $order_totals[$i]['text'], 'value' => $order_totals[$i]['value'], 'class' => $order_totals[$i]['code'], 'sort_order' => $order_totals[$i]['sort_order']);
        tep_db_perform(TABLE_ORDERS_TOTAL, $sql_data_array);
    }
    $customer_notification = SEND_EMAILS == 'true' ? '1' : '0';
    $sql_data_array = array('orders_id' => $insert_id, 'orders_status_id' => $order->info['order_status'], 'date_added' => 'now()', 'customer_notified' => $customer_notification, 'comments' => $order->info['comments']);
    tep_db_perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);
    // Initialized for the email confirmation.
    $products_ordered = '';
    $subtotal = 0;
    $total_tax = 0;
    $total_weight = 0;
    $total_products_price = 0;
    $products_tax = 0;
    $total_cost = 0;
    for ($i = 0, $n = sizeof($order->products); $i < $n; $i++) {
        // Stock Update - Joao Correia.
        if (STOCK_LIMITED == 'true') {
            if (DOWNLOAD_ENABLED == 'true') {
                $stock_query_raw = "SELECT products_quantity, pad.products_attributes_filename\n                            FROM " . TABLE_PRODUCTS . " p\n                            LEFT JOIN " . TABLE_PRODUCTS_ATTRIBUTES . " pa\n                             ON p.products_id=pa.products_id\n                            LEFT JOIN " . TABLE_PRODUCTS_ATTRIBUTES_DOWNLOAD . " pad\n                             ON pa.products_attributes_id=pad.products_attributes_id\n                            WHERE p.products_id = '" . tep_get_prid($order->products[$i]['id']) . "'";
                // Will work with only one option for downloadable products
                // otherwise, we have to build the query dynamically with a loop
                $products_attributes = @$order->products[$i]['attributes'];
                if (is_array($products_attributes)) {
                    $stock_query_raw .= " AND pa.options_id = '" . $products_attributes[0]['option_id'] . "' AND pa.options_values_id = '" . $products_attributes[0]['value_id'] . "'";
                }
                $stock_query = tep_db_query($stock_query_raw);
            } else {
                $stock_query = tep_db_query("select products_quantity from " . TABLE_PRODUCTS . " where products_id = '" . tep_get_prid($order->products[$i]['id']) . "'");
            }
            if (tep_db_num_rows($stock_query) > 0) {
                $stock_values = tep_db_fetch_array($stock_query);
                // Do not decrement quantities if products_attributes_filename exists
                if (DOWNLOAD_ENABLED != 'true' || !$stock_values['products_attributes_filename']) {
                    $stock_left = $stock_values['products_quantity'] - $order->products[$i]['qty'];
                } else {
                    $stock_left = $stock_values['products_quantity'];
                }
                tep_db_query("update " . TABLE_PRODUCTS . " set products_quantity = '" . $stock_left . "' where products_id = '" . tep_get_prid($order->products[$i]['id']) . "'");
                if ($stock_left < 1 && STOCK_ALLOW_CHECKOUT == 'false') {
                    tep_db_query("update " . TABLE_PRODUCTS . " set products_status = '0' where products_id = '" . tep_get_prid($order->products[$i]['id']) . "'");
                }
            }
        }
        // Update products_ordered (for bestsellers list)
        tep_db_query("update " . TABLE_PRODUCTS . " set products_ordered = products_ordered + " . sprintf('%d', $order->products[$i]['qty']) . " where products_id = '" . tep_get_prid($order->products[$i]['id']) . "'");
        $sql_data_array = array('orders_id' => $insert_id, 'products_id' => tep_get_prid($order->products[$i]['id']), 'products_model' => $order->products[$i]['model'], 'products_name' => $order->products[$i]['name'], 'products_price' => $order->products[$i]['price'], 'final_price' => $order->products[$i]['final_price'], 'products_tax' => $order->products[$i]['tax'], 'products_quantity' => $order->products[$i]['qty']);
        tep_db_perform(TABLE_ORDERS_PRODUCTS, $sql_data_array);
        $order_products_id = tep_db_insert_id();
        // Insert customer-chosen options into order.
        $attributes_exist = '0';
        $products_ordered_attributes = '';
        if (isset($order->products[$i]['attributes'])) {
            $attributes_exist = '1';
            for ($j = 0, $n2 = sizeof($order->products[$i]['attributes']); $j < $n2; $j++) {
                if (DOWNLOAD_ENABLED == 'true') {
                    $attributes_query = "select popt.products_options_name, poval.products_options_values_name, pa.options_values_price, pa.price_prefix, pad.products_attributes_maxdays, pad.products_attributes_maxcount , pad.products_attributes_filename\n                               from " . TABLE_PRODUCTS_OPTIONS . " popt, " . TABLE_PRODUCTS_OPTIONS_VALUES . " poval, " . TABLE_PRODUCTS_ATTRIBUTES . " pa\n                               left join " . TABLE_PRODUCTS_ATTRIBUTES_DOWNLOAD . " pad\n                                on pa.products_attributes_id=pad.products_attributes_id\n                               where pa.products_id = '" . $order->products[$i]['id'] . "'\n                                and pa.options_id = '" . $order->products[$i]['attributes'][$j]['option_id'] . "'\n                                and pa.options_id = popt.products_options_id\n                                and pa.options_values_id = '" . $order->products[$i]['attributes'][$j]['value_id'] . "'\n                                and pa.options_values_id = poval.products_options_values_id\n                                and popt.language_id = '" . $languages_id . "'\n                                and poval.language_id = '" . $languages_id . "'";
                    $attributes = tep_db_query($attributes_query);
                } else {
                    $attributes = tep_db_query("select popt.products_options_name, poval.products_options_values_name, pa.options_values_price, pa.price_prefix from " . TABLE_PRODUCTS_OPTIONS . " popt, " . TABLE_PRODUCTS_OPTIONS_VALUES . " poval, " . TABLE_PRODUCTS_ATTRIBUTES . " pa where pa.products_id = '" . $order->products[$i]['id'] . "' and pa.options_id = '" . $order->products[$i]['attributes'][$j]['option_id'] . "' and pa.options_id = popt.products_options_id and pa.options_values_id = '" . $order->products[$i]['attributes'][$j]['value_id'] . "' and pa.options_values_id = poval.products_options_values_id and popt.language_id = '" . $languages_id . "' and poval.language_id = '" . $languages_id . "'");
                }
                $attributes_values = tep_db_fetch_array($attributes);
                $sql_data_array = array('orders_id' => $insert_id, 'orders_products_id' => $order_products_id, 'products_options' => $attributes_values['products_options_name'], 'products_options_values' => $attributes_values['products_options_values_name'], 'options_values_price' => $attributes_values['options_values_price'], 'price_prefix' => $attributes_values['price_prefix']);
                tep_db_perform(TABLE_ORDERS_PRODUCTS_ATTRIBUTES, $sql_data_array);
                if (DOWNLOAD_ENABLED == 'true' && isset($attributes_values['products_attributes_filename']) && tep_not_null($attributes_values['products_attributes_filename'])) {
                    $sql_data_array = array('orders_id' => $insert_id, 'orders_products_id' => $order_products_id, 'orders_products_filename' => $attributes_values['products_attributes_filename'], 'download_maxdays' => $attributes_values['products_attributes_maxdays'], 'download_count' => $attributes_values['products_attributes_maxcount']);
                    tep_db_perform(TABLE_ORDERS_PRODUCTS_DOWNLOAD, $sql_data_array);
                }
                $products_ordered_attributes .= "\n\t" . $attributes_values['products_options_name'] . ' ' . $attributes_values['products_options_values_name'];
            }
        }
        $total_weight += $order->products[$i]['qty'] * $order->products[$i]['weight'];
        $total_tax += tep_calculate_tax($total_products_price, $products_tax) * $order->products[$i]['qty'];
        $total_cost += $total_products_price;
        $products_ordered .= $order->products[$i]['qty'] . ' x ' . $order->products[$i]['name'] . ' (' . $order->products[$i]['model'] . ') = ' . $currencies->display_price($order->products[$i]['final_price'], $order->products[$i]['tax'], $order->products[$i]['qty']) . $products_ordered_attributes . "\n";
    }
    // FOR COUPON SUPPORT
    /*
    $insert_id = $order->create($order_totals, 2);
    //$order_total_modules = new order_total();
    // Store the product info to the order.
    $order->create_add_products($insert_id);
    //$order_number_created'] = $insert_id;
    // Add coupon to redeem track.
    if (isset ($gc_data[$root]['order-adjustment']['merchant-codes']['coupon-adjustment'])) {
      $sql = "select coupon_id
                              from " . TABLE_COUPONS . "
                              where coupon_code= :couponCodeEntered
                              and coupon_active='Y'";
      $sql = $db->bindVars($sql, ':couponCodeEntered', $coupons[0]['code']['VALUE'], 'string');
    
      $coupon_result = tep_db_query($sql);
      $cc_id = $coupon_result['coupon_id'];
    
      tep_db_query("insert into " . TABLE_COUPON_REDEEM_TRACK . "
                                  (coupon_id, redeem_date, redeem_ip, customer_id, order_id)
                                  values ('" . (int) $cc_id . "', now(), '" .
      $gc_data[$root]['shopping-cart']['merchant-private-data']['ip-address']['VALUE'] .
      "', '" . (int) $customer_id . "', '" . (int) $insert_id . "')");
      $cc_id = "";
    }
    */
    // Add the order details to the table.
    // This table could be modified to hold the merchant id and key if required
    // so that different mids and mkeys can be used for different orders.
    tep_db_query("insert into " . $google_checkout->table_order . " values (" . $insert_id . ", " . gc_make_sql_string($gc_data[$root]['google-order-number']['VALUE']) . ", " . gc_make_sql_float($gc_data[$root]['order-total']['VALUE']) . ")");
    $cart->reset(TRUE);
    tep_session_unregister('sendto');
    tep_session_unregister('billto');
    tep_session_unregister('shipping');
    tep_session_unregister('payment');
    tep_session_unregister('comments');
    $google_response->SendAck();
}
 function payment_redirect($cart = false, $approval = false, $order_exists = false)
 {
     global $order, $xtPrice;
     // auth
     $apiContext = $this->apiContext();
     // set payment
     $payer = new Payer();
     $payer->setPaymentMethod('paypal');
     if ($this->code == 'paypalinstallment') {
         $payer->setExternalSelectedFundingInstrumentType('CREDIT');
     }
     // set payer_info
     $payer_info = new PayerInfo();
     // set items
     $item = array();
     // set details
     $this->details = new Details();
     // set amount
     $this->amount = new Amount();
     // set ItemList
     $itemList = new ItemList();
     // set redirect
     $redirectUrls = new RedirectUrls();
     // set address
     $shipping_address = new ShippingAddress();
     if ($cart === true) {
         $products = $_SESSION['cart']->get_products();
         for ($i = 0, $n = sizeof($products); $i < $n; $i++) {
             $item[$i] = new Item();
             $item[$i]->setName($this->encode_utf8($products[$i]['name']))->setCurrency($_SESSION['currency'])->setQuantity($products[$i]['quantity'])->setPrice($products[$i]['price'])->setSku($products[$i]['model'] != '' ? $products[$i]['model'] : $products[$i]['id']);
             $this->details->setSubtotal($this->details->getSubtotal() + $products[$i]['final_price']);
         }
         $total = $price = $_SESSION['cart']->show_total();
         if ($_SESSION['customers_status']['customers_status_ot_discount_flag'] == 1 && $_SESSION['customers_status']['customers_status_ot_discount'] != '0.00') {
             if ($_SESSION['customers_status']['customers_status_show_price_tax'] == 0 && $_SESSION['customers_status']['customers_status_add_tax_ot'] == 1) {
                 $price = $total - $_SESSION['cart']->show_tax(false);
             }
             $this->details->setShippingDiscount($this->details->getShippingDiscount() + $xtPrice->xtcGetDC($price, $_SESSION['customers_status']['customers_status_ot_discount']) * -1);
         }
         $this->amount->setTotal($total + $this->details->getShippingDiscount());
         if ($_SESSION['customers_status']['customers_status_show_price_tax'] == 0 && $_SESSION['customers_status']['customers_status_add_tax_ot'] == 1 && MODULE_SMALL_BUSINESS != 'true') {
             foreach ($_SESSION['cart']->tax as $tax) {
                 $this->details->setTax($this->details->getTax() + $tax['value']);
             }
             $total = $this->calc_total();
             $amount_total = $this->amount->getTotal();
             if ((string) $amount_total != (string) $total) {
                 $this->details->setTax($this->details->getTax() + ($amount_total - $total));
             }
         }
         $shipping_cost = $this->get_config('MODULE_PAYMENT_' . strtoupper($this->code) . '_SHIPPING_COST');
         if ((int) $shipping_cost > 0) {
             $i = count($item);
             $item[$i] = new Item();
             $item[$i]->setName($this->encode_utf8(PAYPAL_EXP_VORL))->setCurrency($_SESSION['currency'])->setQuantity(1)->setPrice($shipping_cost);
             $this->amount->setTotal($this->amount->getTotal() + $shipping_cost);
             $this->details->setSubtotal($this->amount->getTotal());
         }
         // set amount
         $this->amount->setCurrency($_SESSION['currency'])->setDetails($this->details);
         // set redirect
         $redirectUrls->setReturnUrl($this->link_encoding(xtc_href_link('callback/paypal/paypalcart.php', '', 'SSL')))->setCancelUrl($this->link_encoding(xtc_href_link(FILENAME_SHOPPING_CART, 'payment_error=' . $this->code, 'SSL')));
     } else {
         $shipping_address->setRecipientName($this->encode_utf8($order->delivery['firstname'] . ' ' . $order->delivery['lastname']))->setLine1($this->encode_utf8($order->delivery['street_address']))->setCity($this->encode_utf8($order->delivery['city']))->setCountryCode($this->encode_utf8($order_exists === false ? $order->delivery['country']['iso_code_2'] : $order->delivery['country_iso_2']))->setPostalCode($this->encode_utf8($order->delivery['postcode']))->setState($this->encode_utf8($order->delivery['state'] != '' ? xtc_get_zone_code($order->delivery['country_id'], $order->delivery['zone_id'], $order->delivery['state']) : ''));
         if ($order->delivery['suburb'] != '') {
             $shipping_address->setLine2($this->encode_utf8($order->delivery['suburb']));
         }
         $subtotal = 0;
         for ($i = 0, $n = sizeof($order->products); $i < $n; $i++) {
             $item[$i] = new Item();
             $item[$i]->setName($this->encode_utf8($order->products[$i]['name']))->setCurrency($order->info['currency'])->setQuantity($order->products[$i]['qty'])->setPrice($order->products[$i]['price'])->setSku($order->products[$i]['model'] != '' ? $order->products[$i]['model'] : $order->products[$i]['id']);
             $subtotal += $order->products[$i]['price'] * $order->products[$i]['qty'];
         }
         // set totals
         if ($order_exists === false) {
             if (!class_exists('order_total')) {
                 require_once DIR_WS_CLASSES . 'order_total.php';
             }
             $order_total_modules = new order_total();
             $order_totals = $order_total_modules->process();
             $this->get_totals($order_totals, true, $subtotal);
         } else {
             $this->get_totals($order->totals);
         }
         // set amount
         $this->amount->setCurrency($order->info['currency'])->setDetails($this->details);
         // set redirect
         if ($order_exists === false) {
             $redirectUrls->setReturnUrl($this->link_encoding(xtc_href_link(FILENAME_CHECKOUT_PROCESS, '', 'SSL')))->setCancelUrl($this->link_encoding(xtc_href_link(FILENAME_CHECKOUT_PAYMENT, 'payment_error=' . $this->code, 'SSL')));
         } else {
             $redirectUrls->setReturnUrl($this->link_encoding(xtc_href_link('callback/paypal/' . $this->code . '.php', 'oID=' . $order->info['order_id'] . '&key=' . md5($order->customer['email_address']), 'SSL')))->setCancelUrl($this->link_encoding(xtc_href_link('callback/paypal/' . $this->code . '.php', 'payment_error=' . $this->code . '&oID=' . $order->info['order_id'] . '&key=' . md5($order->customer['email_address']), 'SSL')));
         }
         if ($this->code == 'paypalinstallment') {
             $redirectUrls->setReturnUrl($this->link_encoding(xtc_href_link(FILENAME_CHECKOUT_CONFIRMATION, 'conditions=true', 'SSL')));
         }
     }
     // set ItemList
     if ($this->get_config('PAYPAL_ADD_CART_DETAILS') == '0' || $this->check_discount() === true) {
         $item = array();
         $item[0] = new Item();
         $item[0]->setName($this->encode_utf8(MODULE_PAYMENT_PAYPAL_TEXT_ORDER))->setCurrency($_SESSION['currency'])->setQuantity(1)->setPrice($this->details->getSubtotal());
         if ($cart === true) {
             $shipping_cost = $this->get_config('MODULE_PAYMENT_' . strtoupper($this->code) . '_SHIPPING_COST');
             if ((int) $shipping_cost > 0) {
                 $item[1] = new Item();
                 $item[1]->setName($this->encode_utf8(PAYPAL_EXP_VORL))->setCurrency($_SESSION['currency'])->setQuantity(1)->setPrice($shipping_cost);
                 $this->amount->setTotal($this->amount->getTotal() + $shipping_cost);
                 $this->details->setSubtotal($this->amount->getTotal());
             }
         }
     }
     $itemList->setItems($item);
     // profile
     $address_override = false;
     $profile_id = $this->get_config('PAYPAL_' . strtoupper($this->code . '_' . $_SESSION['language_code']) . '_PROFILE');
     if ($profile_id == '') {
         $profile_id = $this->get_config('PAYPAL_STANDARD_PROFILE');
     }
     if ($profile_id != '') {
         if ($this->get_config(strtoupper($profile_id) . '_TIME') < time() - 3600 * 24) {
             $profile = $this->get_profile($profile_id);
             $sql_data_array = array(array('config_key' => strtoupper($profile_id) . '_TIME', 'config_value' => time()), array('config_key' => strtoupper($profile_id) . '_ADDRESS', 'config_value' => $profile[0]['input_fields']['address_override']));
             $this->save_config($sql_data_array);
             $address_override = $profile[0]['input_fields']['address_override'] == '0' ? true : false;
         } else {
             $address_override = $this->get_config(strtoupper($profile_id) . '_ADDRESS') == '0' ? true : false;
         }
     }
     if ($cart === false && $approval === false && $address_override === false || $order_exists === true || $this->code == 'paypalinstallment') {
         $itemList->setShippingAddress($shipping_address);
     }
     if ($this->code == 'paypalinstallment') {
         // set payment address
         $payment_address = new Address();
         $payment_address->setLine1($this->encode_utf8($order->billing['street_address']))->setCity($this->encode_utf8($order->billing['city']))->setState($this->encode_utf8($order->billing['state'] != '' ? xtc_get_zone_code($order->billing['country_id'], $order->billing['zone_id'], $order->billing['state']) : ''))->setPostalCode($this->encode_utf8($order->billing['postcode']))->setCountryCode($this->encode_utf8($order->billing['country']['iso_code_2']));
         if ($order->billing['suburb'] != '') {
             $payment_address->setLine2($this->encode_utf8($order->billing['suburb']));
         }
         $payer_info->setBillingAddress($payment_address)->setShippingAddress($shipping_address)->setEmail($this->encode_utf8($order->customer['email_address']))->setFirstName($this->encode_utf8($order->delivery['firstname']))->setLastName($this->encode_utf8($order->delivery['lastname']));
         $payer->setPayerInfo($payer_info);
     }
     // set transaction
     $transaction = new Transaction();
     $transaction->setAmount($this->amount)->setItemList($itemList)->setDescription($this->encode_utf8(STORE_NAME))->setInvoiceNumber(uniqid());
     // set payment
     $payment = new Payment();
     $payment->setIntent($this->transaction_type)->setPayer($payer)->setRedirectUrls($redirectUrls)->setTransactions(array($transaction))->setCreateTime(time());
     if (isset($profile_id) && $profile_id != '') {
         $payment->setExperienceProfileId($profile_id);
     }
     try {
         $payment->create($apiContext);
         $_SESSION['paypal']['paymentId'] = $payment->getId();
         $approval_link = $payment->getApprovalLink();
         if ($approval === false) {
             xtc_redirect($approval_link);
         } else {
             return $approval_link;
         }
     } catch (Exception $ex) {
         $this->LoggingManager->log(print_r($ex, true), 'DEBUG');
         unset($_SESSION['paypal']);
         if ($cart === true) {
             xtc_redirect(xtc_href_link(FILENAME_SHOPPING_CART, 'payment_error=' . $this->code, 'SSL'));
         } elseif ($this->code != 'paypalplus') {
             xtc_redirect(xtc_href_link(FILENAME_CHECKOUT_PAYMENT, 'payment_error=' . $this->code, 'SSL'));
         }
     }
 }
 /**
  * send data to SOFORT and check SOFORT-response - overwriten by Rbs-Modul
  * @return array with paymentUrl, api-errors, trans-id, payment-secret
  */
 function _makeSofortApiCall()
 {
     global $order, $xtPrice;
     $customer_id = $_SESSION['customer_id'];
     $currency = $_SESSION['currency'];
     $reasons = $this->_getReasons($this->paymentMethod, $customer_id, $order);
     $user_variable_0 = '';
     $user_variable_1 = $customer_id;
     /*
     		$session = session_name() . '=' . session_id();
     
     		if (ENABLE_SSL == true)
     			$server = HTTPS_SERVER;
     		else
     			$server = HTTP_SERVER;
     */
     $paymentSecret = md5(mt_rand() . microtime());
     //important notice: following lines also modify the shippingcosts
     $orderTotals = array();
     if (MODULE_ORDER_TOTAL_INSTALLED) {
         require_once DIR_WS_CLASSES . 'order_total.php';
         $orderTotalModules = new order_total();
         //Following function-call manipulates variables (e.g. prices) within $order! Never call more than once!
         $orderTotals = $orderTotalModules->process();
     }
     $amount = $this->_getShopTotal($orderTotals);
     //$success_url = $server.DIR_WS_CATALOG.'callback/sofort/ressources/scripts/sofortReturn.php?sofortaction=success&sofortcode='.$this->code;
     //$cancel_url = $server.DIR_WS_CATALOG.'callback/sofort/ressources/scripts/sofortReturn.php?sofortaction=cancel&sofortcode='.$this->code;
     //$notification_url = $server . DIR_WS_CATALOG . 'callback/sofort/callback.php?paymentSecret='.$paymentSecret.'&action=multipay';
     $success_url = xtc_href_link('callback/sofort/ressources/scripts/sofortReturn.php', 'sofortaction=success&sofortcode=' . $this->code, 'SSL');
     $cancel_url = xtc_href_link('callback/sofort/ressources/scripts/sofortReturn.php', 'sofortaction=cancel&sofortcode=' . $this->code, 'SSL');
     $notification_url = xtc_href_link('callback/sofort/callback.php', 'paymentSecret=' . $paymentSecret . '&action=multipay', 'SSL');
     $this->sofort->setAmount($amount, $currency);
     $this->sofort->setReason(HelperFunctions::convertEncoding($reasons[0], 3), HelperFunctions::convertEncoding($reasons[1], 3));
     $this->sofort->setSuccessUrl(HelperFunctions::convertEncoding($success_url, 4));
     $this->sofort->setAbortUrl(HelperFunctions::convertEncoding($cancel_url, 4));
     $this->sofort->setTimeoutUrl(HelperFunctions::convertEncoding($cancel_url, 4));
     $this->sofort->setNotificationUrl(HelperFunctions::convertEncoding($notification_url, 4));
     $this->sofort->addUserVariable(HelperFunctions::convertEncoding($user_variable_0, 3));
     $this->sofort->addUserVariable(HelperFunctions::convertEncoding($user_variable_1, 3));
     $this->sofort->setEmailCustomer(HelperFunctions::convertEncoding($order->customer['email_address'], 3));
     $this->sofort->setPhoneNumberCustomer($order->customer['telephone']);
     switch ($this->paymentMethod) {
         case 'SU':
             $this->sofort->setSofortueberweisung($amount);
             // see if customer protection is enabled, set it as parameter to sofortlib
             $this->sofort->setSofortueberweisungCustomerprotection(MODULE_PAYMENT_SOFORT_SU_KS_STATUS == 'True');
             break;
         case 'SL':
             $this->sofort->setSofortlastschrift();
             $this->sofort->setSenderAccount('', '', HelperFunctions::convertEncoding($order->customer['firstname'], 3) . ' ' . HelperFunctions::convertEncoding($order->customer['lastname'], 3));
             break;
         case 'LS':
             $this->sofort->setLastschrift();
             $this->sofort->setSenderAccount(HelperFunctions::convertEncoding($_SESSION['sofort']['ls_bank_code'], 3), HelperFunctions::convertEncoding($_SESSION['sofort']['ls_account_number'], 3), HelperFunctions::convertEncoding($_SESSION['sofort']['ls_sender_holder'], 3));
             $billingSalutation = $this->_getGenderFromAddressBook($order->billing['firstname'], $order->billing['lastname'], $order->billing['company'], $order->billing['street_address'], $order->billing['postcode'], $order->billing['city'], $order->billing['country_id'], $order->billing['zone_id']);
             //split street and number
             if (!preg_match('#(.+)[ .](.+)#i', trim($order->billing['street_address']), $streetparts)) {
                 $streetparts = array();
                 $streetparts[1] = trim($order->billing['street_address']);
                 $streetparts[2] = '';
             }
             //if there is an entry in "suburb" (german: "Adresszusatz"), put it in front of the streetname
             if ($order->billing['suburb']) {
                 $streetparts[1] = $order->billing['suburb'] . ' - ' . $streetparts[1];
             }
             $this->sofort->setLastschriftAddress(HelperFunctions::convertEncoding($order->billing['firstname'], 3), HelperFunctions::convertEncoding($order->billing['lastname'], 3), HelperFunctions::convertEncoding($streetparts[1], 3), HelperFunctions::convertEncoding($streetparts[2], 3), $order->billing['postcode'], HelperFunctions::convertEncoding($order->billing['city'], 3), HelperFunctions::convertEncoding($billingSalutation, 3), HelperFunctions::convertEncoding($order->billing['country']['iso_code_2'], 3));
             break;
         case 'SV':
             $this->sofort->setSofortvorkasse();
             // if this is called a 'test transaction', add a sender account
             if (getenv('test_sv') == true) {
                 $this->sofort->setSenderAccount('00000', '12345', 'Tester Testaccount');
             }
             $this->sofort->setSofortvorkasseCustomerprotection(MODULE_PAYMENT_SOFORT_SV_KS_STATUS == 'True');
             break;
     }
     $this->sofort->sendRequest();
     $return = array();
     $return['apiCallErrors'] = $this->sofort->getErrors();
     $return['paymentUrl'] = $this->sofort->getPaymentUrl();
     $return['transactionId'] = $this->sofort->getTransactionId();
     $return['paymentSecret'] = $paymentSecret;
     $return['orderTotalModules'] = $orderTotalModules;
     $return['orderTotals'] = $orderTotals;
     return $return;
 }
 /**
  * If the EC flow has to be interrupted for any reason, this does the appropriate cleanup and displays status/error messages.
  */
 function terminateEC($error_msg = '', $kill_sess_vars = false, $goto_page = '')
 {
     global $messageStack, $order, $order_total_modules;
     $stackAlert = 'header';
     // debug
     $this->_doDebug('PayPal test Log - terminateEC-A', "goto page: " . $goto_page . "\nerror_msg: " . $error_msg . "\n\nSession data: " . print_r($_SESSION, true));
     if ($kill_sess_vars) {
         if (!empty($_SESSION['paypal_ec_temp'])) {
             $this->ec_delete_user($_SESSION['customer_id']);
         }
         // Unregister the paypal session variables, making the user start over.
         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']);
         // debug
         $this->zcLog('termEC-1', 'Killed the session vars as requested');
     }
     $this->zcLog('termEC-2', 'BEFORE: $this->showPaymentPage = ' . (int) $this->showPaymentPage . "\nToken Data:" . $_SESSION['paypal_ec_token']);
     // force display of payment page if GV/DC active for this customer
     if (MODULE_ORDER_TOTAL_INSTALLED && $this->showPaymentPage !== true && isset($_SESSION['paypal_ec_token'])) {
         require_once DIR_WS_CLASSES . 'order.php';
         $order = new order();
         require_once DIR_WS_CLASSES . 'order_total.php';
         $order_total_modules = new order_total();
         $order_totals = $order_total_modules->process();
         $selection = $order_total_modules->credit_selection();
         if (sizeof($selection) > 0) {
             $this->showPaymentPage = true;
         }
     }
     // if came from Payment page, don't go back to it
     if ($_SESSION['paypal_ec_markflow'] == 1) {
         $this->showPaymentPage = false;
     }
     // if in DP mode, don't go to payment page ... we've already been there to get here
     if ($goto_page == FILENAME_CHECKOUT_PROCESS) {
         $this->showPaymentPage = false;
     }
     // debug
     $this->zcLog('termEC-3', 'AFTER: $this->showPaymentPage = ' . (int) $this->showPaymentPage);
     if (!empty($_SESSION['customer_first_name']) && !empty($_SESSION['customer_id'])) {
         if ($this->showPaymentPage === true || $goto_page == FILENAME_CHECKOUT_PAYMENT) {
             // debug
             $this->zcLog('termEC-4', 'We ARE logged in, and $this->showPaymentPage === true');
             // if no shipping selected or if shipping cost is < 0 goto shipping page
             if (!$_SESSION['shipping'] || $_SESSION['shipping'] == '' || $_SESSION['shipping']['cost'] < 0) {
                 // debug
                 $this->zcLog('termEC-5', 'Have no shipping method selected, or shipping < 0 so set FILENAME_CHECKOUT_SHIPPING');
                 $redirect_path = FILENAME_CHECKOUT_SHIPPING;
                 $stackAlert = 'checkout_shipping';
             } else {
                 // debug
                 $this->zcLog('termEC-6', 'We DO have a shipping method selected, so goto PAYMENT');
                 $redirect_path = FILENAME_CHECKOUT_PAYMENT;
                 $stackAlert = 'checkout_payment';
             }
         } elseif ($goto_page) {
             // debug
             $this->zcLog('termEC-7', '$this->showPaymentPage NOT true, and have custom page parameter: ' . $goto_page);
             $redirect_path = $goto_page;
             $stackAlert = 'header';
             if ($goto_page == FILENAME_SHOPPING_CART) {
                 $stackAlert = 'shopping_cart';
             }
         } else {
             // debug
             $this->zcLog('termEC-8', '$this->showPaymentPage NOT true, and NO custom page selected ... using SHIPPING as default');
             $redirect_path = FILENAME_CHECKOUT_SHIPPING;
             $stackAlert = 'checkout_shipping';
         }
     } else {
         // debug
         $this->zcLog('termEC-9', 'We are NOT logged in, so set snapshot to Shipping page, and redirect to login');
         $_SESSION['navigation']->set_snapshot(FILENAME_CHECKOUT_SHIPPING);
         $redirect_path = FILENAME_LOGIN;
         $stackAlert = 'login';
     }
     if ($error_msg) {
         $messageStack->add_session($stackAlert, $error_msg, 'error');
     }
     // debug
     $this->zcLog('termEC-10', 'Redirecting to ' . $redirect_path . ' - Stack: ' . $stackAlert . "\n" . 'Message: ' . $error_msg . "\nSession Data: " . print_r($_SESSION, true));
     zen_redirect(zen_href_link($redirect_path, '', 'SSL', true, false));
 }
    /**
     * send data to SOFORT and check SOFORT-response
     * @return array with paymentUrl, api-errors, trans-id, payment-secret
     */
    function _makeSofortApiCall()
    {
        global $order;
        $customer_id = $_SESSION['customer_id'];
        $currency = $_SESSION['currency'];
        $reasons = $this->_getReasons($this->paymentMethod, $customer_id, $order);
        $user_variable_0 = '';
        $user_variable_1 = $customer_id;
        /*
        		$session = session_name() . '=' . session_id();
        
        		if (ENABLE_SSL == true)
        			$server = HTTPS_SERVER;
        		else
        			$server = HTTP_SERVER;
        */
        $paymentSecret = md5(mt_rand() . microtime());
        /*		
        		$success_url = $server.DIR_WS_CATALOG.'callback/sofort/ressources/scripts/sofortReturn.php?sofortaction=success&sofortcode='.$this->code;
        		$cancel_url = $server.DIR_WS_CATALOG.'callback/sofort/ressources/scripts/sofortReturn.php?sofortaction=cancel&sofortcode='.$this->code;
        		$notification_url = $server . DIR_WS_CATALOG . 'callback/sofort/callback.php?paymentSecret='.$paymentSecret.'&action=multipay';
        */
        $success_url = xtc_href_link('callback/sofort/ressources/scripts/sofortReturn.php', 'sofortaction=success&sofortcode=' . $this->code, 'SSL');
        $cancel_url = xtc_href_link('callback/sofort/ressources/scripts/sofortReturn.php', 'sofortaction=cancel&sofortcode=' . $this->code, 'SSL');
        $notification_url = xtc_href_link('callback/sofort/callback.php', 'paymentSecret=' . $paymentSecret . '&action=multipay', 'SSL');
        $user_variable_2 = $_SESSION['cart']->cartID;
        $this->invoice->setCurrency($currency);
        //others than EUR will currently not be accepted by API!
        $this->invoice->setReason(HelperFunctions::convertEncoding($reasons[0], 3), HelperFunctions::convertEncoding($reasons[1], 3));
        $this->invoice->setSuccessUrl(HelperFunctions::convertEncoding($success_url, 4));
        $this->invoice->setAbortUrl(HelperFunctions::convertEncoding($cancel_url, 4));
        $this->invoice->setTimeoutUrl(HelperFunctions::convertEncoding($cancel_url, 4));
        $this->invoice->setNotificationUrl(HelperFunctions::convertEncoding($notification_url, 4));
        $this->invoice->addUserVariable(HelperFunctions::convertEncoding($user_variable_0, 3));
        $this->invoice->addUserVariable(HelperFunctions::convertEncoding($user_variable_1, 3));
        $this->invoice->addUserVariable(HelperFunctions::convertEncoding($user_variable_2, 3));
        $this->invoice->setEmailCustomer(HelperFunctions::convertEncoding($order->customer['email_address'], 3));
        $this->invoice->setPhoneNumberCustomer($order->customer['telephone']);
        $this->invoice->setSofortrechnung();
        $this->invoice->setCustomerId(HelperFunctions::convertEncoding($customer_id, 3));
        //important notice: following lines modifies also the $ot_shipping
        $orderTotals = array();
        if (MODULE_ORDER_TOTAL_INSTALLED) {
            require_once DIR_WS_CLASSES . 'order_total.php';
            $orderTotalModules = new order_total();
            //Following function-call manipulates variables (e.g. prices) within $order! Never call more than once!
            $orderTotals = $orderTotalModules->process();
        }
        $this->_addCustomerAddressesToInvoice();
        $this->_addProductsToInvoice($customer_id);
        $this->_addShippingToInvoice($customer_id);
        $this->_addPriceModificatorsToInvoice($customer_id, $orderTotals);
        //check shopTotal against the invoiceclassTotal
        $shopTotal = $this->_getShopTotal($orderTotals);
        $invoiceTotal = $this->invoice->getAmount();
        if (!$this->_checkShopTotalVsInvoiceTotal($shopTotal, $invoiceTotal)) {
            $this->invoice->log('ShopTotal is not near InvoiceTotal! Customer-ID ' . $customer_id . '. Are you using price-modification-tools 
								which are not supported by this "Rechnung bei sofort"-module? Was the tax-rate of all affected articles, 
								shipping options and other positions set correctly? Did you set the currency-exchange-rate correctly?');
            xtc_redirect($cancel_url);
        }
        //send all data to the API and place an order at SOFORT if no errors
        $this->invoice->checkout();
        $return = array();
        $return['apiCallErrors'] = $this->invoice->getErrors();
        $return['paymentUrl'] = $this->invoice->getPaymentUrl();
        $return['transactionId'] = $this->invoice->getTransactionId();
        $return['paymentSecret'] = $paymentSecret;
        $return['orderTotalModules'] = $orderTotalModules;
        $return['orderTotals'] = $orderTotals;
        return $return;
    }
Beispiel #10
0
 function pre_confirmation_check()
 {
     global $order_total_modules, $order_totals, $order;
     require_once DIR_WS_CLASSES . 'order_total.php';
     //if ($_SERVER['REMOTE_ADDR'] == '91.183.44.122') {
     if (count($order_total_modules) < 1 || count($order_totals) < 1) {
         $order_total_modules = new order_total();
         $order_totals = $order_total_modules->process();
     }
     //echo '<pre>';
     //print_r($order_totals);
     //die(print_r($order_total_modules));
     //}
     //$order_totals = $order_total_modules->process();
     order_process(false, $this->order_status);
     return false;
 }
Beispiel #11
0
}
// confirm where link came from
if (!strstr($_SERVER['HTTP_REFERER'], FILENAME_CHECKOUT_CONFIRMATION)) {
    //		zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT,'','SSL'));
}
// load selected payment module
require BITCOMMERCE_PKG_PATH . 'classes/CommercePaymentManager.php';
$paymentManager = new CommercePaymentManager($_SESSION['payment']);
// load the selected shipping module
require BITCOMMERCE_PKG_PATH . 'classes/CommerceShipping.php';
$shipping_modules = new CommerceShipping($_SESSION['shipping']);
require BITCOMMERCE_PKG_PATH . 'classes/CommerceOrder.php';
$order = new order();
require DIR_FS_CLASSES . 'order_total.php';
$order_total_modules = new order_total();
$order_totals = $order_total_modules->process($_REQUEST);
$gBitDb->mDb->StartTrans();
// load the before_process function from the payment modules
if ($order->hasPaymentDue() && !$paymentManager->processPayment($_REQUEST, $order)) {
    zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT, NULL, 'SSL', true, false));
}
$newOrderId = $order->create($order_totals, 2);
$order->create_add_products($newOrderId);
$paymentManager->after_order_create($newOrderId);
$order->send_order_email($newOrderId);
$gBitDb->mDb->completeTrans();
$paymentManager->after_process();
$gBitCustomer->mCart->reset(true);
// unregister session variables used during checkout
foreach (array('sendto', 'billto', 'shipping', 'payment', 'comments') as $key) {
    if (isset($_SESSION[$key])) {
Beispiel #12
0
 function before_process()
 {
     global $customer_id, $order, $sendto, $billto, $payment, $currencies, $cart, $cart_PayPal_IPN_ID;
     global ${$payment};
     include DIR_WS_CLASSES . 'order_total.php';
     $order_total_modules = new order_total();
     $order_totals = $order_total_modules->process();
     $order_id = substr($cart_PayPal_IPN_ID, strpos($cart_PayPal_IPN_ID, '-') + 1);
     $sql_data_array = array('orders_id' => $order_id, 'orders_status_id' => $order->info['order_status'], 'date_added' => 'now()', 'customer_notified' => SEND_EMAILS == 'true' ? '1' : '0', 'comments' => $order->info['comments']);
     tep_db_perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);
     // initialized for the email confirmation
     $products_ordered = '';
     $subtotal = 0;
     $total_tax = 0;
     for ($i = 0, $n = sizeof($order->products); $i < $n; $i++) {
         // Stock Update - Joao Correia
         if (STOCK_LIMITED == 'true') {
             if (DOWNLOAD_ENABLED == 'true') {
                 $stock_query_raw = "SELECT products_quantity, pad.products_attributes_filename\r\n                                FROM " . TABLE_PRODUCTS . " p\r\n                                LEFT JOIN " . TABLE_PRODUCTS_ATTRIBUTES . " pa\r\n                                ON p.products_id=pa.products_id\r\n                                LEFT JOIN " . TABLE_PRODUCTS_ATTRIBUTES_DOWNLOAD . " pad\r\n                                ON pa.products_attributes_id=pad.products_attributes_id\r\n                                WHERE p.products_id = '" . tep_get_prid($order->products[$i]['id']) . "'";
                 // Will work with only one option for downloadable products
                 // otherwise, we have to build the query dynamically with a loop
                 $products_attributes = $order->products[$i]['attributes'];
                 if (is_array($products_attributes)) {
                     $stock_query_raw .= " AND pa.options_id = '" . $products_attributes[0]['option_id'] . "' AND pa.options_values_id = '" . $products_attributes[0]['value_id'] . "'";
                 }
                 $stock_query = tep_db_query($stock_query_raw);
             } else {
                 $stock_query = tep_db_query("select products_quantity from " . TABLE_PRODUCTS . " where products_id = '" . tep_get_prid($order->products[$i]['id']) . "'");
             }
             if (tep_db_num_rows($stock_query) > 0) {
                 $stock_values = tep_db_fetch_array($stock_query);
                 // do not decrement quantities if products_attributes_filename exists
                 if (DOWNLOAD_ENABLED != 'true' || !$stock_values['products_attributes_filename']) {
                     $stock_left = $stock_values['products_quantity'] - $order->products[$i]['qty'];
                 } else {
                     $stock_left = $stock_values['products_quantity'];
                 }
                 tep_db_query("update " . TABLE_PRODUCTS . " set products_quantity = '" . $stock_left . "' where products_id = '" . tep_get_prid($order->products[$i]['id']) . "'");
                 if ($stock_left < 1 && STOCK_ALLOW_CHECKOUT == 'false') {
                     tep_db_query("update " . TABLE_PRODUCTS . " set products_status = '0' where products_id = '" . tep_get_prid($order->products[$i]['id']) . "'");
                 }
             }
         }
         // Update products_ordered (for bestsellers list)
         tep_db_query("update " . TABLE_PRODUCTS . " set products_ordered = products_ordered + " . sprintf('%d', $order->products[$i]['qty']) . " where products_id = '" . tep_get_prid($order->products[$i]['id']) . "'");
         $order_total_modules->update_credit_account($i);
         //ICW ADDED FOR CREDIT CLASS SYSTEM
         //------insert customer choosen option to order--------
         $attributes_exist = '0';
         $products_ordered_attributes = '';
         if (isset($order->products[$i]['attributes'])) {
             $attributes_exist = '1';
             for ($j = 0, $n2 = sizeof($order->products[$i]['attributes']); $j < $n2; $j++) {
                 if (DOWNLOAD_ENABLED == 'true') {
                     $attributes_query = "select popt.products_options_name, poval.products_options_values_name, pa.options_values_price, pa.price_prefix, pad.products_attributes_maxdays, pad.products_attributes_maxcount , pad.products_attributes_filename\r\n                                   from " . TABLE_PRODUCTS_OPTIONS . " popt, " . TABLE_PRODUCTS_OPTIONS_VALUES . " poval, " . TABLE_PRODUCTS_ATTRIBUTES . " pa\r\n                                   left join " . TABLE_PRODUCTS_ATTRIBUTES_DOWNLOAD . " pad\r\n                                   on pa.products_attributes_id=pad.products_attributes_id\r\n                                   where pa.products_id = '" . $order->products[$i]['id'] . "'\r\n                                   and pa.options_id = '" . $order->products[$i]['attributes'][$j]['option_id'] . "'\r\n                                   and pa.options_id = popt.products_options_id\r\n                                   and pa.options_values_id = '" . $order->products[$i]['attributes'][$j]['value_id'] . "'\r\n                                   and pa.options_values_id = poval.products_options_values_id\r\n                                   and popt.language_id = '" . $languages_id . "'\r\n                                   and poval.language_id = '" . $languages_id . "'";
                     $attributes = tep_db_query($attributes_query);
                 } else {
                     $attributes = tep_db_query("select popt.products_options_name, poval.products_options_values_name, pa.options_values_price, pa.price_prefix from " . TABLE_PRODUCTS_OPTIONS . " popt, " . TABLE_PRODUCTS_OPTIONS_VALUES . " poval, " . TABLE_PRODUCTS_ATTRIBUTES . " pa where pa.products_id = '" . $order->products[$i]['id'] . "' and pa.options_id = '" . $order->products[$i]['attributes'][$j]['option_id'] . "' and pa.options_id = popt.products_options_id and pa.options_values_id = '" . $order->products[$i]['attributes'][$j]['value_id'] . "' and pa.options_values_id = poval.products_options_values_id and popt.language_id = '" . $languages_id . "' and poval.language_id = '" . $languages_id . "'");
                 }
                 $attributes_values = tep_db_fetch_array($attributes);
                 $products_ordered_attributes .= "\n\t" . $attributes_values['products_options_name'] . ' ' . $attributes_values['products_options_values_name'];
             }
         }
         //------insert customer choosen option eof ----
         $total_weight += $order->products[$i]['qty'] * $order->products[$i]['weight'];
         $total_tax += tep_calculate_tax($total_products_price, $products_tax) * $order->products[$i]['qty'];
         $total_cost += $total_products_price;
         $products_ordered .= $order->products[$i]['qty'] . ' x ' . $order->products[$i]['name'] . ' (' . $order->products[$i]['model'] . ') = ' . $currencies->display_price($order->products[$i]['final_price'], $order->products[$i]['tax'], $order->products[$i]['qty']) . $products_ordered_attributes . "\n";
     }
     $order_total_modules->apply_credit();
     //ICW ADDED FOR CREDIT CLASS SYSTEM
     // lets start with the email confirmation
     $email_order = STORE_NAME . "\n" . EMAIL_SEPARATOR . "\n" . EMAIL_TEXT_ORDER_NUMBER . ' ' . $order_id . "\n" . EMAIL_TEXT_INVOICE_URL . ' ' . tep_href_link(FILENAME_ACCOUNT_HISTORY_INFO, 'order_id=' . $order_id, 'SSL', false) . "\n" . EMAIL_TEXT_DATE_ORDERED . ' ' . strftime(DATE_FORMAT_LONG) . "\n\n";
     if ($order->info['comments']) {
         $email_order .= tep_db_output($order->info['comments']) . "\n\n";
     }
     $email_order .= EMAIL_TEXT_PRODUCTS . "\n" . EMAIL_SEPARATOR . "\n" . $products_ordered . EMAIL_SEPARATOR . "\n";
     for ($i = 0, $n = sizeof($order_totals); $i < $n; $i++) {
         $email_order .= strip_tags($order_totals[$i]['title']) . ' ' . strip_tags($order_totals[$i]['text']) . "\n";
     }
     if ($order->content_type != 'virtual') {
         $email_order .= "\n" . EMAIL_TEXT_DELIVERY_ADDRESS . "\n" . EMAIL_SEPARATOR . "\n" . tep_address_label($customer_id, $sendto, 0, '', "\n") . "\n";
     }
     $email_order .= "\n" . EMAIL_TEXT_BILLING_ADDRESS . "\n" . EMAIL_SEPARATOR . "\n" . tep_address_label($customer_id, $billto, 0, '', "\n") . "\n\n";
     if (is_object(${$payment})) {
         $email_order .= EMAIL_TEXT_PAYMENT_METHOD . "\n" . EMAIL_SEPARATOR . "\n";
         $payment_class = ${$payment};
         $email_order .= $payment_class->title . "\n\n";
         if ($payment_class->email_footer) {
             $email_order .= $payment_class->email_footer . "\n\n";
         }
     }
     tep_mail($order->customer['firstname'] . ' ' . $order->customer['lastname'], $order->customer['email_address'], EMAIL_TEXT_SUBJECT, $email_order, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS);
     // send emails to other people
     if (SEND_EXTRA_ORDER_EMAILS_TO != '') {
         tep_mail('', SEND_EXTRA_ORDER_EMAILS_TO, EMAIL_TEXT_SUBJECT, $email_order, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS);
     }
     // load the after_process function from the payment modules
     $this->after_process();
     $cart->reset(true);
     // unregister session variables used during checkout
     tep_session_unregister('sendto');
     tep_session_unregister('billto');
     tep_session_unregister('shipping');
     tep_session_unregister('payment');
     tep_session_unregister('comments');
     if (tep_session_is_registered('credit_covers')) {
         tep_session_unregister('credit_covers');
     }
     $order_total_modules->clear_posts();
     //ICW ADDED FOR CREDIT CLASS SYSTEM
     tep_session_unregister('cart_PayPal_IPN_ID');
     tep_redirect(tep_href_link(FILENAME_CHECKOUT_SUCCESS, '', 'SSL'));
 }
 /**
  * Assert info.
  *
  * @param boolean withTotals Flag to include/apply totals or not.
  */
 private function assertInfo($withTotals)
 {
     global $order;
     $order = new \order();
     if ($withTotals) {
         if (!isset($shipping_modules)) {
             $shipping_modules = new \shipping($_SESSION['shipping']);
         }
         $order_total_modules = new \order_total();
         $order_total_modules->collect_posts();
         $order_total_modules->pre_confirmation_check();
         $order_total_modules->process();
     }
     foreach ($order->info as $key => $value) {
         if (in_array($key, array('rowClass', 'ip_address'))) {
             continue;
         }
         if (array_key_exists($key, $this->info)) {
             if ('tax_groups' == $key) {
                 // drop [0] as that is the default for none in zc
                 if (isset($value[0])) {
                     unset($value[0]);
                 }
                 $mytg = $this->info[$key];
                 if (count($value) != count($mytg)) {
                     echo 'info(' . ($withTotals ? 'with' : 'without') . ' ot): tax groups length diff! order: ';
                     var_dump($value);
                     echo 'ZM got: ';
                     var_dump($mytg);
                     echo '<br>';
                 }
                 continue;
             }
             if (in_array($key, array('total', 'subtotal', 'tax'))) {
                 $value = round($value, 3);
                 $this->info[$key] = round($this->info[$key], 3);
             }
             if ((string) $value != (string) $this->info[$key]) {
                 echo 'info(' . ($withTotals ? 'with' : 'without') . ' ot): value mismatch for ' . $key . ': value=';
                 var_dump($value);
                 echo ', ZM got: ';
                 var_dump($this->info[$key]);
                 echo "<BR>";
             }
         } else {
             echo 'info(' . ($withTotals ? 'with' : 'without') . ' ot): missing key: ' . $key . ', value is: ' . $value . "<BR>";
         }
     }
     echo '<br>';
 }
function amazon_process_order($pAmazonOrderId)
{
    global $gAmazonMWS, $gBitUser, $gCommerceSystem, $gBitCustomer, $currencies, $order;
    $ret = NULL;
    $request = new MarketplaceWebServiceOrders_Model_GetOrderRequest();
    $request->setSellerId(MERCHANT_ID);
    // @TODO: set request. Action can be passed as MarketplaceWebServiceOrders_Model_GetOrderRequest
    // object or array of parameters
    // Set the list of AmazonOrderIds
    $orderIds = new MarketplaceWebServiceOrders_Model_OrderIdList();
    $orderIds->setId(array($pAmazonOrderId));
    $request->setAmazonOrderId($orderIds);
    $holdUser = $gBitUser;
    $azUser = new BitPermUser($holdUser->lookupHomepage($gCommerceSystem->getConfig('MODULE_PAYMENT_AMAZONMWS_LOCAL_USERNAME', 'amazonmws')));
    $azUser->load();
    $gBitUser = $azUser;
    $gBitCustomer = new CommerceCustomer($gBitUser->mUserId);
    $gBitCustomer->syncBitUser($gBitUser->mInfo);
    $_SESSION['customer_id'] = $gBitUser->mUserId;
    try {
        $response = $gAmazonMWS->getOrder($request);
        if ($response->isSetGetOrderResult()) {
            $getOrderResult = $response->getGetOrderResult();
            if ($getOrderResult->isSetOrders()) {
                $oldCwd = getcwd();
                chdir(BITCOMMERCE_PKG_PATH);
                $azOrderList = $getOrderResult->getOrders();
                if ($azOrders = $azOrderList->getOrder()) {
                    require_once BITCOMMERCE_PKG_PATH . 'classes/CommerceOrder.php';
                    $order = new order();
                    $order->info = array('order_status' => DEFAULT_ORDERS_STATUS_ID, 'subtotal' => 0, 'tax' => 0, 'total' => 0, 'tax_groups' => array(), 'comments' => isset($_SESSION['comments']) ? $_SESSION['comments'] : '', 'ip_address' => $_SERVER['REMOTE_ADDR']);
                    $azOrder = current($azOrders);
                    // Setup delivery address
                    if ($orderTotal = $azOrder->getOrderTotal()) {
                        $order->info['total'] = $orderTotal->getAmount();
                        $order->info['currency'] = $orderTotal->getCurrencyCode();
                        $order->info['currency_value'] = $currencies->currencies[$order->info['currency']]['currency_value'];
                    }
                    if ($shippingAddress = $azOrder->getShippingAddress()) {
                        $country = zen_get_countries(zen_get_country_id($shippingAddress->getCountryCode()), TRUE);
                        $zoneName = zen_get_zone_name_by_code($country['countries_id'], $shippingAddress->getStateOrRegion());
                        $order->delivery = array('firstname' => substr($shippingAddress->getName(), 0, strpos($shippingAddress->getName(), ' ')), 'lastname' => substr($shippingAddress->getName(), strpos($shippingAddress->getName(), ' ') + 1), 'company' => NULL, 'street_address' => $shippingAddress->getAddressLine1(), 'suburb' => trim($shippingAddress->getAddressLine2() . ' ' . $shippingAddress->getAddressLine3()), 'city' => $shippingAddress->getCity(), 'postcode' => $shippingAddress->getPostalCode(), 'state' => $zoneName, 'country' => $country, 'format_id' => $country['address_format_id'], 'telephone' => $shippingAddress->getPhone(), 'email_address' => NULL);
                        $order->customer = $order->delivery;
                        $order->billing = $order->delivery;
                    }
                    // Setup shipping
                    $shipping = array('cost' => 0);
                    switch ($azOrder->getShipServiceLevel()) {
                        case 'Std US Dom':
                            $shipping['id'] = 'usps_MEDIA';
                            $shipping['title'] = 'United States Postal Service (USPS Media Mail (1 - 2 Weeks))';
                            $shipping['code'] = 'USPSREG';
                            break;
                    }
                    $azOrderItems = amazon_mws_get_order_items($azOrder->getAmazonOrderId());
                    $azOrderItem = $azOrderItems->getOrderItem();
                    foreach ($azOrderItem as $azi) {
                        $testSku = $azi->getSellerSKU();
                        list($productsId, $attrString) = explode(':', $testSku, 2);
                        $productsKey = $productsId . ':ASIN-' . $azi->getASIN();
                        $order->contents[$productsKey] = $gBitCustomer->mCart->getProductHash($productsKey);
                        $order->contents[$productsKey]['products_quantity'] = $azi->getQuantityOrdered();
                        $order->contents[$productsKey]['products_name'] = $azi->getTitle();
                        if ($itemPrice = $azi->getItemPrice()) {
                            //							{$itemTax->getCurrencyCode()}
                            $order->contents[$productsKey]['price'] = $itemPrice->getAmount();
                            $order->contents[$productsKey]['final_price'] = $itemPrice->getAmount();
                        }
                        if ($itemTax = $azi->getItemTax()) {
                            //							{$itemTax->getCurrencyCode()}
                            $order->contents[$productsKey]['tax'] = $itemTax->getAmount();
                        }
                        if ($shippingPrice = $azi->getShippingPrice()) {
                            //							{$itemTax->getCurrencyCode()}
                            $order->info['shipping_cost'] = $shippingPrice->getAmount();
                        }
                        if (empty($attrString)) {
                            $attrString = $gCommerceSystem->getConfig('MODULE_PAYMENT_AMAZONMWS_DEFAULT_ATTRIBUTES');
                        }
                        // stock up the attributes
                        if ($attrString && ($attrs = explode(',', $attrString))) {
                            foreach ($attrs as $optionValueId) {
                                $optionId = $order->mDb->getOne("SELECT cpa.`products_options_id` FROM " . TABLE_PRODUCTS_ATTRIBUTES . " cpa WHERE cpa.`products_options_values_id`=?", array($optionValueId));
                                $order->contents[$productsKey]['attributes'][$optionId . '_' . $optionValueId] = $optionValueId;
                            }
                        }
                        if (!empty($order->contents[$productsKey]['attributes'])) {
                            $attributes = $order->contents[$productsKey]['attributes'];
                            $order->contents[$productsKey]['attributes'] = array();
                            $subindex = 0;
                            foreach ($attributes as $option => $value) {
                                $optionValues = zen_get_option_value(zen_get_options_id($option), (int) $value);
                                // Determine if attribute is a text attribute and change products array if it is.
                                if ($value == PRODUCTS_OPTIONS_VALUES_TEXT_ID) {
                                    $attr_value = $order->contents[$productsKey]['attributes_values'][$option];
                                } else {
                                    $attr_value = $optionValues['products_options_values_name'];
                                }
                                $order->contents[$productsKey]['attributes'][$subindex] = array('option' => $optionValues['products_options_name'], 'value' => $attr_value, 'option_id' => $option, 'value_id' => $value, 'prefix' => $optionValues['price_prefix'], 'price' => $optionValues['options_values_price']);
                                $subindex++;
                            }
                        }
                        $shown_price = zen_add_tax($order->contents[$productsKey]['final_price'], $order->contents[$productsKey]['tax']) * $order->contents[$productsKey]['products_quantity'] + zen_add_tax($order->contents[$productsKey]['onetime_charges'], $order->contents[$productsKey]['tax']);
                        $order->subtotal += $shown_price;
                        $products_tax = $order->contents[$productsKey]['tax'];
                        $products_tax_description = $order->contents[$productsKey]['tax_description'];
                        if (DISPLAY_PRICE_WITH_TAX == 'true') {
                            $order->info['tax'] += $shown_price - $shown_price / ($products_tax < 10 ? "1.0" . str_replace('.', '', $products_tax) : "1." . str_replace('.', '', $products_tax));
                            if (isset($order->info['tax_groups']["{$products_tax_description}"])) {
                                $order->info['tax_groups']["{$products_tax_description}"] += $shown_price - $shown_price / ($products_tax < 10 ? "1.0" . str_replace('.', '', $products_tax) : "1." . str_replace('.', '', $products_tax));
                            } else {
                                $order->info['tax_groups']["{$products_tax_description}"] = $shown_price - $shown_price / ($products_tax < 10 ? "1.0" . str_replace('.', '', $products_tax) : "1." . str_replace('.', '', $products_tax));
                            }
                        } else {
                            $order->info['tax'] += $products_tax / 100 * $shown_price;
                            if (isset($order->info['tax_groups']["{$products_tax_description}"])) {
                                $order->info['tax_groups']["{$products_tax_description}"] += $products_tax / 100 * $shown_price;
                            } else {
                                $order->info['tax_groups']["{$products_tax_description}"] = $products_tax / 100 * $shown_price;
                            }
                        }
                        $order->info['tax'] = zen_round($order->info['tax'], 2);
                        if ($azi->isSetShippingPrice()) {
                            $shippingPrice = $azi->getShippingPrice();
                            $shipping['cost'] += $shippingPrice->getAmount();
                        }
                    }
                    foreach (array('cc_type', 'cc_owner', 'cc_number', 'cc_expires', 'coupon_code') as $key) {
                        $order->info[$key] = NULL;
                    }
                    $order->info['shipping_method'] = $shipping['title'];
                    $order->info['shipping_method_code'] = $shipping['code'];
                    $order->info['shipping_module_code'] = $shipping['id'];
                    $order->info['payment_module_code'] = 'amazonmws';
                    $order->info['payment_method'] = 'Amazon Order';
                    $_SESSION['sendto'] = NULL;
                    $_SESSION['shipping'] = $shipping;
                    unset($_SESSION['cot_gv']);
                    require_once DIR_FS_CLASSES . 'order_total.php';
                    global $order_total_modules;
                    $order_total_modules = new order_total();
                    $order_totals = $order_total_modules->pre_confirmation_check();
                    require_once DIR_WS_MODULES . 'payment/amazonmws.php';
                    $amazon = new amazonmws($azOrder->getAmazonOrderId());
                    $amazonOutput = $amazon->process();
                    $order_totals = $order_total_modules->process();
                    array_splice($order_totals, count($order_totals) - 1, 0, array($amazonOutput));
                    if ($ordersId = $order->create($order_totals, 2)) {
                        $order->create_add_products($ordersId);
                        $ret = $ordersId;
                        $order->updateStatus(array('status' => MODULE_PAYMENT_AMAZONMWS_INITIAL_ORDER_STATUS_ID));
                    }
                }
                chdir($oldCwd);
            }
        }
    } catch (MarketplaceWebServiceOrders_Exception $ex) {
        echo "Caught Exception: " . $ex->getMessage() . "\n";
        echo "Response Status Code: " . $ex->getStatusCode() . "\n";
        echo "Error Code: " . $ex->getErrorCode() . "\n";
        echo "Error Type: " . $ex->getErrorType() . "\n";
        echo "Request ID: " . $ex->getRequestId() . "\n";
        echo "XML: " . $ex->getXML() . "\n";
    }
    $gBitUser = $holdUser;
    $gBitCustomer = new CommerceCustomer($gBitUser->mUserId);
    $_SESSION['customer_id'] = $gBitUser->mUserId;
    return $ret;
}
Beispiel #15
0
 function _process()
 {
     global $osC_Database, $osC_Session, $osC_Customer, $osC_Currencies, $cart, $order, $payment_modules, $shipping_modules, $order_total_modules;
     // load selected payment module
     require DIR_WS_CLASSES . 'payment.php';
     $payment_modules = new payment($osC_Session->value('payment'));
     // load the selected shipping module
     require DIR_WS_CLASSES . 'shipping.php';
     $shipping_modules = new shipping($osC_Session->value('shipping'));
     $order = new order();
     // load the before_process function from the payment modules
     $payment_modules->before_process();
     require DIR_WS_CLASSES . 'order_total.php';
     $order_total_modules = new order_total();
     $order_totals = $order_total_modules->process();
     $Qorder = $osC_Database->query('insert into :table_orders (customers_id, customers_name, customers_company, customers_street_address, customers_suburb, customers_city, customers_postcode, customers_state, customers_country, customers_telephone, customers_email_address, customers_address_format_id, customers_ip_address, delivery_name, delivery_company, delivery_street_address, delivery_suburb, delivery_city, delivery_postcode, delivery_state, delivery_country, delivery_address_format_id, billing_name, billing_company, billing_street_address, billing_suburb, billing_city, billing_postcode, billing_state, billing_country, billing_address_format_id, payment_method, cc_type, cc_owner, cc_number, cc_expires, date_purchased, orders_status, currency, currency_value) values (:customers_id, :customers_name, :customers_company, :customers_street_address, :customers_suburb, :customers_city, :customers_postcode, :customers_state, :customers_country, :customers_telephone, :customers_email_address, :customers_address_format_id, :customers_ip_address, :delivery_name, :delivery_company, :delivery_street_address, :delivery_suburb, :delivery_city, :delivery_postcode, :delivery_state, :delivery_country, :delivery_address_format_id, :billing_name, :billing_company, :billing_street_address, :billing_suburb, :billing_city, :billing_postcode, :billing_state, :billing_country, :billing_address_format_id, :payment_method, :cc_type, :cc_owner, :cc_number, :cc_expires, :date_purchased, :orders_status, :currency, :currency_value)');
     $Qorder->bindTable(':table_orders', TABLE_ORDERS);
     $Qorder->bindInt(':customers_id', $osC_Customer->id);
     $Qorder->bindValue(':customers_name', $order->customer['firstname'] . ' ' . $order->customer['lastname']);
     $Qorder->bindValue(':customers_company', $order->customer['company']);
     $Qorder->bindValue(':customers_street_address', $order->customer['street_address']);
     $Qorder->bindValue(':customers_suburb', $order->customer['suburb']);
     $Qorder->bindValue(':customers_city', $order->customer['city']);
     $Qorder->bindValue(':customers_postcode', $order->customer['postcode']);
     $Qorder->bindValue(':customers_state', $order->customer['state']);
     $Qorder->bindValue(':customers_country', $order->customer['country']['title']);
     $Qorder->bindValue(':customers_telephone', $order->customer['telephone']);
     $Qorder->bindValue(':customers_email_address', $order->customer['email_address']);
     $Qorder->bindInt(':customers_address_format_id', $order->customer['format_id']);
     $Qorder->bindValue(':customers_ip_address', tep_get_ip_address());
     $Qorder->bindValue(':delivery_name', $order->delivery['firstname'] . ' ' . $order->delivery['lastname']);
     $Qorder->bindValue(':delivery_company', $order->delivery['company']);
     $Qorder->bindValue(':delivery_street_address', $order->delivery['street_address']);
     $Qorder->bindValue(':delivery_suburb', $order->delivery['suburb']);
     $Qorder->bindValue(':delivery_city', $order->delivery['city']);
     $Qorder->bindValue(':delivery_postcode', $order->delivery['postcode']);
     $Qorder->bindValue(':delivery_state', $order->delivery['state']);
     $Qorder->bindValue(':delivery_country', $order->delivery['country']['title']);
     $Qorder->bindInt(':delivery_address_format_id', $order->delivery['format_id']);
     $Qorder->bindValue(':billing_name', $order->billing['firstname'] . ' ' . $order->billing['lastname']);
     $Qorder->bindValue(':billing_company', $order->billing['company']);
     $Qorder->bindValue(':billing_street_address', $order->billing['street_address']);
     $Qorder->bindValue(':billing_suburb', $order->billing['suburb']);
     $Qorder->bindValue(':billing_city', $order->billing['city']);
     $Qorder->bindValue(':billing_postcode', $order->billing['postcode']);
     $Qorder->bindValue(':billing_state', $order->billing['state']);
     $Qorder->bindValue(':billing_country', $order->billing['country']['title']);
     $Qorder->bindInt(':billing_address_format_id', $order->billing['format_id']);
     $Qorder->bindValue(':payment_method', $order->info['payment_method']);
     $Qorder->bindValue(':cc_type', $order->info['cc_type']);
     $Qorder->bindValue(':cc_owner', $order->info['cc_owner']);
     $Qorder->bindValue(':cc_number', $order->info['cc_number']);
     $Qorder->bindValue(':cc_expires', $order->info['cc_expires']);
     $Qorder->bindRaw(':date_purchased', 'now()');
     $Qorder->bindValue(':orders_status', $order->info['order_status']);
     $Qorder->bindValue(':currency', $order->info['currency']);
     $Qorder->bindValue(':currency_value', $order->info['currency_value']);
     $Qorder->execute();
     $insert_id = $osC_Database->nextID();
     for ($i = 0, $n = sizeof($order_totals); $i < $n; $i++) {
         $Qtotals = $osC_Database->query('insert into :table_orders_total (orders_id, title, text, value, class, sort_order) values (:orders_id, :title, :text, :value, :class, :sort_order)');
         $Qtotals->bindTable(':table_orders_total', TABLE_ORDERS_TOTAL);
         $Qtotals->bindInt(':orders_id', $insert_id);
         $Qtotals->bindValue(':title', $order_totals[$i]['title']);
         $Qtotals->bindValue(':text', $order_totals[$i]['text']);
         $Qtotals->bindValue(':value', $order_totals[$i]['value']);
         $Qtotals->bindValue(':class', $order_totals[$i]['code']);
         $Qtotals->bindInt(':sort_order', $order_totals[$i]['sort_order']);
         $Qtotals->execute();
     }
     $Qstatus = $osC_Database->query('insert into :table_orders_status_history (orders_id, orders_status_id, date_added, customer_notified, comments) values (:orders_id, :orders_status_id, :date_added, :customer_notified, :comments)');
     $Qstatus->bindTable(':table_orders_status_history', TABLE_ORDERS_STATUS_HISTORY);
     $Qstatus->bindInt(':orders_id', $insert_id);
     $Qstatus->bindInt(':orders_status_id', $order->info['order_status']);
     $Qstatus->bindRaw(':date_added', 'now()');
     $Qstatus->bindInt(':customer_notified', SEND_EMAILS == 'true' ? '1' : '0');
     $Qstatus->bindValue(':comments', $order->info['comments']);
     $Qstatus->execute();
     // initialized for the email confirmation
     $products_ordered = '';
     $subtotal = 0;
     $total_tax = 0;
     $total_weight = 0;
     $total_cost = 0;
     for ($i = 0, $n = sizeof($order->products); $i < $n; $i++) {
         // Stock Update - Joao Correia
         if (STOCK_LIMITED == 'true') {
             if (DOWNLOAD_ENABLED == 'true') {
                 $Qstock = $osC_Database->query('select products_quantity, pad.products_attributes_filename from :table_products p left join :table_products_attributes pa on (p.products_id = pa.products_id) left join :table_products_attributes_download pad on (pa.products_attributes_id = pad.products_attributes_id) where p.products_id = :products_id');
                 $Qstock->bindTable(':table_products', TABLE_PRODUCTS);
                 $Qstock->bindTable(':table_products_attributes', TABLE_PRODUCTS_ATTRIBUTES);
                 $Qstock->bindTable(':table_products_attributes_download', TABLE_PRODUCTS_ATTRIBUTES_DOWNLOAD);
                 $Qstock->bindInt(':products_id', tep_get_prid($order->products[$i]['id']));
                 // Will work with only one option for downloadable products otherwise, we have to build the query dynamically with a loop
                 $products_attributes = $order->products[$i]['attributes'];
                 if (is_array($products_attributes)) {
                     $Qstock->appendQuery('and pa.options_id = :options_id and pa.options_values_id = :options_values_id');
                     $Qstock->bindInt(':options_id', $products_attributes[0]['option_id']);
                     $Qstock->bindInt(':options_values_id', $products_attributes[0]['value_id']);
                 }
             } else {
                 $Qstock = $osC_Database->query('select products_quantity from :table_products where products_id = :products_id');
                 $Qstock->bindTable(':table_products', TABLE_PRODUCTS);
                 $Qstock->bindInt(':products_id', tep_get_prid($order->products[$i]['id']));
             }
             $Qstock->execute();
             if ($Qstock->numberOfRows() > 0) {
                 $stock_left = $Qstock->valueInt('products_quantity');
                 // do not decrement quantities if products_attributes_filename exists
                 if (DOWNLOAD_ENABLED != 'true' || DOWNLOAD_ENABLED == 'true' && strlen($Qstock->value('products_attributes_filename')) < 1) {
                     $stock_left = $stock_left - $order->products[$i]['qty'];
                     $Qupdate = $osC_Database->query('update :table_products set products_quantity = :products_quantity where products_id = :products_id');
                     $Qupdate->bindTable(':table_products', TABLE_PRODUCTS);
                     $Qupdate->bindInt(':products_quantity', $stock_left);
                     $Qupdate->bindInt(':products_id', tep_get_prid($order->products[$i]['id']));
                     $Qupdate->execute();
                 }
                 if (STOCK_ALLOW_CHECKOUT == 'false' && $stock_left < 1) {
                     $Qupdate = $osC_Database->query('update :table_products set products_status = :products_status where products_id = :products_id');
                     $Qupdate->bindTable(':table_products', TABLE_PRODUCTS);
                     $Qupdate->bindInt(':products_status', 0);
                     $Qupdate->bindInt(':products_id', tep_get_prid($order->products[$i]['id']));
                     $Qupdate->execute();
                 }
             }
         }
         // Update products_ordered (for bestsellers list)
         $Qupdate = $osC_Database->query('update :table_products set products_ordered = products_ordered + :products_ordered where products_id = :products_id');
         $Qupdate->bindTable(':table_products', TABLE_PRODUCTS);
         $Qupdate->bindInt(':products_ordered', $order->products[$i]['qty']);
         $Qupdate->bindInt(':products_id', tep_get_prid($order->products[$i]['id']));
         $Qupdate->execute();
         $Qproducts = $osC_Database->query('insert into :table_orders_products (orders_id, products_id, products_model, products_name, products_price, final_price, products_tax, products_quantity) values (:orders_id, :products_id, :products_model, :products_name, :products_price, :final_price, :products_tax, :products_quantity)');
         $Qproducts->bindTable(':table_orders_products', TABLE_ORDERS_PRODUCTS);
         $Qproducts->bindInt(':orders_id', $insert_id);
         $Qproducts->bindInt(':products_id', tep_get_prid($order->products[$i]['id']));
         $Qproducts->bindValue(':products_model', $order->products[$i]['model']);
         $Qproducts->bindValue(':products_name', $order->products[$i]['name']);
         $Qproducts->bindValue(':products_price', $order->products[$i]['price']);
         $Qproducts->bindValue(':final_price', $order->products[$i]['final_price']);
         $Qproducts->bindValue(':products_tax', $order->products[$i]['tax']);
         $Qproducts->bindInt(':products_quantity', $order->products[$i]['qty']);
         $Qproducts->execute();
         $order_products_id = $osC_Database->nextID();
         //------insert customer choosen option to order--------
         $attributes_exist = '0';
         $products_ordered_attributes = '';
         if (isset($order->products[$i]['attributes'])) {
             $attributes_exist = '1';
             for ($j = 0, $n2 = sizeof($order->products[$i]['attributes']); $j < $n2; $j++) {
                 if (DOWNLOAD_ENABLED == 'true') {
                     $Qattributes = $osC_Database->query('select popt.products_options_name, poval.products_options_values_name, pa.options_values_price, pa.price_prefix, pad.products_attributes_maxdays, pad.products_attributes_maxcount, pad.products_attributes_filename from :table_products_options popt, :table_products_options_values poval, :table_products_attributes pa left join :table_products_attributes_download pad on (pa.products_attributes_id = pad.products_attributes_id) where pa.products_id = :products_id and pa.options_id = :options_id and pa.options_id = popt.products_options_id and pa.options_values_id = :options_values_id and pa.options_values_id = poval.products_options_values_id and popt.language_id = :popt_language_id and poval.language_id = :poval_language_id');
                     $Qattributes->bindTable(':table_products_options', TABLE_PRODUCTS_OPTIONS);
                     $Qattributes->bindTable(':table_products_options_values', TABLE_PRODUCTS_OPTIONS_VALUES);
                     $Qattributes->bindTable(':table_products_attributes', TABLE_PRODUCTS_ATTRIBUTES);
                     $Qattributes->bindTable(':table_products_attributes_download', TABLE_PRODUCTS_ATTRIBUTES_DOWNLOAD);
                     $Qattributes->bindInt(':products_id', $order->products[$i]['id']);
                     $Qattributes->bindInt(':options_id', $order->products[$i]['attributes'][$j]['option_id']);
                     $Qattributes->bindInt(':options_values_id', $order->products[$i]['attributes'][$j]['value_id']);
                     $Qattributes->bindInt(':popt_language_id', $osC_Session->value('languages_id'));
                     $Qattributes->bindInt(':poval_language_id', $osC_Session->value('languages_id'));
                 } else {
                     $Qattributes = $osC_Database->query('select popt.products_options_name, poval.products_options_values_name, pa.options_values_price, pa.price_prefix from :table_products_options popt, :table_products_options_values poval, :table_products_attributes pa where pa.products_id = :products_id and pa.options_id = :options_id and pa.options_id = popt.products_options_id and pa.options_values_id = :options_values_id and pa.options_values_id = poval.products_options_values_id and popt.language_id = :popt_language_id and poval.language_id = :poval_language_id');
                     $Qattributes->bindTable(':table_products_options', TABLE_PRODUCTS_OPTIONS);
                     $Qattributes->bindTable(':table_products_options_values', TABLE_PRODUCTS_OPTIONS_VALUES);
                     $Qattributes->bindTable(':table_products_attributes', TABLE_PRODUCTS_ATTRIBUTES);
                     $Qattributes->bindInt(':products_id', $order->products[$i]['id']);
                     $Qattributes->bindInt(':options_id', $order->products[$i]['attributes'][$j]['option_id']);
                     $Qattributes->bindInt(':options_values_id', $order->products[$i]['attributes'][$j]['value_id']);
                     $Qattributes->bindInt(':popt_language_id', $osC_Session->value('languages_id'));
                     $Qattributes->bindInt(':poval_language_id', $osC_Session->value('languages_id'));
                 }
                 $Qattributes->execute();
                 $Qopa = $osC_Database->query('insert into :table_orders_products_attributes (orders_id, orders_products_id, products_options, products_options_values, options_values_price, price_prefix) values (:orders_id, :orders_products_id, :products_options, :products_options_values, :options_values_price, :price_prefix)');
                 $Qopa->bindTable(':table_orders_products_attributes', TABLE_ORDERS_PRODUCTS_ATTRIBUTES);
                 $Qopa->bindInt(':orders_id', $insert_id);
                 $Qopa->bindInt(':orders_products_id', $order_products_id);
                 $Qopa->bindValue(':products_options', $attributes_values['products_options_name']);
                 $Qopa->bindValue(':products_options_values', $attributes_values['products_options_values_name']);
                 $Qopa->bindValue(':options_values_price', $attributes_values['options_values_price']);
                 $Qopa->bindValue(':price_prefix', $attributes_values['price_prefix']);
                 $Qopa->execute();
                 if (DOWNLOAD_ENABLED == 'true' && strlen($Qattributes->value('products_attributes_filename')) > 0) {
                     $Qopd = $osC_Database->query('insert into :table_orders_products_download (orders_id, orders_products_id, orders_products_filename, download_maxdays, download_count) values (:orders_id, :orders_products_id, :orders_products_filename, :download_maxdays, :download_count)');
                     $Qopd->bindTable(':table_orders_products_download', TABLE_ORDERS_PRODUCTS_DOWNLOAD);
                     $Qopd->bindInt(':orders_id', $insert_id);
                     $Qopd->bindInt(':orders_products_id', $order_products_id);
                     $Qopd->bindValue(':orders_products_filename', $Qattributes->value('products_attributes_filename'));
                     $Qopd->bindValue(':download_maxdays', $Qattributes->value('products_attributes_maxdays'));
                     $Qopd->bindValue(':download_count', $Qattributes->value('products_attributes_maxcount'));
                     $Qopd->execute();
                 }
                 $products_ordered_attributes .= "\n\t" . $Qattributes->value('products_options_name') . ' ' . $Qattributes->value('products_options_values_name');
             }
         }
         //------insert customer choosen option eof ----
         $total_weight += $order->products[$i]['qty'] * $order->products[$i]['weight'];
         $total_tax += tep_calculate_tax($order->products[$i]['final_price'], $order->products[$i]['tax']) * $order->products[$i]['qty'];
         $total_cost += $order->products[$i]['final_price'];
         $products_ordered .= $order->products[$i]['qty'] . ' x ' . $order->products[$i]['name'] . ' (' . $order->products[$i]['model'] . ') = ' . $osC_Currencies->displayPrice($order->products[$i]['final_price'], $order->products[$i]['tax_class_id'], $order->products[$i]['qty']) . $products_ordered_attributes . "\n";
     }
     // lets start with the email confirmation
     $email_order = STORE_NAME . "\n" . EMAIL_SEPARATOR . "\n" . EMAIL_TEXT_ORDER_NUMBER . ' ' . $insert_id . "\n" . EMAIL_TEXT_INVOICE_URL . ' ' . tep_href_link(FILENAME_ACCOUNT, 'orders=' . $insert_id, 'SSL', false) . "\n" . EMAIL_TEXT_DATE_ORDERED . ' ' . strftime(DATE_FORMAT_LONG) . "\n\n";
     if ($order->info['comments']) {
         $email_order .= tep_output_string_protected($order->info['comments']) . "\n\n";
     }
     $email_order .= EMAIL_TEXT_PRODUCTS . "\n" . EMAIL_SEPARATOR . "\n" . $products_ordered . EMAIL_SEPARATOR . "\n";
     for ($i = 0, $n = sizeof($order_totals); $i < $n; $i++) {
         $email_order .= strip_tags($order_totals[$i]['title']) . ' ' . strip_tags($order_totals[$i]['text']) . "\n";
     }
     if ($order->content_type != 'virtual') {
         $email_order .= "\n" . EMAIL_TEXT_DELIVERY_ADDRESS . "\n" . EMAIL_SEPARATOR . "\n" . tep_address_label($osC_Customer->id, $osC_Session->value('sendto'), 0, '', "\n") . "\n";
     }
     $email_order .= "\n" . EMAIL_TEXT_BILLING_ADDRESS . "\n" . EMAIL_SEPARATOR . "\n" . tep_address_label($osC_Customer->id, $osC_Session->value('billto'), 0, '', "\n") . "\n\n";
     $payment =& $osC_Session->value('payment');
     if (is_object(${$payment})) {
         $email_order .= EMAIL_TEXT_PAYMENT_METHOD . "\n" . EMAIL_SEPARATOR . "\n";
         $payment_class = ${$payment};
         $email_order .= $payment_class->title . "\n\n";
         if (isset($payment_class->email_footer)) {
             $email_order .= $payment_class->email_footer . "\n\n";
         }
     }
     tep_mail($order->customer['firstname'] . ' ' . $order->customer['lastname'], $order->customer['email_address'], EMAIL_TEXT_SUBJECT, $email_order, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS);
     // send emails to other people
     if (SEND_EXTRA_ORDER_EMAILS_TO != '') {
         tep_mail('', SEND_EXTRA_ORDER_EMAILS_TO, EMAIL_TEXT_SUBJECT, $email_order, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS);
     }
     // load the after_process function from the payment modules
     $payment_modules->after_process();
     $cart->reset(true);
     // unregister session variables used during checkout
     $osC_Session->remove('sendto');
     $osC_Session->remove('billto');
     $osC_Session->remove('shipping');
     $osC_Session->remove('payment');
     $osC_Session->remove('comments');
     tep_redirect(tep_href_link(FILENAME_CHECKOUT, 'success', 'SSL'));
 }
    $oos_pagetitle .= '&raquo;' . OOS_META_TITLE;

    // assign Smarty variables;
    $oSmarty->assign(
        array(
            'pagetitle'         => htmlspecialchars($oos_pagetitle),
            'meta_description'  => htmlspecialchars($oos_meta_description),
            'meta_keywords'     => htmlspecialchars($oos_meta_keywords),
            'oos_breadcrumb'    => $oBreadcrumb->trail(BREADCRUMB_SEPARATOR),
            'oos_heading_title' => $aLang['heading_title'],
            'oos_heading_image' => 'confirmation.gif'
        )
    );

    if (MODULE_ORDER_TOTAL_INSTALLED) {
      $oOrderTotalModules->process();
      $order_total_output = $oOrderTotalModules->output();
      $oSmarty->assign('order_total_output', $order_total_output);
    }

    if (is_array($oPaymentModules->modules)) {
        if ($confirmation = $oPaymentModules->confirmation()) {
            $oSmarty->assign('confirmation', $confirmation);
        }
    }

    if (is_array($oPaymentModules->modules)) {
      $oPaymentModules_process_button =  $oPaymentModules->process_button();
    }

    $oSmarty->assign('payment_modules_process_button', $oPaymentModules_process_button);
Beispiel #17
0
 function pre_confirmation_check()
 {
     global $HTTP_GET_VARS, $order, $ppe_token;
     if (!tep_session_is_registered('ppe_token')) {
         tep_redirect(tep_href_link('ext/modules/payment/paypal/express.php', '', 'SSL'));
     }
     if (!isset($HTTP_GET_VARS['do'])) {
         $response_array = $this->getExpressCheckoutDetails($ppe_token);
         if ($response_array['ACK'] == 'Success' || $response_array['ACK'] == 'SuccessWithWarning') {
             // load the selected shipping module
             include DIR_WS_CLASSES . 'shipping.php';
             $shipping_modules = new shipping($shipping);
             include DIR_WS_CLASSES . 'order_total.php';
             $order_total_modules = new order_total();
             $order_total_modules->process();
             if ($response_array['AMT'] == $this->format_raw($order->info['total'])) {
                 tep_redirect(tep_href_link(FILENAME_CHECKOUT_PROCESS, '', 'SSL'));
             } else {
                 tep_redirect(tep_href_link(FILENAME_CHECKOUT_CONFIRMATION, 'do=confirm', 'SSL'));
             }
         }
     }
 }
// method if more than one module is now enabled
if (!isset($_SESSION['shipping']) || isset($_SESSION['shipping']) && $_SESSION['shipping'] == false && xtc_count_shipping_modules() > 1) {
    $_SESSION['shipping'] = $shipping_modules->cheapest();
}
if ($kein_versand == 1) {
    $_SESSION['shipping'] = false;
}
$order = new order();
// load all enabled payment modules
require DIR_WS_CLASSES . 'payment.php';
$payment_modules = new payment($_SESSION['payment']);
$payment_modules->update_status();
require DIR_WS_CLASSES . 'order_total.php';
// GV Code ICW ADDED FOR CREDIT CLASS SYSTEM
$order_total_modules = new order_total();
$order_total_modules->process();
// GV Code Start
$order_total_modules->collect_posts();
$order_total_modules->pre_confirmation_check();
// GV Code End
if (is_array($payment_modules->modules)) {
    $payment_modules->pre_confirmation_check();
}
$breadcrumb->add(NAVBAR_TITLE_PAYPAL_CHECKOUT, xtc_href_link(FILENAME_PAYPAL_CHECKOUT, '', 'SSL'));
require DIR_WS_INCLUDES . 'header.php';
if (SHOW_IP_LOG == 'true') {
    $smarty->assign('IP_LOG', 'true');
    if ($_SERVER['HTTP_X_FORWARDED_FOR']) {
        $customers_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        $customers_ip = $_SERVER['REMOTE_ADDR'];
$oOrder = new order;

if ( (isset($_SESSION['shipping'])) && ($_SESSION['shipping']['id'] == 'free_free')) {
    if ( ($oOrder->info['total'] - $oOrder->info['shipping_cost']) < MODULE_ORDER_TOTAL_SHIPPING_FREE_SHIPPING_OVER ) {
        MyOOS_CoreApi::redirect(oos_href_link($aPages['checkout_shipping'], '', 'SSL'));
    }
}


// load the before_process function from the payment modules
$oPaymentModules->before_process();

require 'includes/classes/class_order_total.php';
$oOrderTotalModules = new order_total;

$order_totals = $oOrderTotalModules->process();

$sql_data_array = array('customers_id' => $_SESSION['customer_id'],
                        'customers_name' => $oOrder->customer['firstname'] . ' ' . $oOrder->customer['lastname'],
                        'customers_number' => $oOrder->customer['number'],
                        'customers_company' => $oOrder->customer['company'],
                        'customers_street_address' => $oOrder->customer['street_address'],
                        'customers_suburb' => $oOrder->customer['suburb'],
                        'customers_city' => $oOrder->customer['city'],
                        'customers_postcode' => $oOrder->customer['postcode'],
                        'customers_state' => $oOrder->customer['state'],
                        'customers_country' => $oOrder->customer['country']['title'],
                        'customers_telephone' => $oOrder->customer['telephone'],
                        'customers_email_address' => $oOrder->customer['email_address'],
                        'customers_address_format_id' => $oOrder->customer['format_id'],
                        'delivery_name' => $oOrder->delivery['firstname'] . ' ' . $oOrder->delivery['lastname'],