Query the Zuora Product Catalog

Edited

This code uses React's useEffect hook to perform the operations when the component mounts. It utilizes axios for HTTP requests to interact with the Zuora API and assumes there is a backend API endpoint (/api/extracts) to handle database insertions.

import React, { useEffect } from 'react';
import axios from 'axios';

const ProductMigration = () => {
  useEffect(() => {
    const processMigration = async () => {
      const processName = 'product-migration';

      // Replace with your Zuora API credentials
      const zuoraClientId = 'YOUR_ZUORA_CLIENT_ID';
      const zuoraClientSecret = 'YOUR_ZUORA_CLIENT_SECRET';

      // Authenticate with Zuora API
      let zuoraAccessToken;
      try {
        const authResponse = await axios.post('https://rest.zuora.com/oauth/token', {
          client_id: zuoraClientId,
          client_secret: zuoraClientSecret,
          grant_type: 'client_credentials',
        });
        zuoraAccessToken = authResponse.data.access_token;
      } catch (error) {
        console.error('Error authenticating with Zuora:', error);
        return;
      }

      // Set up Zuora API headers
      const zuoraHeaders = {
        Authorization: `Bearer ${zuoraAccessToken}`,
        'Content-Type': 'application/json',
      };

      // Query for product IDs
      try {
        const queryResponse = await axios.post(
          'https://rest.zuora.com/v1/action/query',
          {
            queryString: 'select Id from Product',
          },
          {
            headers: zuoraHeaders,
          }
        );

        const products = queryResponse.data.records;

        for (const p of products) {
          console.log(`Fetching product ${p.Id}`);

          // Fetch product data
          const productResponse = await axios.get(
            `https://rest.zuora.com/v1/catalog/product/${p.Id}`,
            {
              headers: zuoraHeaders,
            }
          );

          const productData = productResponse.data;

          // Insert into extracts table
          await axios.post('/api/extracts', {
            process: processName,
            id: p.Id,
            name: 'product-catalog',
            data: productData,
          });

          // Iterate over productRatePlans
          const productRatePlans = productData.productRatePlans || [];

          for (const prp of productRatePlans) {
            const productRatePlanCharges = prp.productRatePlanCharges || [];

            for (const prpc of productRatePlanCharges) {
              // Fetch charge data
              const chargeResponse = await axios.get(
                `https://rest.zuora.com/v1/object/product-rate-plan-charge/${prpc.id}`,
                {
                  headers: zuoraHeaders,
                }
              );

              const chargeData = chargeResponse.data;

              // Insert into extracts table
              await axios.post('/api/extracts', {
                process: processName,
                id: prpc.id,
                name: 'product-rate-plan-charge',
                data: chargeData,
              });
            }
          }
        }
      } catch (error) {
        console.error('Error fetching data from Zuora:', error);
      }
    };

    processMigration();
  }, []);

  return null; // This component doesn't render anything
};

export default ProductMigration;

Notes:

  • Authentication: Make sure to replace 'YOUR_ZUORA_CLIENT_ID' and 'YOUR_ZUORA_CLIENT_SECRET' with your actual Zuora API credentials.

  • Backend API Endpoint: The code assumes there's an API endpoint at /api/extracts that handles inserting data into the extracts table. You'll need to implement this endpoint in your backend.

  • Error Handling: The code includes basic error handling with try...catch blocks. You might want to enhance this with more robust error management depending on your needs.

  • Dependencies: You'll need to install axios by running npm install axios in your project directory.

Explanation:

  • The ProductMigration component uses the useEffect hook to perform side effects (API calls) when the component mounts.

  • It authenticates with the Zuora API to obtain an access token.

  • It queries the Zuora API to get all product IDs.

  • For each product, it fetches detailed product data and posts it to the backend API for insertion into the database.

  • It parses the product data to extract productRatePlans and productRatePlanCharges.

  • For each charge, it fetches detailed charge data and posts it to the backend API.

Additional Steps:

  • Implement Backend Endpoint: You'll need to create the /api/extracts endpoint in your backend server to handle the POST requests and perform the database insertions.

  • CORS Configuration: If your backend is on a different domain or port, ensure you have CORS configured properly to allow requests from your React app.

  • Security: Handle sensitive information securely. Avoid committing API credentials to version control and consider using environment variables.

Usage:

  • Include the ProductMigration component in your React application where appropriate.

  • Ensure that your backend server is running and the necessary database tables are set up.

This React code is designed to work within a React environment, adhering to best practices for API interaction and data handling in a React application.