Magento 2 sync products between two separate website by graph QL

By | December 26, 2024
Spread the love

Syncing products between two separate websites in Magento 2 using GraphQL involves fetching product data from one site and sending it to another via their GraphQL APIs. Below is a general guide to implement this:

1. Prerequisites

  • Magento 2 Setup: Ensure both websites are running Magento 2 and have their GraphQL APIs enabled.
  • API Tokens: Obtain admin or integration tokens for both sites to authenticate GraphQL requests.
  • Tools: Use a scripting language like PHP, Python, or Node.js to interact with GraphQL APIs.

2. Define GraphQL Queries

  1. Fetch Products: Use the products query to fetch product details from the source site.
    query {
      products(filter: {}) {
        items {
          sku
          name
          price {
            regularPrice {
              amount {
                value
                currency
              }
            }
          }
          description {
            html
          }
          custom_attributes {
            attribute_code
            value
          }
        }
      }
    }
  2. Create/Update Products: Use the createProduct or custom mutation in the destination site. Example:
    mutation {
      createProduct(
        input: {
          sku: "12345"
          name: "Product Name"
          price: 99.99
          type_id: "simple"
          attribute_set_id: 4
          description: "Description here"
          custom_attributes: [
            { attribute_code: "color", value: "red" }
          ]
        }
      ) {
        product {
          sku
          name
          price
        }
      }
    }
  3. Write the Sync Script

    Here’s a sample PHP script using Guzzle for API requests:

    <?php
    require 'vendor/autoload.php';
    
    use GuzzleHttp\Client;
    
    $sourceUrl = 'https://source-website.com/graphql';
    $destinationUrl = 'https://destination-website.com/graphql';
    $sourceToken = 'source-site-token';
    $destinationToken = 'destination-site-token';
    
    $client = new Client();
    
    // Fetch products from source site
    $response = $client->post($sourceUrl, [
        'headers' => [
            'Authorization' => "Bearer $sourceToken",
            'Content-Type' => 'application/json',
        ],
        'json' => [
            'query' => 'query { products(filter: {}) { items { sku name price { regularPrice { amount { value currency } } } } } }',
        ],
    ]);
    
    $products = json_decode($response->getBody()->getContents(), true)['data']['products']['items'];
    
    // Sync products to destination site
    foreach ($products as $product) {
        $mutation = '
        mutation {
            createProduct(
                input: {
                    sku: "' . $product['sku'] . '"
                    name: "' . addslashes($product['name']) . '"
                    price: ' . $product['price']['regularPrice']['amount']['value'] . '
                }
            ) {
                product {
                    sku
                    name
                }
            }
        }';
    
        $client->post($destinationUrl, [
            'headers' => [
                'Authorization' => "Bearer $destinationToken",
                'Content-Type' => 'application/json',
            ],
            'json' => ['query' => $mutation],
        ]);
    }
  4. Error Handling

    • Handle pagination for large product catalogs in the source products query.
    • Validate product attributes to avoid conflicts with the destination website schema.
    • Implement logging to track failed or skipped products.
  5. Testing

    • Test the script in a staging environment.
    • Verify that all product details (e.g., SKUs, prices, and descriptions) match between the source and destination websites.

    This approach ensures that products are synced between two separate Magento 2 websites using GraphQL. Let me know if you’d like help customizing this for your specific use case!