Skip to content

Instantly share code, notes, and snippets.

@ali-cedcoss
Last active April 25, 2022 14:13
Show Gist options
  • Save ali-cedcoss/6d7abd40bf1fdd128c461a7e3b01eb38 to your computer and use it in GitHub Desktop.
Save ali-cedcoss/6d7abd40bf1fdd128c461a7e3b01eb38 to your computer and use it in GitHub Desktop.
updating variable products SKUs
public function ced_ebay_prepareProductHtmlForUpdatingSKU($proIDs = array(), $userId){
		foreach ( $proIDs as $key => $value ) {
			$prod_data        = wc_get_product( $value );
			$type             = $prod_data->get_type();
			$item_id          = get_post_meta( $value, '_ced_ebay_listing_id_' . $userId, true );
			$preparedData     = $this->getFormattedDataForUpdatingSKU( $value, $userId, $item_id );
			return $preparedData;
		}
	}

	public function getFormattedDataForUpdatingSKU($value, $userId, $item_id){
		$logger = wc_get_logger();
		$context = array('source' => 'getFormattedDataForUpdatingSKU');
		$product = wc_get_product( $value );
		$product_data        = $product->get_data();
		$productType         = $product->get_type();
		$finalXml = '';
		$xmlArray = [];
		// $title = $product_data['name'];
		// $description = $product_data['description'] . ' ' . $product_data['short_description'];
		// $pictureUrl          = wp_get_attachment_image_url( get_post_meta( $value, '_thumbnail_id', true ), 'full' ) ? wp_get_attachment_image_url( get_post_meta( $value, '_thumbnail_id', true ), 'full' ) : '';
		$shop_data = ced_ebay_get_shop_data( $userId );
		if ( ! empty( $shop_data ) ) {
			$siteID      = $shop_data['siteID'];
			$token       = $shop_data['token']['eBayAuthToken'];
			$getLocation = $shop_data['Location'];
		}
		if ( ! empty( $item_id ) ) {
			$item['ItemID'] = $item_id;
		}


		if ( 'variable' == $productType ) {
			$variation_xml = $this->getFormattedDataForUpdatingVariationSKU( $value, $userId );
			// print_r($variation_xml);die;
			$item['Variations'] = 'ced';
			$xmlArray['Item']      = $item;
			$rootElement           = 'Item';
			$xml                   = new SimpleXMLElement( "<$rootElement/>" );
			$this->array2XML( $xml, $xmlArray['Item'] );
		} else {
			$xmlArray['Item']      = $item;
			$rootElement           = 'Item';
			$xml                   = new SimpleXMLElement( "<$rootElement/>" );
			$this->array2XML( $xml, $xmlArray['Item'] );
		}
		$val = $xml->asXML();
		$finalXml .= $val;
		$finalXml = str_replace( '<?xml version="1.0"?>', '', $finalXml );

		if ( 'variable' == $productType ) {
			if ( ! empty( $item_id ) ) {
				$xmlHeader = '<?xml version="1.0" encoding="utf-8"?>
				<ReviseFixedPriceItemRequest xmlns="urn:ebay:apis:eBLBaseComponents">
					<RequesterCredentials>
						<eBayAuthToken>' . $token . '</eBayAuthToken>
					</RequesterCredentials>
					<Version>859</Version>
					<ErrorLanguage>en_US</ErrorLanguage>
					<WarningLevel>High</WarningLevel>';
				$xmlFooter = '</ReviseFixedPriceItemRequest>';
			}
		} else {
			if ( ! empty( $item_id ) ) {
				$xmlHeader = '<?xml version="1.0" encoding="utf-8"?>
				<ReviseItemRequest xmlns="urn:ebay:apis:eBLBaseComponents">
					<RequesterCredentials>
						<eBayAuthToken>' . $token . '</eBayAuthToken>
					</RequesterCredentials>
					<Version>859</Version>
					<ErrorLanguage>en_US</ErrorLanguage>
					<WarningLevel>High</WarningLevel>';
				$xmlFooter = '</ReviseItemRequest>';
			}
		}

		$mainXML = $xmlHeader . $finalXml . $xmlFooter;
		$mainXML = str_replace( '<Variations>ced</Variations>', $variation_xml, $mainXML );
		// print_r($mainXML);die;
		if ( 'variable' == $productType ) {
			return array( $mainXML, true );
		} else {
			return array( $mainXML, false );
		}


	}

	public function getFormattedDataForUpdatingVariationSKU( $proIDs, $userId = '' ) {
		$_product = wc_get_product( $proIDs );
		// var_dump(wc_attribute_label('attribute_var1',$_product));
		$variation_attribute = $_product->get_variation_attributes();
		// print_r($variation_attribute);
		$allVariations = $_product->get_children();
		// print_r($allVariations);die;
		$primarycatId = $this->fetchMetaValueOfProduct( $proIDs, '_umb_ebay_category' );
		$shop_data    = ced_ebay_get_shop_data( $userId );
		if ( ! empty( $shop_data ) ) {
			$siteID      = $shop_data['siteID'];
			$token       = $shop_data['token']['eBayAuthToken'];
			$getLocation = $shop_data['Location'];
		}
		$file             = CED_EBAY_DIRPATH . 'admin/ebay/lib/cedGetcategories.php';
		$renderDependency = $this->renderDependency( $file );
		if ( $renderDependency ) {
			$cedCatInstance  = CedGetCategories::get_instance( $siteID, $token );
			$getCatSpecifics = $cedCatInstance->_getCatSpecifics( $primarycatId );
			$limit           = array( 'ConditionEnabled', 'ConditionValues' );
			$getCatFeatures  = $cedCatInstance->_getCatFeatures( $primarycatId, $limit );
			$getCatFeatures  = isset( $getCatFeatures['Category'] ) ? $getCatFeatures['Category'] : false;
		}
		$variationspecificsset  = '';
		$variationspecificsset .= '<VariationSpecificsSet>';

		foreach ( $variation_attribute as $attr_name => $attr_value ) {
			$taxonomy          = $attr_name;
			$attr_name         = str_replace( 'pa_', '', $attr_name );
			$attr_name         = str_replace( 'attribute_', '', $attr_name );
			$attr_name         = wc_attribute_label( $attr_name, $_product );
			$attr_name_by_slug = get_taxonomy( $taxonomy );
			if ( is_object( $attr_name_by_slug ) ) {
				$attr_name = $attr_name_by_slug->label;
			}
			$variationspecificsset .= '<NameValueList>';
			$variationspecificsset .= '<Name>' . $attr_name . '</Name>';
			foreach ( $attr_value as $k => $v ) {
				 $termObj = get_term_by( 'slug', $v, $taxonomy );
				if ( is_object( $termObj ) ) {
					$variationspecificsset .= '<Value>' . $termObj->name . '</Value>';
				} else {
					$variationspecificsset .= '<Value>' . $v . '</Value>';
				}
			}
			$variationspecificsset .= '</NameValueList>';
		}
		$variationspecificsset .= '</VariationSpecificsSet>';
		$variation              = '';
		foreach ( $allVariations as $key => $Id ) {
			$var_attr   = wc_get_product_variation_attributes( $Id );
			$variation .= '<Variation>';
			$mpn        = $this->fetchMetaValueOfProduct( $Id, '_umb_ebay_mpn' );
			$ean        = $this->fetchMetaValueOfProduct( $Id, '_umb_ebay_ean' );
			$isbn       = $this->fetchMetaValueOfProduct( $Id, '_umb_ebay_isbn' );
			$upc        = $this->fetchMetaValueOfProduct( $Id, '_umb_ebay_upc' );
			if ( empty( $ean ) ) {
				$ean = 'Does Not Apply';
			}
			if ( '' != $ean || '' != $isbn || '' != $upc ) {
				$variation .= '<VariationProductListingDetails>';
				if ( '' != $ean ) {
					$variation .= '<EAN>' . $ean . '</EAN>';
				}
				if ( '' != $isbn ) {
					$variation .= '<ISBN>' . $isbn . '</ISBN>';
				}
				if ( '' != $upc ) {
					$variation .= '<UPC>' . $upc . '</UPC>';
				}
				$variation .= '</VariationProductListingDetails>';
			} else {
				$variation .= '<VariationProductListingDetails>';
				$variation .= '<EAN>Does Not Apply</EAN>';
				$variation .= '</VariationProductListingDetails>';
			}
			$renderDataOnGlobalSettings = get_option( 'ced_ebay_global_settings', false );
			$amount                     = get_post_meta( $Id, '_stock', true );
			$manage_stock               = get_post_meta( $Id, '_manage_stock', true );
			$product_status             = get_post_meta( $Id, '_stock_status', true );
			$listing_stock_type         = isset( $renderDataOnGlobalSettings[ $userId ]['ced_ebay_product_stock_type'] ) ? $renderDataOnGlobalSettings[ $userId ]['ced_ebay_product_stock_type'] : '';
			$listing_stock              = isset( $renderDataOnGlobalSettings[ $userId ]['ced_ebay_listing_stock'] ) ? $renderDataOnGlobalSettings[ $userId ]['ced_ebay_listing_stock'] : '';

			if ( 'yes' != $manage_stock && 'instock' == $product_status ) {
				$renderDataOnGlobalSettings = get_option( 'ced_ebay_global_settings', false );
				if ( ! empty( $listing_stock_type ) && ! empty( $listing_stock ) && 'MaxStock' == $listing_stock_type ) {
					$amount = $listing_stock;
				} else {
					$amount = 1;
				}
			} else {
				if ( 'outofstock' != $product_status ) {
					if ( ! empty( $listing_stock_type ) && ! empty( $listing_stock ) && 'MaxStock' == $listing_stock_type ) {
						if ( $amount > $listing_stock ) {
							$amount = $listing_stock;
						} else {
							$amount = intval( $amount );
							if ( $amount < 1 ) {
								$amount = '0';
							}
						}
					} else {
						$amount = intval( $amount );
						if ( $amount < 1 ) {
							$amount = '0';
						}
					}
				} else {
					$amount = 0;
				}
			}

			$price                     = get_post_meta( $Id, '_price', true );
			$profile_price_markup_type = $this->fetchMetaValueOfProduct( $proIds, '_umb_ebay_profile_price_markup_type' );
			$profile_price_markup      = $this->fetchMetaValueOfProduct( $proIds, '_umb_ebay_profile_price_markup' );
			if ( ! empty( $profile_price_markup_type ) && ! empty( $profile_price_markup ) ) {
				if ( 'Fixed_Increase' == $profile_price_markup_type ) {
					$price = $price + $profile_price_markup;
				} elseif ( 'Percentage_Increase' == $profile_price_markup_type ) {
					$price = $price + ( ( $price * $profile_price_markup ) / 100 );
				} elseif ( 'Percentage_Decrease' == $profile_price_markup_type ) {
					$price = $price - ( ( $price * $profile_price_markup ) / 100 );
				} elseif ( 'Fixed_Decrease' == $profile_price_markup_type ) {
					$price = $price - $profile_price_markup;
				}
			}
			if ( get_option( 'ced_ebay_global_settings', false ) ) {
				$dataInGlobalSettings = get_option( 'ced_ebay_global_settings', false );
				$price_markup_type    = isset( $dataInGlobalSettings[ $userId ]['ced_ebay_product_markup_type'] ) ? $dataInGlobalSettings[ $userId ]['ced_ebay_product_markup_type'] : '';
				$price_markup_value   = isset( $dataInGlobalSettings[ $userId ]['ced_ebay_product_markup'] ) ? $dataInGlobalSettings[ $userId ]['ced_ebay_product_markup'] : '';
			}
			if ( 'Percentage_Increased' == $price_markup_type ) {
				$price = $price + ( ( $price * $price_markup_value ) / 100 );
				$msrp  = $msrp + ( ( $msrp * $price_markup_value ) / 100 );

			} elseif ( 'Fixed_Increased' == $price_markup_type ) {
				$price = $price + $price_markup_value;
				$msrp  = $msrp + $price_markup_value;
			} elseif ( 'Percentage_Decreased' == $price_markup_type ) {
				$price = $price - ( ( $price * $price_markup_value ) / 100 );
				$msrp  = $msrp - ( ( $msrp * $price_markup_value ) / 100 );
			} elseif ( 'Fixed_Decreased' == $price_markup_type ) {
				$price = $price - $price_markup_value;
				$msrp  = $msrp - $price_markup_value;
			}

			$sku = get_post_meta( $Id, '_sku', true );
			if ( empty( $sku ) ) {
				$sku = $Id;
			}

			$variation .= '
		<SKU>' . $sku . '</SKU>';
			$variation .= '<VariationSpecifics>';
			// var_dump($var_attr);die;
			foreach ( $var_attr as $key => $value ) {
				$taxonomy          = $key;
				$atr_name          = str_replace( 'attribute_', '', $key );
				$taxonomy          = $atr_name;
				$atr_name          = str_replace( 'pa_', '', $atr_name );
				$atr_name          = wc_attribute_label( $atr_name, $_product );
				$termObj           = get_term_by( 'slug', $value, $taxonomy );
				$attr_name_by_slug = get_taxonomy( $taxonomy );
				if ( is_object( $attr_name_by_slug ) ) {
					$atr_name = $attr_name_by_slug->label;
				}
				if ( is_object( $termObj ) ) {
					$variation .= '<NameValueList><Name>' . $atr_name . '</Name><Value>' . $termObj->name . '</Value></NameValueList>';
				} else {
					$variation .= '<NameValueList><Name>' . $atr_name . '</Name><Value>' . $value . '</Value></NameValueList>';

				}
			}
			$variation .= '</VariationSpecifics>';
			$variation .= '</Variation>';
		}
		$main_attribute = '<Variations>' . $variationspecificsset . $variation . '</Variations>';
		return $main_attribute;
		// print_r($main_attribute);die("daa");

	}


class-ebay.php

	public function prepareProductHtmlForUpdatingSKU( $proIDs = array(), $userId ) {
		if ( ! is_array( $proIDs ) ) {
			$proIDs = array( $proIDs );
		}
		$response = $this->ebayProductsInstance->ced_ebay_prepareProductHtmlForUpdatingSKU( $proIDs, $userId );
		return $response;

	}

admin.php

elseif ( 'update_sku' == $operation ) {
					$prodIDs          = $product_id[0];
					$already_uploaded = get_post_meta( $prodIDs, '_ced_ebay_listing_id_' . $user_id, true );
					if ( $already_uploaded ) {
						$SimpleXml = $ced_ebay_manager->prepareProductHtmlForUpdatingSKU( $prodIDs, $user_id );
// 						 print_r($SimpleXml);die;
						require_once CED_EBAY_DIRPATH . 'admin/ebay/lib/ebayUpload.php';
						$ebayUploadInstance = EbayUpload::get_instance( $siteID, $token );
						$uploadOnEbay       = $ebayUploadInstance->update( $SimpleXml[0], $SimpleXml[1] );
						print_r($uploadOnEbay);
						die;
						if ( is_array( $uploadOnEbay ) && ! empty( $uploadOnEbay ) ) {
							if ( isset( $uploadOnEbay['Ack'] ) ) {
								if ( 'Warning' == $uploadOnEbay['Ack'] || 'Success' == $uploadOnEbay['Ack'] ) {
									$ebayID = $uploadOnEbay['ItemID'];
									echo json_encode(
										array(
											'status'  => 200,
											'message' => 'Product Updated Successfully',
											'prodid'  => $prodIDs,
										)
									);
									die;
								} else {
									$error = '';
									if ( isset( $uploadOnEbay['Errors'][0] ) ) {
										foreach ( $uploadOnEbay['Errors'] as $key => $value ) {
											if ( 'Error' == $value['SeverityCode'] ) {
												$error .= $value['ShortMessage'] . '<br>';
											}
										}
									} else {
										$error .= $uploadOnEbay['Errors']['ShortMessage'] . '<br>';
									}
									echo json_encode(
										array(
											'status'  => 400,
											'message' => $error,
											'prodid'  => $prodIDs,
										)
									);
									die;
								}
							}
						}
					} else {
						echo json_encode(
							array(
								'status'  => 400,
								'message' => __(
									'Product Not Found On eBay',
									'woocommerce-ebay-integration'
								),
							)w
						);
						die;
					}
				}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment