Esempio n. 1
0
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;
}
Esempio n. 2
0
 function create_add_products($pOrdersId, $zf_mode = false)
 {
     global $gBitDb, $gBitUser, $currencies, $order_total_modules, $order_totals;
     $this->StartTrans();
     // initialized for the email confirmation
     $this->products_ordered_html = '';
     // lowstock email report
     $this->email_low_stock = '';
     foreach (array_keys($this->contents) as $productsKey) {
         // Stock Update - Joao Correia
         if (STOCK_LIMITED == 'true') {
             if (DOWNLOAD_ENABLED == 'true') {
                 $stock_query_raw = "SELECT products_quantity, pad.products_attributes_filename\n\t\t\t\t\t\t\t\t\t\tFROM " . TABLE_PRODUCTS . " p\n\t\t\t\t\t\t\t\t\t\t\tLEFT JOIN " . TABLE_PRODUCTS_OPTIONS_MAP . " pom ON(p.`products_id`=pom.`products_id`)\n\t\t\t\t\t\t\t\t\t\t\tLEFT JOIN " . TABLE_PRODUCTS_ATTRIBUTES . " pa ON (pa.`products_options_values_id`=pom.`products_options_values_id`)\n\t\t\t\t\t\t\t\t\t\t\tLEFT JOIN " . TABLE_PRODUCTS_ATTRIBUTES_DOWNLOAD . " pad ON(pa.`products_attributes_id`=pad.`products_attributes_id`)\n\t\t\t\t\t\t\t\t\t\tWHERE p.`products_id` = ?";
                 $bindVars = array(zen_get_prid($this->contents[$productsKey]['id']));
                 // Will work with only one option for downloadable products
                 // otherwise, we have to build the query dynamically with a loop
                 $products_attributes = $this->contents[$productsKey]['attributes'];
                 if (is_array($products_attributes)) {
                     $stock_query_raw .= " AND pa.`products_options_id` = ? AND pa.`products_options_values_id` = ?";
                     $bindVars[] = zen_get_options_id($products_attributes[0]['option_id']);
                     $bindVars[] = $products_attributes[0]['value_id'];
                 }
                 $stockValues = $gBitDb->query($stock_query_raw, $bindVars);
             } else {
                 $stockValues = $gBitDb->getRow("select `products_quantity` from " . TABLE_PRODUCTS . " where `products_id` = ?", array(zen_get_prid($this->contents[$productsKey]['id'])));
             }
             if ($stock_values && $stock_values->RecordCount() > 0) {
                 // do not decrement quantities if products_attributes_filename exists
                 if (DOWNLOAD_ENABLED != 'true' || !empty($stockValues['products_attributes_filename'])) {
                     $stock_left = $stockValues['products_quantity'] - $this->contents[$productsKey]['products_quantity'];
                     $this->contents[$productsKey]['stock_reduce'] = $this->contents[$productsKey]['products_quantity'];
                 } else {
                     $stock_left = $stockValues['products_quantity'];
                 }
                 //				$this->contents[$productsKey]['stock_value'] = $stockValues['products_quantity'];
                 $gBitDb->Execute("update " . TABLE_PRODUCTS . " set `products_quantity` = '" . $stock_left . "' where `products_id` = '" . zen_get_prid($this->contents[$productsKey]['id']) . "'");
                 //				if ( ($stock_left < 1) && (STOCK_ALLOW_CHECKOUT == 'false') ) {
                 if ($stock_left < 1) {
                     // only set status to off when not displaying sold out
                     if (SHOW_PRODUCTS_SOLD_OUT == '0') {
                         $gBitDb->Execute("update " . TABLE_PRODUCTS . " set `products_status` = '0' where `products_id` = '" . zen_get_prid($this->contents[$productsKey]['id']) . "'");
                     }
                 }
                 // for low stock email
                 if ($stock_left <= STOCK_REORDER_LEVEL) {
                     // WebMakers.com Added: add to low stock email
                     $this->email_low_stock .= 'ID# ' . zen_get_prid($this->contents[$productsKey]['id']) . "\t\t" . $this->contents[$productsKey]['model'] . "\t\t" . $this->contents[$productsKey]['name'] . "\t\t" . ' Qty Left: ' . $stock_left . "\n";
                 }
             }
         }
         // Update products_ordered (for bestsellers list)
         $gBitDb->Execute("update " . TABLE_PRODUCTS . " set `products_ordered` = `products_ordered` + " . sprintf('%f', $this->contents[$productsKey]['products_quantity']) . " where `products_id` = '" . zen_get_prid($this->contents[$productsKey]['id']) . "'");
         $sql_data_array = array('orders_id' => $pOrdersId, 'products_id' => zen_get_prid($this->contents[$productsKey]['id']), 'products_model' => $this->contents[$productsKey]['model'], 'products_name' => $this->contents[$productsKey]['name'], 'products_price' => $this->contents[$productsKey]['price'], 'products_cogs' => $this->contents[$productsKey]['products_cogs'], 'products_wholesale' => $this->contents[$productsKey]['products_wholesale'], 'products_commission' => $this->contents[$productsKey]['commission'], 'final_price' => $this->contents[$productsKey]['final_price'], 'onetime_charges' => $this->contents[$productsKey]['onetime_charges'], 'products_tax' => $this->contents[$productsKey]['tax'], 'products_quantity' => $this->contents[$productsKey]['products_quantity'], 'products_priced_by_attribute' => $this->contents[$productsKey]['products_priced_by_attribute'], 'product_is_free' => $this->contents[$productsKey]['product_is_free'], 'products_discount_type' => $this->contents[$productsKey]['products_discount_type'], 'products_discount_type_from' => $this->contents[$productsKey]['products_discount_type_from']);
         $gBitDb->associateInsert(TABLE_ORDERS_PRODUCTS, $sql_data_array);
         $this->contents[$productsKey]['orders_products_id'] = zen_db_insert_id(TABLE_ORDERS_PRODUCTS, 'orders_products_id');
         $order_total_modules->update_credit_account($productsKey);
         //ICW ADDED FOR CREDIT CLASS SYSTEM
         if (!empty($this->contents[$productsKey]['purchase_group_id'])) {
             $gBitUser->addUserToGroup($gBitUser->mUserId, $this->contents[$productsKey]['purchase_group_id']);
         }
         //------insert customer choosen option to order--------
         $attributes_exist = '0';
         $this->products_ordered_attributes = '';
         if (!empty($this->contents[$productsKey]['attributes'])) {
             $attributes_exist = '1';
             foreach (array_keys($this->contents[$productsKey]['attributes']) as $j) {
                 $optionValues = zen_get_option_value((int) $this->contents[$productsKey]['attributes'][$j]['option_id'], (int) $this->contents[$productsKey]['attributes'][$j]['value_id']);
                 if (!empty($optionValues['purchase_group_id'])) {
                     $gBitUser->addUserToGroup($gBitUser->mUserId, $optionValues['purchase_group_id']);
                 }
                 if (!empty($optionValues['products_options_id'])) {
                     //clr 030714 update insert query.	changing to use values form $order->contents for products_options_values.
                     $sql_data_array = array('orders_id' => $pOrdersId, 'orders_products_id' => $this->contents[$productsKey]['orders_products_id'], 'products_options' => $optionValues['products_options_name'], 'products_options_values' => $this->contents[$productsKey]['attributes'][$j]['value'], 'options_values_price' => $optionValues['options_values_price'], 'options_values_cogs' => $optionValues['options_values_cogs'], 'options_values_wholesale' => $optionValues['options_values_wholesale'], 'price_prefix' => $optionValues['price_prefix'], 'product_attribute_is_free' => $optionValues['product_attribute_is_free'], 'products_attributes_wt' => $optionValues['products_attributes_wt'], 'products_attributes_wt_pfix' => $optionValues['products_attributes_wt_pfix'], 'attributes_discounted' => (int) $optionValues['attributes_discounted'], 'attributes_price_base_inc' => (int) $optionValues['attributes_price_base_inc'], 'attributes_price_onetime' => $optionValues['attributes_price_onetime'], 'attributes_price_factor' => $optionValues['attributes_price_factor'], 'attributes_pf_offset' => $optionValues['attributes_pf_offset'], 'attributes_pf_onetime' => $optionValues['attributes_pf_onetime'], 'attributes_pf_onetime_offset' => $optionValues['attributes_pf_onetime_offset'], 'attributes_qty_prices' => $optionValues['attributes_qty_prices'], 'attributes_qty_prices_onetime' => $optionValues['attributes_qty_prices_onetime'], 'attributes_price_words' => $optionValues['attributes_price_words'], 'attributes_price_words_free' => $optionValues['attributes_price_words_free'], 'attributes_price_letters' => $optionValues['attributes_price_letters'], 'attributes_price_letters_free' => $optionValues['attributes_price_letters_free'], 'products_options_id' => $optionValues['products_options_id'], 'products_options_values_id' => $optionValues['products_options_values_id']);
                     $gBitDb->associateInsert(TABLE_ORDERS_PRODUCTS_ATTRIBUTES, $sql_data_array);
                 }
                 if (DOWNLOAD_ENABLED == 'true' && isset($optionValues['products_attributes_filename']) && zen_not_null($optionValues['products_attributes_filename'])) {
                     $sql_data_array = array('orders_id' => $pOrdersId, 'orders_products_id' => $this->contents[$productsKey]['orders_products_id'], 'orders_products_filename' => $optionValues['products_attributes_filename'], 'download_maxdays' => $optionValues['products_attributes_maxdays'], 'download_count' => $optionValues['products_attributes_maxcount']);
                     $gBitDb->associateInsert(TABLE_ORDERS_PRODUCTS_DOWNLOAD, $sql_data_array);
                 }
                 $this->products_ordered_attributes .= "\n\t" . $optionValues['products_options_name'] . ' ' . zen_decode_specialchars($this->contents[$productsKey]['attributes'][$j]['value']);
             }
         }
         //------insert customer choosen option eof ----
         $this->total_weight += $this->contents[$productsKey]['products_quantity'] * $this->contents[$productsKey]['weight'];
         //			$this->total_tax += zen_calculate_tax($total_products_price, $products_tax) * $this->contents[$productsKey]['products_quantity'];
         //			$this->total_cost += $total_products_price;
         $this->products_ordered_html .= '<tr>' . '<td class="product-details alignright" valign="top" width="30">' . $this->contents[$productsKey]['products_quantity'] . '&nbsp;x</td>' . '<td class="product-details" valign="top">' . $this->contents[$productsKey]['name'] . ($this->contents[$productsKey]['model'] != '' ? ' (' . $this->contents[$productsKey]['model'] . ') ' : '') . '<span style="white-space:nowrap;"><small><em> ' . $this->products_ordered_attributes . '</em></small></span></td>' . '<td class="product-details-num alignright" valign="top">' . $currencies->display_price($this->contents[$productsKey]['final_price'], $this->contents[$productsKey]['tax'], $this->contents[$productsKey]['products_quantity']) . ($this->contents[$productsKey]['onetime_charges'] != 0 ? '</td></tr><tr><td class="product-details">' . TEXT_ONETIME_CHARGES_EMAIL . '</td>' . '<td>' . $currencies->display_price($this->contents[$productsKey]['onetime_charges'], $this->contents[$productsKey]['tax'], 1) : '') . '</td></tr>';
     }
     $order_total_modules->apply_credit();
     //ICW ADDED FOR CREDIT CLASS SYSTEM
     $this->CompleteTrans();
 }