Exemplo n.º 1
0
 /**
  * Actually fetch the shipping quotes based on the set information.
  *
  * @return array An array of shipping quotes.
  */
 private function FetchQuotes()
 {
     $upsUrl = 'https://wwwcie.ups.com/ups.app/xml/Rate';
     $shipmentXML = $this->GenerateRateXML();
     $result = PostToRemoteFileAndGetResponse($upsUrl, $shipmentXML);
     if ($result === false) {
         $this->SetError(GetLang('UPSOpenError'));
         return false;
     }
     $x = @simplexml_load_string($result);
     if (!is_object($x)) {
         $this->SetError(GetLang('UPSOpenError'));
         return false;
     }
     // Was an error returned from UPS? If so, set that and return
     if (isset($x->Response->ResponseStatusCode) && $x->Response->ResponseStatusCode == 0) {
         $this->SetError((string) $x->Response->Error->ErrorDescription);
         return false;
     }
     $quotes = array();
     if (!isset($x->RatedShipment[0])) {
         $quoteXML = array($x->RatedShipment);
     } else {
         $quoteXML = $x->RatedShipment;
     }
     $deliveryTypes = $this->GetValue('deliverytypes');
     if (!is_array($deliveryTypes)) {
         $deliveryTypes = array($deliveryTypes);
     }
     foreach ($quoteXML as $quote) {
         // Fetch the friendly name of the shipping service for this quote
         $serviceName = GetLang('Unknown');
         $service = (string) $quote->Service->Code;
         // We're not offering this delivery type in the store so skip it
         if (!in_array($service, $deliveryTypes)) {
             continue;
         }
         if (isset($this->internationalTypes[$service])) {
             $serviceName = GetLang('DeliveryType' . $this->internationalTypes[$service]);
         } else {
             if (isset($this->domesticTypes[$service])) {
                 $serviceName = GetLang('DeliveryType' . $this->domesticTypes[$service]);
             }
         }
         $cost = (double) $quote->TotalCharges->MonetaryValue;
         $currencyCode = (string) $quote->TotalCharges->CurrencyCode;
         $quoteCurrency = GetCurrencyByCode($currencyCode);
         if ($quoteCurrency == false) {
             $this->SetError(sprintf(GetLang('UPSCurrencyCodeError'), $currencyCode));
             continue;
         }
         $transitTime = 0;
         if (isset($quote->GuaranteedDaysToDelivery)) {
             $transitTime = (string) $quote->GuaranteedDaysToDelivery;
         }
         $cost = ConvertPriceToDefaultCurrency($cost, $quoteCurrency);
         $quotes[] = new ISC_SHIPPING_QUOTE($this->GetId(), $this->GetDisplayName(), $cost, $serviceName, $transitTime);
     }
     return $quotes;
 }
Exemplo n.º 2
0
	/**
	* Gets the estimated fees and costs of a listing for eBay
	*
	*/
	private function getEstimatedListingCostsAction()
	{
		$productOptions = $_POST['productOptions'];
		$productCount = (int)$_POST['productCount'];
		$templateId = (int)$_POST['templateId'];
		$listingDate = $_POST['listingDate'];
		$scheduleDate = $_POST['scheduleDate'];

		$testProduct = array(
			'productid'			=> 0,
			'prodname'			=> 'Test Product',
			'proddesc'			=> 'Description',
			'prodcode'			=> 'SKU',
			'prodprice'			=> 50.00,
			'prodcondition'		=> 'New',
			'prodweight'		=> 5,
			'prodwidth'			=> 5,
			'prodheight'		=> 5,
			'proddepth'			=> 5,
			'prodvariationid'	=> 0,
		);

		try {
			$template = new ISC_ADMIN_EBAY_TEMPLATE($templateId);

			if ($listingDate == 'schedule') {
				$isoScheduleDate = date('c', $scheduleDate);

				$template->setScheduleDate($isoScheduleDate);
			}

			$result = ISC_ADMIN_EBAY_LIST_PRODUCTS::verifyListItem($testProduct, $template);

			// was there item level errors? we want to display those.
			if (!$result->isValid()) {
				$errorMessage = implode('<br />', $result->getErrors());
				throw new Exception($errorMessage);
			}
		}
		catch (Exception $ex) {
			ISC_JSON::output(isc_html_escape($ex->getMessage()), false);
		}

		$firstFee = current($result->getFees());
		$currencyCode = $firstFee['currency'];
		$currency = GetCurrencyByCode($currencyCode);

		$estimatedTotal = 0;
		$perItem = 0;
		$fees = array();
		foreach ($result->getFees() as $fee) {
			if ($fee['fee'] == 0 || $fee['name'] == 'ListingFee') {
				continue;
			}

			$fees[] = array(
				'name' => GetLang('EbayFee' . $fee['name']),
				'fee' => $this->formatFee($fee['fee'], $currency)
			);

			$perItem += $fee['fee'];
		}

		$quantityPerProduct = 1;
		if ($template->getSellingMethod() == ISC_ADMIN_EBAY::CHINESE_AUCTION_LISTING) {
			$quantityPerProduct = $template->getQuantityToSell();
		}
		$this->template->assign('quantity', $quantityPerProduct);

		$itemCount = $productCount * $quantityPerProduct;

		// estimated total fees
		$itemsTotal = $perItem * $productCount;
		$grandTotal = $itemsTotal * $quantityPerProduct;

		$this->template->assign('fees', $fees);
		$this->template->assign('currencyCode', $currencyCode);
		$this->template->assign('itemsTotal', $this->formatFee($itemsTotal, $currency));
		$this->template->assign('grandTotal', $this->formatFee($grandTotal, $currency));
		$this->template->assign('perItem', $this->formatFee($perItem, $currency));
		$this->template->assign('productCount', $productCount);
		$this->template->assign('itemCount', $itemCount);

		// build description of extra fees
		$extraFeesString = GetLang('EbayListingEstimatedCostsExtraFees');
		$extraFees = array();
		if ($template->getQuantityToSell() > $template->getTrueQuantityToSell()) {
			$extraFees[] = GetLang('EbayListingEstimatedCostsAuctionWarning', array('quantity' => $template->getQuantityToSell()));
		}
		$extraFees[] = GetLang('EbayListingEstimatedCostsFinalValueFee');

		foreach ($extraFees as $x => $fee) {
			$extraFeesString .= "\n\n" . ($x + 1) . '. ' . $fee;
		}

		$out = array(
			'html' 		=> $this->template->render('ebay.listproducts.estimatedcosts.tpl'),
			'extraFees' => $extraFeesString,
		);

		ISC_JSON::output('', true, $out);
	}
Exemplo n.º 3
0
	/**
	 * This function get all the available eBay live listing for the user and return a string of the managing template html.
	 * @return string Return the html of the eBay live listing page
	 */
	public function ManageEbayLiveListingGrid()
	{
		// Show a list of ebay item in a table
		$page = 0;
		$start = 0;
		$numListing = 0;
		$numPages = 0;
		$GLOBALS['EbayListingGrid'] = "";
		$GLOBALS['Nav'] = "";
		$max = 0;
		$searchURL = '';

		if (isset($_GET['searchQueryListing']) && isset($_GET['listingType']) && isset($_GET['listingStatus'])) {
			$GLOBALS['ListingQuery'] = $query['searchQueryListing'] = $_GET['searchQueryListing'];
			$GLOBALS['ListingType'] = $query['listingType'] = $_GET['listingType'];
			$GLOBALS['ListingStatus'] = $query['listingStatus'] = $_GET['listingStatus'];
			$searchURL = '&amp;searchQueryListing='.$query;
			foreach ($query as $k => $v) {
				$searchURL .= "&amp;$k=$v";
			}
		} else {
			$query = "";
			$GLOBALS['Query'] = "";
		}

		if (isset($_GET['sortOrder']) && $_GET['sortOrder'] == 'asc') {
			$sortOrder = 'asc';
		} else {
			$sortOrder = "desc";
		}

		$sortLinks = array(
			"Item" => "ei.title",
			"DateListed" => "ei.datetime_listed",
			"Type" => "ei.listing_type",
			"Status" => "ei.listing_status",
			"BidCount" => "ei.bid_count",
			"QuantityRemaining" => "ei.quantity_remaining",
			"CurrentPrice" => "ei.current_price",
			"BinPrice" => "ei.buyitnow_price",
			"OrderNumber" => "order_no",
		);


		if (isset($_GET['sortField']) && in_array($_GET['sortField'], $sortLinks)) {
			$sortField = $_GET['sortField'];
			SaveDefaultSortField("ManageEbayListing", $_REQUEST['sortField'], $sortOrder);
		}
		else {
			$sortField = "ei.datetime_listed";
			list($sortField, $sortOrder) = GetDefaultSortField("ManageEbayListing", $sortField, $sortOrder);
		}

		if (isset($_GET['page'])) {
			$page = (int)$_GET['page'];
		} else {
			$page = 1;
		}

		$sortURL = sprintf("&sortField=%s&sortOrder=%s", $sortField, $sortOrder);
		$GLOBALS['SortURL'] = $sortURL;

		// Limit the number of questions returned
		if ($page == 1) {
			$start = 1;
		} else {
			$start = ($page * ISC_EBAY_LISTING_PER_PAGE) - (ISC_EBAY_LISTING_PER_PAGE-1);
		}

		$start = $start-1;

		// Get the results for the query
		$listingResult = $this->_GetEbayListingList($query, $start, $sortField, $sortOrder, $numListing);
		$numPages = ceil($numListing / ISC_EBAY_LISTING_PER_PAGE);

		// Add the "(Page x of n)" label
		if($numListing > ISC_EBAY_LISTING_PER_PAGE) {
			$GLOBALS['Nav'] = sprintf("(%s %d of %d) &nbsp;&nbsp;&nbsp;", GetLang('Page'), $page, $numPages);
			$GLOBALS['Nav'] .= BuildPagination($numListing, ISC_EBAY_LISTING_PER_PAGE, $page, sprintf("index.php?ToDo=viewEbay&currentTab=0%s", $sortURL));
		}
		else {
			$GLOBALS['Nav'] = "";
		}

		$GLOBALS['Nav'] = rtrim($GLOBALS['Nav'], ' |');
		$GLOBALS['SearchQueryListing'] = $query;
		$GLOBALS['SortField'] = $sortField;
		$GLOBALS['SortOrder'] = $sortOrder;

		BuildAdminSortingLinks($sortLinks, "index.php?ToDo=viewEbay&amp;currentTab=0&amp;".$searchURL."&amp;page=".$page, $sortField, $sortOrder);

		// Workout the maximum size of the array
		$max = $start + ISC_EBAY_LISTING_PER_PAGE;

		if ($max > count($listingResult)) {
			$max = count($listingResult);
		}
		if($numListing > 0) {
			$GLOBALS['ManageEbayLiveListingIntro'] = sprintf(GetLang('ManageEbayLiveListingIntro'), $numListing);

			// Display the live listing
			while ($row = $GLOBALS["ISC_CLASS_DB"]->Fetch($listingResult))
			{
				$GLOBALS['Item'] = isc_html_escape($row['title']);
				if (trim($row['ebay_item_link'])) {
					$GLOBALS['Item'] = '<a target="_blank" href="'.$row['ebay_item_link'].'">' .$GLOBALS['Item']. '</a>';
				}
				$GLOBALS['DateListed'] = CDate($row['datetime_listed']);
				$GLOBALS['Type'] = GetLang(isc_html_escape($row['listing_type']));
				$GLOBALS['Status'] = GetLang(isc_html_escape(ucfirst($row['listing_status'])));
				$GLOBALS['BidCount'] = GetLang('NA');
				if (!empty ($row['bid_count'])) {
					$GLOBALS['BidCount'] = $row['bid_count'];
				}
				$GLOBALS['QuantityRemaining'] = GetLang('NA');
				if (!empty ($row['quantity_remaining'])) {
					$GLOBALS['QuantityRemaining'] = $row['quantity_remaining'];
				}
				$currentPriceCurrency = GetCurrencyByCode($row['current_price_currency']);
				$GLOBALS['CurrentPrice'] = FormatPriceInCurrency($row['current_price'], $currentPriceCurrency['currencyid']);
				$binPriceCurrency = GetCurrencyByCode($row['buyitnow_price_currency']);
				$GLOBALS['BinPrice'] = FormatPriceInCurrency($row['buyitnow_price'], $binPriceCurrency['currencyid']);
				$GLOBALS['OrderNumber'] = $row['order_no'];
				if ($row['order_no'] == '') {
					$GLOBALS['OrderNumber'] = '';
				}
				$GLOBALS['EbayItemId'] = $row['ebay_item_id'];
				if ($row['listing_type'] == 'FixedPriceItem') {
					$GLOBALS['BinPrice'] = $GLOBALS['CurrentPrice'];
					$GLOBALS['CurrentPrice'] = GetLang('NA');
				}

				$GLOBALS['EbayListingGrid'] .= $this->template->render('ebay.listing.manage.row.tpl');
			}

			return $this->template->render('ebay.listing.manage.grid.tpl');
		}
		$GLOBALS['ShowListingOptions'] = 'display:none;';
		return '';
	}
Exemplo n.º 4
0
		                		        <tr bgcolor=#CCCCCC><td colspan=5 height=1></td></tr>
	        		                <?php 
                                                                                                                                                                                                            }
                                                                                                                                                                                                        } else {
                                                                                                                                                                                                            if ($payy->type == "onpay" and ($payy->isdefault and !@in_array($payy->id, $disallowedPayments) or @in_array($payy->id, $allowedPayments))) {
                                                                                                                                                                                                                $onpay_login = $payy->text1;
                                                                                                                                                                                                                $onpay_secret = decodePwd($payy->pass1);
                                                                                                                                                                                                                $onpay_select1 = $payy->select1;
                                                                                                                                                                                                                $onpay_select1 = @mb_split(":x:", $onpay_select1);
                                                                                                                                                                                                                $onpay_currency = $payy->currency;
                                                                                                                                                                                                                $onpay_comment = $payy->comment;
                                                                                                                                                                                                                if ($onpay_login and $onpay_secret) {
                                                                                                                                                                                                                    if (!$onpay_currency) {
                                                                                                                                                                                                                        $onpay_currency = "RUB";
                                                                                                                                                                                                                    }
                                                                                                                                                                                                                    $onpay_currency = GetCurrencyByCode($onpay_currency);
                                                                                                                                                                                                                    $money_onpay = $money * $onpay_currency->koeficient;
                                                                                                                                                                                                                    $onpay_symbol = $onpay_currency->symbol;
                                                                                                                                                                                                                    $money_onpay = $money_onpay + $money_onpay / 100 * $payy->small1;
                                                                                                                                                                                                                    $money_onpay = round($money_onpay, 2);
                                                                                                                                                                                                                    ?>
							<tr>
							<td valign=top><BR><A class=rootlink href="http://onpay.ru/" target=_blank><img src="./_rootimages/logo_onpay.gif" border=0></a>&nbsp;&nbsp;&nbsp;&nbsp;</td>
				                        <td width=10>&nbsp;</td>
							<td width=1 bgcolor=#CCCCCC></td>
							<td width=10>&nbsp;</td>
							<td><BR>
						
							<B>:: <?php 
                                                                                                                                                                                                                    print $_lang[payOnPay];
                                                                                                                                                                                                                    ?>
	/**
	* Ebay: Sent to a seller when a buyer completes the checkout process for an item. Not sent when an auction ends without bids.
	*
	* My notes: Seems to be triggered when the buyer's payment process for an AUCTION item has completed, is not fired for fixed price items which fire 'FixedPrice...' notifications instead
	*
	* @param array $body
	*/
	protected function _handleAuctionCheckoutComplete($body)
	{
		// The data fields in the notification are the same as those returned by the GetItemTransactions call with the default detail level.
		if (!empty ($body['Item']['ItemID']) && ISC_ADMIN_EBAY::validEbayItemId($body['Item']['ItemID'])) {
			// variables init
			$order = array();
			$orderId = 1;
			$order['ShippingInsuranceCost'] = 0;
			$completedPaymentHoldStatus = array('None', 'Released');
			$orderStatus = ORDER_STATUS_AWAITING_PAYMENT;
			$existingOrderId = 0;

			// Determine if the buyer purchase multiple items from the same seller
			if (!empty($body['TransactionArray']['Transaction']['ContainingOrder'])) {
			 // Call the operation to get the order transaction.
				$orderId = $body['TransactionArray']['Transaction']['ContainingOrder']['OrderID'];

				// if the record already exist, check if we need to update existing orders, that the payment hasn't been cleared previously.
				$existingOrder = GetOrderByEbayOrderId($orderId);
				$orderTransaction = ISC_ADMIN_EBAY_OPERATIONS::getOrderTransactions($orderId);
				$transactions = $orderTransaction->OrderArray->Order->TransactionArray->Transaction;

				$order['SubTotal'] = (string) $orderTransaction->OrderArray->Order->Subtotal;
				$order['ShippingCost'] = (string) $orderTransaction->OrderArray->Order->ShippingServiceSelected->ShippingServiceCost;
				$order['ShippingInsuranceCost'] = 0;
				$order['GrandTotal'] = (string) $orderTransaction->OrderArray->Order->Total;
				$order['TotalQuantityPurchased'] = 0;
				foreach ($transactions as $transaction) {
					$convertedTransaction = (array) $transaction;
					$variationOptionsString = '';
					if (isset($convertedTransaction['Variation']->VariationSpecifics)) {
						$variationNameValueList = (array) $convertedTransaction['Variation']->VariationSpecifics->NameValueList;
						$variationOptions = array();
						$variationSpecifics = (array) $convertedTransaction['Variation']->VariationSpecifics;
						if (is_array($variationSpecifics['NameValueList'])) {
							foreach ($variationSpecifics['NameValueList'] as $option) {
								$variationOptions[(string) $option->Name] = (string) $option->Value;
							}
						} else {
							$variationOptions[(string) $variationSpecifics['NameValueList']->Name] = (string) $variationSpecifics['NameValueList']->Value;
						}
						$variationOptionsString = serialize($variationOptions);
					}
					$quantityPurchased = $convertedTransaction['QuantityPurchased'];
					$transactionPrice = $convertedTransaction['TransactionPrice'];
					$itemId = (string) $convertedTransaction['Item']->ItemID;
					$transactionId = (string) $convertedTransaction['TransactionID'];
					$totalTransactionPrice = $transactionPrice * $quantityPurchased;
					$order['Transaction'][] = array(
						'QuantityPurchased' => $quantityPurchased,
						'TransactionPrice' => $transactionPrice,
						'ItemId' => $itemId,
						'TotalTransactionPrice' => $totalTransactionPrice,
						'VariationOptionsString' => $variationOptionsString,
						'TransactionId' => $transactionId,
					);
					$order['TotalQuantityPurchased'] += $quantityPurchased;
					$order['Currency'] = GetCurrencyByCode($body['TransactionArray']['Transaction']['AmountPaid']['!currencyID']);
					$buyerInfoShippingAddress = $body['TransactionArray']['Transaction']['Buyer']['BuyerInfo']['ShippingAddress'];
					$buyerEmailAddress = $body['TransactionArray']['Transaction']['Buyer']['Email'];
				}

				if ($existingOrder) {
					$existingOrderId = $existingOrder['orderid'];
				}
			}
			else {
				$transactions = $body['TransactionArray'];
				foreach ($transactions as $transaction) {
					$itemId = $body['Item']['ItemID'];
					$transactionId = $transaction['TransactionID'];
					$query = "
						SELECT *
						FROM [|PREFIX|]order_products
						WHERE ebay_item_id = '".$GLOBALS["ISC_CLASS_DB"]->Quote($itemId)."'
							AND ebay_transaction_id = '".$GLOBALS["ISC_CLASS_DB"]->Quote($transactionId)."'
						LIMIT 1
					";
					$res = $GLOBALS['ISC_CLASS_DB']->Query($query);
					$row = $GLOBALS['ISC_CLASS_DB']->Fetch($res);
					$eachItemPriceExTax = $transaction['TransactionPrice']['!'];
					$quantityPurchased = $transaction['QuantityPurchased'];
					$totalTransactionPrice = $quantityPurchased * $eachItemPriceExTax;
					$variationOptionsString = '';

					// do we have a variation for this product?
					if (isset($transaction['Variation']['VariationSpecifics'])) {
						$variationNameValueList = $transaction['Variation']['VariationSpecifics']['NameValueList'];
						$variationOptions = array();
						foreach ($variationNameValueList as $option) {
							$variationOptions[$option['Name']] = $option['Value'];
						}
						$variationOptionsString = serialize($variationOptions);
					}
					$order['TotalQuantityPurchased'] = $quantityPurchased;
					$order['SubTotal'] = $eachItemPriceExTax * $order['TotalQuantityPurchased'];
					$order['ShippingCost'] = $transaction['ShippingServiceSelected']['ShippingServiceCost']['!'];
					if (isset ($transaction['ShippingServiceSelected']['ShippingInsuranceCost']['!'])) {
						$order['ShippingInsuranceCost'] = $transaction['ShippingServiceSelected']['ShippingInsuranceCost']['!'];
					}
					$order['GrandTotal'] = $transaction['AmountPaid']['!'];
					$order['Transaction'][] = array(
						'QuantityPurchased' => $quantityPurchased,
						'TransactionPrice' => $eachItemPriceExTax,
						'ItemId' => $itemId,
						'TotalTransactionPrice' => $totalTransactionPrice,
						'VariationOptionsString' => $variationOptionsString,
						'TransactionId' => $transactionId,
					);
					$order['Currency'] = GetCurrencyByCode($transaction['AmountPaid']['!currencyID']);
					$buyerInfoShippingAddress = $transaction['Buyer']['BuyerInfo']['ShippingAddress'];
					$buyerEmailAddress = $transaction['Buyer']['Email'];

					if (!$row) {
						// only process the new transaction
						break;
					} else {
						$existingOrderId = $row['orderorderid'];
					}
				}
			}

			$paymentHoldStatus = $body['TransactionArray']['Transaction']['Status']['PaymentHoldStatus'];
			if (in_array(trim($paymentHoldStatus), $completedPaymentHoldStatus)) {
				$orderStatus = ORDER_STATUS_AWAITING_FULFILLMENT;
			}
			if ($existingOrderId != 0) {
				if (!isset ($existingOrder)) {
					$existingOrder = GetOrder($existingOrderId, false, true, true);
				}

				// check if there're any existing order need to be updated.
				// in the case, paypal release the hold payment of buyer
				if ($existingOrder['ordstatus'] == ORDER_STATUS_AWAITING_PAYMENT
				&& $orderStatus == ORDER_STATUS_AWAITING_FULFILLMENT) {
					// update the quantity for each transaction
					$GLOBALS["ISC_CLASS_DB"]->StartTransaction();
					foreach ($order['Transaction'] as $eachTransaction) {
						// Get product Id
						try {
							$itemObj = new ISC_ADMIN_EBAY_ITEMS($eachTransaction['ItemId']);
							$productId = $itemObj->getProductId();
						} catch (Exception $e) {
							$this->log->LogSystemDebug('ebay', $e->getMessage());
							return false;
						}

						// update the item quantity in store
						$updatedData['quantity_remaining'] = $itemObj->getQuantityRemaining() - $eachTransaction['QuantityPurchased'];
						if (!$GLOBALS['ISC_CLASS_DB']->UpdateQuery('ebay_items', $updatedData, "ebay_item_id='" . $eachTransaction['ItemId'] . "'")) {
							$this->log->LogSystemDebug('ebay', $GLOBALS["ISC_CLASS_DB"]->Error());
							$GLOBALS["ISC_CLASS_DB"]->RollbackTransaction();
							return false;
						}
						if (!UpdateOrderStatus($existingOrderId, $orderStatus, true, true)) {
							$GLOBALS["ISC_CLASS_DB"]->RollbackTransaction();
							return false;
						}
					}
					$GLOBALS["ISC_CLASS_DB"]->CommitTransaction();

					// update the store inventory if necessary
					if (GetConfig('UpdateInventoryLevels') == 1) {
						DecreaseInventoryFromOrder($existingOrderId);
					}
					$this->log->LogSystemDebug('ebay', 'The status of the store order ('. $existingOrderId .') has been updated to: Awaiting Fulfillment');
				}
				return true;
			}

			$order['ShippingTotalCost'] = $order['ShippingInsuranceCost'] + $order['ShippingCost'];

			// Buyer's address information
			$addressMap = array(
				'Name',
				'CompanyName',
				'Street1',
				'Street2',
				'CityName',
				'PostalCode',
				'Country',
				'CountryName',
				'Phone',
				'StateOrProvince',
			);

			// Initialize the value, make sure it's not empty
			foreach ($addressMap as $key) {
				if (!isset($buyerInfoShippingAddress[$key])) {
					$buyerInfoShippingAddress[$key] = '';
				}
			}
			$buyerCountryId = GetCountryIdByISO2($buyerInfoShippingAddress['Country']);
			$buyerStateId = GetStateByName($buyerInfoShippingAddress['StateOrProvince'], $buyerCountryId);
			$buyerStateName = $buyerInfoShippingAddress['StateOrProvince'];
			if (!$buyerStateId) {
				$buyerStateId = GetStateByAbbrev($buyerInfoShippingAddress['StateOrProvince'], $buyerCountryId);
				$stateInfo = GetStateInfoById($buyerStateId);
				$buyerStateName = $stateInfo['statename'];
			}

			// Tokenize buyer's first and last name
			$nameTokens = explode(' ', $buyerInfoShippingAddress['Name']);
			$buyerFirstName = $nameTokens[0];
			$buyerLastName = '';
			if (!empty($nameTokens[1])) {
				$buyerLastName = $nameTokens[1];
			}

			$orderToken = generateOrderToken();

			// Preparing data to be inserted to orders table
			$newOrder = array(
				'ordtoken' => $orderToken,
				'orderpaymentmodule' => '',
				'orderpaymentmethod' => '',
				'orderpaymentmodule' => '',
				'extraInfo' => serialize(array()),
				'orddefaultcurrencyid' => $order['Currency']['currencyid'],
				'orddate' => time(),
				'ordlastmodified' => time(),
				'ordcurrencyid' => $order['Currency']['currencyid'],
				'ordcurrencyexchangerate' => 1,
				'ordipaddress' => GetIP(),
				'ordcustmessage' => '',
				'ordstatus' => $orderStatus,
				'base_shipping_cost' => $order['ShippingTotalCost'],
				'base_handling_cost' => 0,
				'ordbillemail' => $buyerEmailAddress,
				'ordbillfirstname' => $buyerFirstName,
				'ordbilllastname' => $buyerLastName,
				'ordbillcompany' => $buyerInfoShippingAddress['CompanyName'],
				'ordbillstreet1' => $buyerInfoShippingAddress['Street1'],
				'ordbillstreet2' => $buyerInfoShippingAddress['Street2'],
				'ordbillsuburb' => $buyerInfoShippingAddress['CityName'],
				'ordbillzip' => $buyerInfoShippingAddress['PostalCode'],
				'ordbillcountrycode' => $buyerInfoShippingAddress['Country'],
				'ordbillphone' => $buyerInfoShippingAddress['Phone'],
				'ordbillstateid' => (int) $buyerStateId,
				'ordbillstate' => $buyerStateName,
				'ordbillcountry' => $buyerInfoShippingAddress['CountryName'],
				'ordbillcountryid' => (int) $buyerCountryId,
				'total_ex_tax' => $order['GrandTotal'],
				'total_inc_tax' => $order['GrandTotal'],
				'shipping_cost_ex_tax' => $order['ShippingTotalCost'],
				'shipping_cost_inc_tax' => $order['ShippingTotalCost'],
				'subtotal_inc_tax' => $order['SubTotal'],
				'subtotal_ex_tax' => $order['SubTotal'],
				'ebay_order_id' => $orderId,
			);
			ResetStartingOrderNumber();

			// Start the transaction
			$GLOBALS["ISC_CLASS_DB"]->StartTransaction();

			// Inserting order data
			$newOrderId = $GLOBALS["ISC_CLASS_DB"]->InsertQuery('orders', $newOrder);
			if (!$newOrderId) {
				$this->log->LogSystemDebug('ebay', $GLOBALS["ISC_CLASS_DB"]->Error());
				$GLOBALS["ISC_CLASS_DB"]->RollbackTransaction();
				return false;
			}

			$orderAddress = array(
				'first_name' => $buyerFirstName,
				'last_name' => $buyerLastName,
				'company' => $buyerInfoShippingAddress['CompanyName'],
				'address_1' => $buyerInfoShippingAddress['Street1'],
				'address_2' => $buyerInfoShippingAddress['Street2'],
				'city' => $buyerInfoShippingAddress['CityName'],
				'zip' => $buyerInfoShippingAddress['PostalCode'],
				'country_iso2' => $buyerInfoShippingAddress['Country'],
				'phone' => $buyerInfoShippingAddress['Phone'],
				'total_items' => $order['TotalQuantityPurchased'],
				'email' => $buyerEmailAddress,
				'country_id' => (int) $buyerCountryId,
				'country' => $buyerInfoShippingAddress['CountryName'],
				'state_id' => (int) $buyerStateId,
				'state' => $buyerStateName,
				'order_id' => $newOrderId,
			);

			$addressId = $GLOBALS['ISC_CLASS_DB']->insertQuery('order_addresses', $orderAddress);
			if (!$addressId) {
				$this->log->LogSystemDebug('ebay', $GLOBALS["ISC_CLASS_DB"]->Error());
				$GLOBALS["ISC_CLASS_DB"]->RollbackTransaction();
				return false;
			}

			// Inserting order shipping
			$orderShipping = array(
				'order_address_id' => $addressId,
				'order_id' => $newOrderId,
				'base_cost' => $order['ShippingTotalCost'],
				'cost_inc_tax' => $order['ShippingTotalCost'],
				'cost_ex_tax' => $order['ShippingTotalCost'],
				'method' => 'Available on eBay',
			);

			if (!$GLOBALS['ISC_CLASS_DB']->insertQuery('order_shipping', $orderShipping)) {
				$this->log->LogSystemDebug('ebay', $GLOBALS["ISC_CLASS_DB"]->Error());
				$GLOBALS["ISC_CLASS_DB"]->RollbackTransaction();
				return false;
			}

			// Go thru each sold item in the order
			foreach ($order['Transaction'] as $eachTransaction) {
				// Get product Id
				try {
					$itemObj = new ISC_ADMIN_EBAY_ITEMS($eachTransaction['ItemId']);
					$productId = $itemObj->getProductId();
				} catch (Exception $e) {
					$this->log->LogSystemDebug('ebay', $e->getMessage());
					return false;
				}

				// Inserting order product
				$productObj = new ISC_PRODUCT($productId);
				$newProduct = array(
					'orderorderid' => $newOrderId,
					'ordprodid' => $productId,
					'ordprodsku' => $productObj->GetSKU(),
					'ordprodname' => $productObj->GetProductName(),
					'ordprodtype' => $productObj->GetProductType(),
					'ordprodqty' => $eachTransaction['QuantityPurchased'],
					'base_price' => $eachTransaction['TransactionPrice'],
					'price_ex_tax' => $eachTransaction['TransactionPrice'],
					'price_inc_tax' => $eachTransaction['TransactionPrice'],
					'price_tax' => 0,
					'base_total' => $eachTransaction['TotalTransactionPrice'],
					'total_ex_tax' => $eachTransaction['TotalTransactionPrice'],
					'total_inc_tax' => $eachTransaction['TotalTransactionPrice'],
					'total_tax' => 0,
					'base_cost_price' => 0,
					'cost_price_inc_tax' => 0,
					'cost_price_inc_tax' => 0,
					'cost_price_tax' => 0,
					'ordprodweight' => $productObj->GetWeight(false),
					'ordprodoptions' => $eachTransaction['VariationOptionsString'],
					'ordprodvariationid' => $productObj->_prodvariationid,
					'ordprodwrapid' => 0,
					'ordprodwrapname' => '',
					'base_wrapping_cost' => 0,
					'wrapping_cost_ex_tax' => 0,
					'wrapping_cost_inc_tax' => 0,
					'wrapping_cost_tax' => 0,
					'ordprodwrapmessage' => '',
					'ordprodeventname' => '',
					'ordprodeventdate' => 0,
					'ordprodfixedshippingcost' => $productObj->GetFixedShippingCost(),
					'order_address_id' => $addressId,
					'ebay_item_id' => $eachTransaction['ItemId'],
					'ebay_transaction_id' => $eachTransaction['TransactionId'],
				);

				$orderProductId = $GLOBALS['ISC_CLASS_DB']->insertQuery('order_products', $newProduct);
				if (!$orderProductId) {
					$this->log->LogSystemDebug('ebay', $GLOBALS["ISC_CLASS_DB"]->Error());
					$GLOBALS["ISC_CLASS_DB"]->RollbackTransaction();
					return false;
				}

				if ($orderStatus == ORDER_STATUS_AWAITING_FULFILLMENT) {
					// update the item quantity in store
					$updatedData['quantity_remaining'] = $itemObj->getQuantityRemaining() - $eachTransaction['QuantityPurchased'];
					if (!$GLOBALS['ISC_CLASS_DB']->UpdateQuery('ebay_items', $updatedData, "ebay_item_id='" . $eachTransaction['ItemId'] . "'")) {
						$this->log->LogSystemDebug('ebay', $GLOBALS["ISC_CLASS_DB"]->Error());
						$GLOBALS["ISC_CLASS_DB"]->RollbackTransaction();
						return false;
					}
				}
			}
			$GLOBALS["ISC_CLASS_DB"]->CommitTransaction();

			// update the store inventory if necessary
			if (GetConfig('UpdateInventoryLevels') == 1) {
				DecreaseInventoryFromOrder($newOrderId);
			}

			// Trigger new order notifications
			SendOrderNotifications($orderToken);

			$this->log->LogSystemDebug('ebay', 'An Item ('. $body['Item']['ItemID'] .') has been paid by the buyer and added to the store order (' . $newOrderId. ').');
			return true;
		}
		return false;
	}