/** * Wait for the reports to be generated, requests and parses them. * * @param object $service * @param string $region * @param array $creds * @return string */ function do_report(MarketplaceWebService_Interface $service, $region, $creds) { // Retrieve, validate and add the report request ID to the template. if (!($requestID = trim(file_get_contents(CACHE_REQ_FILE . $region)))) { trigger_error('Could not read Request ID cache file', E_USER_ERROR); } // Create an array with the regional report request IDs. $requestID = explode("\n", $requestID); // Retrieve the start time, if set. Otherwise generate it now. if (is_file(CACHE_TIME_FILE . $region)) { $starttime = intval(file_get_contents(CACHE_TIME_FILE . $region)); } else { $starttime = time(); file_put_contents(CACHE_TIME_FILE . $region, $starttime); } $reportID = array(); // Create the request object to retrieve all reports from the last day. $request = new MarketplaceWebService_Model_GetReportListRequest(); $request->setMerchant($creds['merchant_id']); // $request->setAvailableFromDate (new DateTime ('-1 days', new DateTimeZone ('UTC'))); $IDList = new MarketplaceWebService_Model_IdList(); $IDs = array(); foreach ($requestID as $line) { list($region, $ID) = explode("\t", $line); $IDs[] = $ID; } $IDList->setId($IDs); $request->setReportRequestIdList($IDList); // $request->setAcknowledged (false); $reportID = array(); foreach ($requestID as $line) { // Split region and request ID, and ready region for use in constants. list($region, $ID) = explode("\t", $line); // If current regions report ID has been retrieved, skip to next. if (isset($reportID[$region])) { continue; } // Retrieve the report IDs. $ID = Get_ReportID($service, $request, $ID, $creds['merchant_id']); if ($ID) { $reportID[$region] = $ID; } } // Calculate running time. $runtime = intval((time() - $starttime) / 60); if ($runtime > 1) { $runtime .= " minutes"; } else { $runtime .= " minute"; } // If not all report IDs has been found, keep waiting for 1 more minute then refresh. if (count($reportID) != count($requestID)) { return $runtime; } // Fetch previously added items from dbfeeds_products_extra. $tableFeeds = TABLE_DBFEEDS_PROD_EXTRA; $tableProds = TABLE_PRODUCTS; $tableProdDesc = TABLE_PRODUCTS_DESCRIPTION; $query = <<<OutSQL SELECT p.`products_id`, fe.`extra_value` AS asin FROM dbfeed_products_extra AS fe INNER JOIN products AS p ON p.`products_id` = fe.`products_id` INNER JOIN products_description AS pd ON pd.`products_id` = p.`products_id` AND pd.`language_id` = 1 WHERE fe.`dbfeed_class` LIKE 'dbfeed_amazon%' AND `extra_field` = 'asin' GROUP BY p.`products_id` ORDER BY pd.`products_name` OutSQL; if (!($res = mysql_query($query))) { trigger_error("Could not retrieve local product details: " . $query . "\n" . mysql_error(), E_USER_ERROR); } // Store ASIN and PID in a temp array to check for existing products when parsing Amazon reports. $localData = array(); while ($row = mysql_fetch_array($res)) { $localData[$row['asin']] = $row['products_id']; } $amazonData = $skipList = array(); foreach ($reportID as $region => $ID) { // Retrieve report from Amazon. $request = new MarketplaceWebService_Model_GetReportRequest(); $request->setMerchant($creds['merchant_id']); $request->setReport(@fopen('php://memory', 'rw+')); $request->setReportId($ID); // Lower-case region for use in filename. $region = strtolower($region); // Retrieve report details and save for aggregation. $temp = explode("\n", mb_convert_encoding(Get_Report($service, $request), 'UTF-8')); // Fetch primary data for Canada. if ($region == 'ca') { // Create array of headers, for easier indexing of data. $headers = array_flip(explode("\t", trim(array_shift($amazonData['ca'])))); // Create the data source array in a specific order, to ensure there are no surprises later on. while ($product = array_shift($temp)) { $SKU = $product[$headers['seller-sku']]; // If current element exists in the skip-list: Skip. if (isset($skipList[$SKU])) { continue; } // New product, add to output data array. $amazonData[$SKU]['asin'] = ''; $amazonData[$SKU]['sku'] = $product[$headers['seller-sku']]; $amazonData[$SKU]['price'] = $product[$headers['price']]; $amazonData[$SKU]['desc'] = $product[$headers['item-name']]; $amazonData[$SKU]['name'] = $product[$headers['item-name']]; } } else { // Since CA's main report is lacking the ASIN, add it to the data array. if ($region == 'ca asin') { $headers = array_flip(explode("\t", trim(array_shift($amazonData['ca asin'])))); // Save all Amazon CA ASIN numbers, for later referencing. while ($product = array_shift($temp)) { $SKU = $product[$headers['sku']]; $ASIN = $product[$headers['asin']]; // If ASIN has been set in the database already. if (isset($localData[$ASIN])) { // Check if the main report has been processed. if (isset($amazonData[$SKU])) { // Have, remove current line from the output data array. unset($amazonData[$SKU]); } else { // Have not, add current product to the skip-list. $skipList[$SKU] = true; } // Skip to next element. continue; } // New product, add the ASIN to the output data array. $product = explode("\t", trim($product)); $amazonData[$SKU]['asin'] = $ASIN; } } else { // Create array of US CSV headers, for easier indexing of data. $headers = array_flip(explode("\t", trim(array_shift($temp)))); while ($product = array_shift($temp)) { // Explode the current CSV line, and ready variables for inclusion into the output data array. $product = explode("\t", trim($product)); $SKU = $product[$headers['seller-sku']]; $ASIN = $product[$headers['asin1']]; $name = $product[$headers['item-name']]; $price = $product[$headers['price']]; $desc = mb_substr($product[$headers['item-description']], 0, 100, 'UTF-8'); $amazonData[$SKU] = array('asin' => $ASIN, 'sku' => $SKU, 'price' => $price, 'desc' => $desc, 'name' => $name); } } } } // Serialize the data, and save it to temp file, so that we don't have to repeat all of this waiting again. if (!file_put_contents(CACHE_REP_FILE . $region, serialize($amazonData))) { trigger_error('Could not write to aggregate report data file.', E_USER_ERROR); } // Delete request ID cache file. unlink(CACHE_REQ_FILE . $region); unlink(CACHE_TIME_FILE . $region); // Redirect to next step. header("Location: http://{$_SERVER['SERVER_NAME']}{$_SERVER['SCRIPT_NAME']}?feed=" . rawurlencode($_GET['feed'])); die; }
function init($reportId) { $config = array('ServiceURL' => $this->serviceUrl, 'ProxyHost' => null, 'ProxyPort' => -1, 'MaxErrorRetry' => 3); $service = new MarketplaceWebService_Client(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, $config, APPLICATION_NAME, APPLICATION_VERSION); $request = new MarketplaceWebService_Model_GetReportRequest(); $request->setMerchant(MERCHANT_ID); $request->setReport(@fopen('php://memory', 'rw+')); $request->setReportId($reportId); return $this->invokeGetReport($service, $request); }
/** * @param ReportListItem $report * @return string */ public function getReport(ReportListItem $report) { $request = new \MarketplaceWebService_Model_GetReportRequest(); $request->setReport(@fopen('php://memory', 'rw+')); $request->setReportId($report->getReportId()); $request->setMerchant($this->config->getMerchantId()); $request->setMarketplace($this->config->getMarketPlaceId()); $this->service->getReport($request); $reportData = stream_get_contents($request->getReport()); return $reportData; }
function getAmazonNewOrders($with_header_message = true) { global $files; use_class('jng_sp_download'); $class_jd = new jng_sp_download(); $ready_path = SP_AMAZONEDE_DECRYPT_PATH; $archived_path = SP_AMAZONEDE_ARCHIVE_PATH; use_class('amazon/MarketplaceWebService/Client'); //MANDATORY CLASS use_class('amazon/MarketplaceWebService/Model/ErrorResponse'); //MANDATORY CLASS use_class('amazon/MarketplaceWebService/Model/GetReportRequest'); //FEED USED CLASS use_class('amazon/MarketplaceWebService/Model/GetReportResponse'); //FEED USED CLASS use_class('amazon/MarketplaceWebService/Model/GetReportListRequest'); //FEED USED CLASS use_class('amazon/MarketplaceWebService/Model/GetReportListResponse'); //FEED USED CLASS use_class('amazon/MarketplaceWebService/Model/TypeList'); //TYPE LIST CLASS $serviceUrl = "https://mws.amazonservices.de"; $aws_config = array('ServiceURL' => $serviceUrl, 'ProxyHost' => null, 'ProxyPort' => -1, 'MaxErrorRetry' => 3); $service = new MarketplaceWebService_Client(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, $aws_config, APPLICATION_NAME, APPLICATION_VERSION); $list = new MarketplaceWebService_Model_TypeList(); $list->setType('_GET_ORDERS_DATA_'); $report_from_date = new DateTime('-3 months', new DateTimeZone('UTC')); $report_to_date = new DateTime('now', new DateTimeZone('UTC')); $request = new MarketplaceWebService_Model_GetReportListRequest(); $request->setMerchant(MERCHANT_ID); $request->setMarketplace(MARKETPLACE_ID); $request->setAvailableToDate($report_to_date); $request->setAvailableFromDate($report_from_date); $request->setReportTypeList($list); $request->setAcknowledged(false); // echo"<pre>";var_dump($request);die(); $response = $service->getReportList($request); // echo"<pre>";var_dump($response);die(); if ($response->isSetGetReportListResult()) { if ($with_header_message) { echo "START DOWNLOADING NEW ORDERS FROM AMAZON PERIODE " . $report_from_date->format(DATE_ISO8601) . " TO " . $report_to_date->format(DATE_ISO8601) . "<br/>"; } $getReportListResult = $response->getGetReportListResult(); $reportInfoList = $getReportListResult->getReportInfoList(); if (count($reportInfoList) > 0) { $download_message = ' --- NO NEW ORDERS AVAILABLE ---<br/>'; foreach ($reportInfoList as $reportInfo) { if ($reportInfo->isSetReportId()) { $report_id = $reportInfo->getReportId(); $filename = date('Ymd') . '-' . $report_id . '.XML'; if (!$class_jd->isAlreadyDownloaded("jng_sp_id = 4 AND SUBSTRING_INDEX(filename, '-',-1) = '{$report_id}.XML'")) { $download_message = ''; echo " >> DOWNLOADING REPORT_ID: {$report_id} ... "; $fullpath_ready = $ready_path . $filename; $handle = fopen($fullpath_ready, 'w'); $request_report = new MarketplaceWebService_Model_GetReportRequest(); $request_report->setMarketplace(MARKETPLACE_ID); $request_report->setMerchant(MERCHANT_ID); $request_report->setReport($handle); $request_report->setReportId($report_id); $response_report = $service->getReport($request_report); echo "STREAMING XML {$filename} ... "; $archive_path_raw = $archived_path . 'raw/' . date('Y') . '/'; if (!file_exists($archive_path_raw)) { mkdir($archive_path_raw); } $fullpath_archive = $archive_path_raw . $filename; $class_jd->addDownload('4', 'ORDERS', $filename, 'R'); $files[] = $filename; fclose($handle); echo "PROCESS DONE<br/>"; } } } echo $download_message; } else { echo ' --- NO NEW ORDERS AVAILABLE ---<br/>'; } //LOOP MORE IF HAS NEXT NEW ORDERS if ($getReportListResult->isSetHasNext() && $getReportListResult->getHasNext()) { getAmazonNewOrders(false); } else { echo "DONE DOWNLOADING NEW ORDERS FROM AMAZON <br/>"; } } }