fix: Improve product matching to support SKU as barcode/GTIN
- Match products where WooCommerce SKU is stored as GTIN in Google - Also search Reports API by GTIN when SKU looks like a barcode - Supports stores that use barcodes (UPC/EAN) as their SKU Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
@@ -317,6 +317,11 @@ class Informatiq_SP_Google_API {
|
||||
/**
|
||||
* Find product by SKU or GTIN.
|
||||
*
|
||||
* Matching logic:
|
||||
* 1. SKU matches offerId
|
||||
* 2. SKU matches gtin (for stores where SKU is the barcode)
|
||||
* 3. GTIN matches gtin
|
||||
*
|
||||
* @param string $sku Product SKU.
|
||||
* @param string $gtin Product GTIN.
|
||||
* @return array|null Product data or null if not found.
|
||||
@@ -337,12 +342,18 @@ class Informatiq_SP_Google_API {
|
||||
|
||||
if ( ! empty( $response['products'] ) ) {
|
||||
foreach ( $response['products'] as $product ) {
|
||||
// Check if offerId (SKU) matches.
|
||||
// Check if offerId matches SKU.
|
||||
if ( isset( $product['offerId'] ) && $product['offerId'] === $sku ) {
|
||||
return $product;
|
||||
}
|
||||
|
||||
// Check if GTIN matches.
|
||||
// Check if SKU matches Google's GTIN (for stores where SKU is the barcode).
|
||||
if ( isset( $product['gtin'] ) && $product['gtin'] === $sku ) {
|
||||
$this->logger->info( "Product matched by GTIN={$sku} (SKU used as barcode)" );
|
||||
return $product;
|
||||
}
|
||||
|
||||
// Check if separate GTIN field matches.
|
||||
if ( ! empty( $gtin ) && isset( $product['gtin'] ) && $product['gtin'] === $gtin ) {
|
||||
return $product;
|
||||
}
|
||||
@@ -373,7 +384,7 @@ class Informatiq_SP_Google_API {
|
||||
// Use the Reports API to search for competitive visibility data.
|
||||
$endpoint = "/reports/v1beta/accounts/{$this->merchant_id}/reports:search";
|
||||
|
||||
// Query for price competitiveness report.
|
||||
// Try searching by offer_id first.
|
||||
$query = array(
|
||||
'query' => "SELECT
|
||||
offer_id,
|
||||
@@ -393,6 +404,28 @@ class Informatiq_SP_Google_API {
|
||||
}
|
||||
}
|
||||
|
||||
// If SKU looks like a GTIN (numeric, 8-14 digits), also try searching by gtin.
|
||||
if ( preg_match( '/^\d{8,14}$/', $sku ) ) {
|
||||
$query = array(
|
||||
'query' => "SELECT
|
||||
gtin,
|
||||
price_benchmark.price_benchmark_value,
|
||||
price_benchmark.price_benchmark_currency_code
|
||||
FROM PriceCompetitivenessProductView
|
||||
WHERE gtin = '{$sku}'",
|
||||
);
|
||||
|
||||
$response = $this->api_request( 'POST', $endpoint, $query );
|
||||
|
||||
if ( ! empty( $response['results'] ) ) {
|
||||
foreach ( $response['results'] as $result ) {
|
||||
if ( isset( $result['priceBenchmark']['priceBenchmarkValue']['amountMicros'] ) ) {
|
||||
return (float) $result['priceBenchmark']['priceBenchmarkValue']['amountMicros'] / 1000000;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
|
||||
} catch ( Exception $e ) {
|
||||
|
||||
Reference in New Issue
Block a user