Main site

Integrating with Third-Party APIs

Integrating third-party APIs into JsRates is straightforward: utilize the fetch API for HTTP requests to your desired API endpoint. This allows you to access and use the response data to enhance or adjust your content.

Take, for example, the integration with the Google Distance Matrix API. By sending a fetch request to its endpoint, you can obtain the distance between two addresses – the origin and the destination. This information can then be used in calculating your shipping rates. The sample code provided below illustrates how this can be accomplished.

The sample code assumes you have saved your Google API key in the environment object as a secret variable, see Adding secret variables on how to save your secret variable in the Settings page.

AI Prompt:

I'd like a shipping rate calculator that calculates the distance in km between the origin and destination addresses using Google Distance Matrix API (in driving mode) and the resulting distance in km is multiplied by $0.01 for shipping cost.
The API access key will be provided as part of the environment variable object.

AI Output:

export async function calculateShippingRates(DATA, env) {
  try {
    
    // Get the origin and destination addresses
    const origin = DATA.origin;
    const destination = DATA.destination;

    // Build the Google Distance Matrix API request URL
    const apiKey = env.GOOGLE_API_KEY;
    const url = `https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins=${origin.address1},${origin.city},${origin.province},${origin.country}&destinations=${destination.address1},${destination.city},${destination.province},${destination.country}&key=${apiKey}`;

    // Make the request to the Google Distance Matrix API
    const response = await fetch(url);
    const data = await response.json();

    // Get the distance in kilometers
    const distance = data.rows[0].elements[0].distance.value / 1000;

    // Calculate the shipping cost
    const shippingCost = distance * 0.01;

    // Return the shipping rates
    return {
      rates: [
        {
          service_name: "Standard Shipping",
          service_code: "standard",
          total_price: shippingCost * 100,
          description: "Standard shipping",
          currency: DATA.currency,
        },
      ],
    };
  } catch (error) {
    // Return an error rate
    return {
      rates: [
        {
          service_name: "",
          service_code: "",
          total_price: null,
          description: "",
          currency: "",
          min_delivery_date: "",
          max_delivery_date: "",
        },
      ],
    };
  }
}