Save up to 40% on development costs from market

Shopify Real-Time Shipping Rates Integration

Overview

This implementation allows users to manually enter their shipping details (ZIP code, country, and province) and fetch real-time shipping rates on a Shopify product page. The rates are retrieved from Shopify’s shipping API, and the product is temporarily added to the cart for accurate calculations.

 

How It Works

  1. A form is provided where users enter their ZIP code, country, and province.

  2. When the form is submitted, JavaScript captures the input values and sends a request to Shopify to add the product temporarily to the cart.

  3. After adding the product, Shopify’s /cart/shipping_rates.json API is called with the provided shipping details.

  4. The API response is displayed, showing available shipping methods and costs.

  5. The product is then removed from the cart for cleanup.

  6. The response is logged in the browser console for debugging.

Installation

Step 1: Add the Form to Your Shopify Product Page

Include this form inside product.liquid or another relevant template file:

				
					<form id="shipping-form">
    <label for="zip">ZIP Code:</label>
    <input type="text" id="zip" name="zip" required />

    <label for="country">Country:</label>
    <input type="text" id="country" name="country" required />

    <label for="province">Province/State:</label>
    <input type="text" id="province" name="province" required />

    <button type="submit">Get Shipping Rates</button>
</form>

<div id="shipping-rates"></div>
				
			

Step 2: Add the JavaScript Code

Place this JavaScript inside your Shopify theme file (theme.liquid) or an external JavaScript file.

				
					document.addEventListener('DOMContentLoaded', function () {
    // Get the form and shipping rates container
    const shippingForm = document.getElementById('shipping-form');
    const shippingRatesContainer = document.getElementById('shipping-rates');

    // Event listener for form submission
    shippingForm.addEventListener('submit', function (event) {
        event.preventDefault(); // Prevent default form submission
        
        const zip = document.getElementById('zip').value;
        const country = document.getElementById('country').value;
        const province = document.getElementById('province').value;
        const variantId = {{ product.selected_or_first_available_variant.id }};

        // Add the product to the cart (temporarily) to calculate shipping rates
        fetch('/cart/add.js', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                items: [{ id: variantId, quantity: 1 }]
            })
        })
        .then(() => {
            // Fetch shipping rates based on user input
            return fetch(`/cart/shipping_rates.json?shipping_address[zip]=${zip}&shipping_address[country]=${country}&shipping_address[province]=${province}`);
        })
        .then(response => response.json())
        .then(data => {
            // Log response for debugging
            console.log("Shipping Rates API Response:", data);

            // Display shipping rates
            if (data.shipping_rates && data.shipping_rates.length > 0) {
                let ratesHTML = '<h3>Shipping Rates</h3>';
                data.shipping_rates.forEach(rate => {
                    ratesHTML += `<p>${rate.name}: ${rate.price}</p>`;
                });
                shippingRatesContainer.innerHTML = ratesHTML;
            } else {
                shippingRatesContainer.innerHTML = '<p>No shipping rates available.</p>';
            }
        })
        .catch(error => {
            console.error("Error fetching shipping rates:", error);
            shippingRatesContainer.innerHTML = '<p>Error calculating shipping rates. Please try again.</p>';
        })
        .finally(() => {
            // Remove the product from the cart (cleanup)
            fetch('/cart/clear.js', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' }
            });
        });
    });
});
				
			

Debugging & Testing

To test if everything is working correctly:

  1. Open your website.

  2. Right-click anywhere and select Inspect to open DevTools.

  3. Go to the Console tab.

  4. Submit the form and check for the log:

    Shipping Rates API Response: { shipping_rates: [...] }

    This helps debug any missing shipping rates.

Customization

Change Default Product Quantity

Currently, the script adds 1 unit of the product to the cart for rate calculation. To modify this, change:

quantity: 1

Increase or decrease the quantity as needed.

Modify Form Fields

  • You can customize the form labels, inputs, or add dropdowns for country selection.

  • Ensure the ID values in the JavaScript match those in the form (zip, country, province).

Troubleshooting

1. No Shipping Rates Available

  • Make sure the shipping zones and rates are configured in Shopify Admin.

  • Check the browser console for API response logs.

2. Shipping Rates API Returns an Error

  • Ensure that the ZIP, country, and province values are valid.

  • Double-check Shopify settings under Settings > Shipping and Delivery.

3. Debugging API Requests

  • Use console.log("Shipping Rates API Response:", data); in the script.

  • Open DevTools > Network Tab and inspect the requests made to Shopify.

Conclusion

This script provides a seamless way to fetch real-time shipping rates on the Shopify product page, allowing customers to calculate costs before checkout.

Let me know if you need further modifications or enhancements! 🚀

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top