Skip to content

Instantly share code, notes, and snippets.

@ali-cedcoss
Last active May 10, 2022 04:31
Show Gist options
  • Save ali-cedcoss/6fca0840320ffc536d858cfc7f97b3f8 to your computer and use it in GitHub Desktop.
Save ali-cedcoss/6fca0840320ffc536d858cfc7f97b3f8 to your computer and use it in GitHub Desktop.
indexing ebay products data locally

create a database to store the ebay products data

add_action('wp_ajax_nopriv_run_code', function(){
			global $wpdb;
			$table_name = $wpdb->prefix . 'ced_ebay_listings_data';
			$charset_collate = $wpdb->get_charset_collate();
			$sql = "CREATE TABLE IF NOT EXISTS ". $table_name . " (
				id BIGINT(20) unsigned NOT NULL,
				primary_category BIGINT(20) NOT NULL,
				listing_price BIGINT(20) NOT NULL,
				listing_stock BIGINT(20) NOT NULL,
				listing_title VARCHAR(255) NOT NULL,
				is_variation VARCHAR(255) NOT NULL,
				PRIMARY KEY (id)
				) $charset_collate;";
				$wpdb->query($sql);
				print_r($wpdb);

		});

actions to async store data in custom db

add_action('wp_ajax_nopriv_ced_ebay_save_products_data_async_endpoint', array($this, 'ced_ebay_save_products_data_async_endpoint'));
			add_action('ced_ebay_save_products_data_async_action', array($this, 'ced_ebay_save_products_data_async_method'));


public function ced_ebay_save_products_data_async_method($ebay_item){
		if(!empty($ebay_item)){
			$logger   = wc_get_logger();
			$context  = array( 'source' => 'ced_ebay_save_products_data_async_endpoint' );
			$listing_id = $ebay_item['listing_id'];
			$logger->info('Saving Data for '.wc_print_r($listing_id, true), $context);
			if('no' == $ebay_item['is_variation']){
				global $wpdb;
				if('no' == $ebay_item['update']){
					$logger->info('Adding new product to DB!', $context);
					$table_name = $wpdb->prefix . 'ced_ebay_listings_data';
					$wpdb->insert(
						$table_name,
						array(
							'id'                  => $listing_id,
							'primary_category'    => !empty($ebay_item['primary_category']) ? $ebay_item['primary_category'] : '',
							'primary_category_name'    => !empty($ebay_item['primary_category_name']) ? $ebay_item['primary_category_name'] : '',
							'listing_price'       => $ebay_item['listing_price'] ? $ebay_item['listing_price'] : '',
							'listing_stock'       => $ebay_item['listing_stock'] ? $ebay_item['listing_stock'] : '',
							'listing_title'       => $ebay_item['listing_title'] ? $ebay_item['listing_title'] : '',
							'is_variation'        => $ebay_item['is_variation'] ? $ebay_item['is_variation'] : '',
							'start_time'		  => $ebay_item['listing_start_time'] ? $ebay_item['listing_start_time'] : '',
						)
					);

					if(empty($wpdb->last_error)){
						$logger->info('Data Saved Successfully!', $context);
					} else {
						$logger->info('There was an error in saving the data in db!', $context);
					}
				} else {
					$logger->info('Updating existing product in DB!', $context);
					$table_name = $wpdb->prefix . 'ced_ebay_listings_data';
					$wpdb->update(
						$table_name,
						array(
							'id'                  => $listing_id,
							'primary_category'    => !empty($ebay_item['primary_category']) ? $ebay_item['primary_category'] : '',
							'primary_category_name'    => !empty($ebay_item['primary_category_name']) ? $ebay_item['primary_category_name'] : '',
							'listing_price'       => $ebay_item['listing_price'] ? $ebay_item['listing_price'] : '',
							'listing_stock'       => $ebay_item['listing_stock'] ? $ebay_item['listing_stock'] : '',
							'listing_title'       => $ebay_item['listing_title'] ? $ebay_item['listing_title'] : '',
							'is_variation'        => $ebay_item['is_variation'] ? $ebay_item['is_variation'] : '',
							'start_time'		  => $ebay_item['listing_start_time'] ? $ebay_item['listing_start_time'] : '',
						),
						array(
							'id'                  => $listing_id,
						)
					);

					if(empty($wpdb->last_error)){
						$logger->info('Data Updated Successfully!', $context);
					} else {
						$logger->info('There was an error in updating the data in db!', $context);
					}
				}

			} else {
				$logger->info('Skipping variable product '.wc_print_r($listing_id, true), $context);
			}
		}
	}

	public function ced_ebay_save_products_data_async_endpoint(){
		// delete_option('ced_ebay_import_listings_async_pagination');die('deleted');
	$logger   = wc_get_logger();
	$context  = array( 'source' => 'ced_ebay_save_products_data_async_endpoint' );
	require_once CED_EBAY_DIRPATH . 'admin/ebay/lib/ebayUpload.php';
	$user_id            = 'vintagetoymall';
	$ced_ebay_manager   = $this->ced_ebay_manager;
		$shop_data      = ced_ebay_get_shop_data( $user_id );
	if ( ! empty( $shop_data ) ) {
		$siteID = $shop_data['siteID'];
		$token  = $shop_data['token']['eBayAuthToken'];
	}
	$page_number            = get_option( 'ced_ebay_import_listings_async_pagination' ) ? get_option( 'ced_ebay_import_listings_async_pagination' ) : 1;
	$length                 = 10;
	$mainXml                = '
		<?xml version="1.0" encoding="utf-8"?>
		<GetMyeBaySellingRequest xmlns="urn:ebay:apis:eBLBaseComponents">
		  <RequesterCredentials>
			<eBayAuthToken>' . $token . '</eBayAuthToken>
		  </RequesterCredentials>
		  <ActiveList>
			<Sort>TimeLeft</Sort>
			<Pagination>
			 <EntriesPerPage>' . $length . '</EntriesPerPage>
			  <PageNumber>' . $page_number . '</PageNumber>
			</Pagination>
		  </ActiveList>
		</GetMyeBaySellingRequest>';
		$ebayUploadInstance = EbayUpload::get_instance( $siteID, $token );
		$activelist         = $ebayUploadInstance->get_active_products( $mainXml );
		// print_r($activelist);die;
		$logger->info(wc_print_r('>>>>>> Page Number '.$page_number.'/'.$activelist['ActiveList']['PaginationResult']['TotalNumberOfPages'].' <<<<<<<<', true), $context);
        if(!empty($activelist['ActiveList']['PaginationResult']['TotalNumberOfPages'])){
if($page_number > $activelist['ActiveList']['PaginationResult']['TotalNumberOfPages']){
			$logger->info('Reached end of list. Resetting page.', $context);
			update_option('ced_ebay_import_listings_async_pagination', 1);
			return;
		}
        }

		if(!isset($activelist['ActiveList']['ItemArray']['Item'][0])){
			$tempActiveList = array();
						$tempActiveList = $activelist['ActiveList']['ItemArray']['Item'];
						unset( $activelist['ActiveList']['ItemArray']['Item'] );
						$activelist['ActiveList']['ItemArray']['Item'][] = $tempActiveList;
		}
		if ( isset( $activelist['ActiveList']['ItemArray']['Item'][0] ) ) {
			$count_import_operations = 0;
			foreach ( $activelist['ActiveList']['ItemArray']['Item'] as $key => $value ) {
				$store_product  = array();
				$itemId         = ! empty( $value['ItemID'] ) ? $value['ItemID'] : false;
				$get_item_details            = '
				<?xml version="1.0" encoding="utf-8"?>
				<GetItemRequest xmlns="urn:ebay:apis:eBLBaseComponents">
				  <RequesterCredentials>
					<eBayAuthToken>' . $token . '</eBayAuthToken>
				  </RequesterCredentials>
				  <DetailLevel>ReturnAll</DetailLevel>
				  <ItemID>' . $itemId . '</ItemID>
				</GetItemRequest>';
				$itemDetails        = $ebayUploadInstance->get_item_details( $get_item_details );
                
$store_product = get_posts(
					array(
						'numberposts'  => -1,
						'post_type'    => 'product',
						'meta_key'     => '_ced_ebay_listing_id_' . $user_id,
						'meta_value'   => $itemId,
						'meta_compare' => '=',
					)
				);
							$store_product = wp_list_pluck( $store_product, 'ID' );
							if(!isset($itemDetails['Item']['Variations'])){
								$is_variation = 'no';
							} else {
								$is_variation = 'yes';
							}
							// print_r($store_product);die;
			if ( false != $itemId && empty($store_product) ) {
					global $wpdb;
					$table_name = $wpdb->prefix . 'ced_ebay_listings_data';
					// $itemId = '194307923370';
					$existing_record = $wpdb->get_results($wpdb->prepare("SELECT * FROM $table_name WHERE `id` = %s",$itemId), 'ARRAY_A');
					if(empty($existing_record[0])){
						++$count_import_operations;
						as_enqueue_async_action( 'ced_ebay_save_products_data_async_action', array('data'=>array(
							'listing_id'=>$itemId,
							'listing_title' => $itemDetails['Item']['Title'],
							'primary_category' => $itemDetails['Item']['PrimaryCategory']['CategoryID'],
							'primary_category_name' => $itemDetails['Item']['PrimaryCategory']['CategoryName'],
							'listing_price' => $itemDetails['Item']['StartPrice'],
							'listing_stock'=> $itemDetails['Item']['Quantity'] - $itemDetails['Item']['SellingStatus']['QuantitySold'],
							'is_variation' => $is_variation,
							'listing_start_time' => $itemDetails['Item']['ListingDetails']['StartTime'],
							'update' => 'no',
						)), 'ced_ebay_save_products_data_async' );
					} else {
						++$count_import_operations;
						as_enqueue_async_action( 'ced_ebay_save_products_data_async_action', array('data'=>array(
							'listing_id'=>$itemId,
							'listing_title' => $itemDetails['Item']['Title'],
							'primary_category' => $itemDetails['Item']['PrimaryCategory']['CategoryID'],
							'primary_category_name' => $itemDetails['Item']['PrimaryCategory']['CategoryName'],
							'listing_price' => $itemDetails['Item']['StartPrice'],
							'listing_stock'=> $itemDetails['Item']['Quantity'] - $itemDetails['Item']['SellingStatus']['QuantitySold'],
							'is_variation' => $is_variation,
							'listing_start_time' => $itemDetails['Item']['ListingDetails']['StartTime'],
							'update' => 'yes',
						)), 'ced_ebay_save_products_data_async' );
					}

			} else {
				++$count_import_operations;
			}
			}

			// die('done');

			if ( 10 == $count_import_operations ) {
				$next_page = ! empty( get_option( 'ced_ebay_import_listings_async_pagination' ) ) ? get_option( 'ced_ebay_import_listings_async_pagination' ) : 1;
				++$next_page;
				update_option( 'ced_ebay_import_listings_async_pagination', $next_page );
			} else {
				update_option( 'ced_ebay_import_listings_async_pagination', 1 );
			}
		} else {
			$logger->info('No listings found. API Error!', $context);
		}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment