DEV Community

VoiceDeveloper
VoiceDeveloper

Posted on

How to Integrate Voice AI with Shopify Stores

Why Voice AI Is a Game‑Changer for Shopify Stores

Imagine a shopper browsing your catalog, hearing a short, natural‑sounding description of each product, or asking a virtual assistant to “read me the latest reviews.” Voice AI can turn that vision into reality, boosting accessibility, engagement, and conversion rates.

Adding a text‑to‑speech (TTS) layer to a Shopify store isn’t as hard as it used to be. Modern APIs let you generate high‑quality audio on demand, and with a few lines of code you can stitch it into your theme, product pages, or even a custom Shopify app. In this guide we’ll walk through a practical, developer‑focused integration using the ElevenLabs TTS platform (the service I’ve been using for its natural voice cloning).

Pro tip: If you haven’t tried ElevenLabs yet, grab a free trial here: https://try.elevenlabs.io/kr07zfuqn1bp


1. Set Up an ElevenLabs Account and API Key

  1. Sign up at the link above.
  2. Navigate to Dashboard → API Keys and create a new key.
  3. Keep the key safe – you’ll need it in both server‑side and client‑side code.

ElevenLabs offers a robust REST API that accepts plain text and returns an MP3 (or WAV) stream. The API also supports voice cloning, so you can train a custom voice that matches your brand tone.


2. Create a Minimal Shopify Private App

You’ll need a way to call the ElevenLabs API from your store without exposing the secret key to browsers. The cleanest approach is a private app that runs on a lightweight server (Node.js, Python, or even a serverless function).

Steps in Shopify Admin

  1. Apps → Develop apps → Create an app → give it a name like “Voice AI Bridge.”
  2. Under Configuration, add the following scopes:
    • read_products (to fetch product titles/descriptions)
    • write_script_tags (to inject your JavaScript)
  3. Save and Install the app. Note the API key and API secret – you’ll use these for authentication when calling Shopify’s Admin API.

3. Build a Tiny Backend Service (Python Example)

Below is a Flask‑style snippet that receives a product ID, pulls the product description via Shopify’s REST API, sends it to ElevenLabs, and returns a signed URL to the generated audio.

# app.py
import os
import requests
from flask import Flask, request, jsonify
from shopify import Session, GraphQL

app = Flask(__name__)

SHOPIFY_STORE = os.getenv("SHOPIFY_STORE")      # e.g. myshop.myshopify.com
SHOPIFY_TOKEN = os.getenv("SHOPIFY_TOKEN")      # Private app access token
ELEVENLABS_KEY = os.getenv("ELEVENLABS_KEY")    # From your ElevenLabs dashboard

def get_product_description(product_id):
    url = f"https://{SHOPIFY_STORE}/admin/api/2023-10/products/{product_id}.json"
    headers = {"X-Shopify-Access-Token": SHOPIFY_TOKEN}
    resp = requests.get(url, headers=headers)
    resp.raise_for_status()
    return resp.json()["product"]["body_html"]

def synthesize_text(text, voice_id="21m00Tcm4TlvDq8ikWAM"):
    tts_url = "https://api.elevenlabs.io/v1/text-to-speech/{voice_id}"
    headers = {
        "xi‑api‑key": ELEVENLABS_KEY,
        "Content-Type": "application/json"
    }
    payload = {
        "text": text,
        "voice_settings": {"stability": 0.75, "similarity_boost": 0.85}
    }
    r = requests.post(tts_url.format(voice_id=voice_id), json=payload, headers=headers)
    r.raise_for_status()
    # ElevenLabs streams raw audio; we’ll just return the bytes
    return r.content

@app.route("/api/voice/<int:product_id>")
def voice_for_product(product_id):
    description = get_product_description(product_id)
    audio_bytes = synthesize_text(description)
    # Store in a temporary location (S3, Cloudinary, etc.). Here we use a data URI for demo.
    data_uri = "data:audio/mpeg;base64," + audio_bytes.encode("base64").replace("\n", "")
    return jsonify({"audio_src": data_uri})

if __name__ == "__main__":
    app.run(debug=True)
Enter fullscreen mode Exit fullscreen mode

Note: In production you’d want to cache the generated MP3 (e.g., in AWS S3) to avoid re‑synthesizing on every request and to keep latency low.


4. Inject a Front‑End Widget with Shopify Script Tags

Now that we have an endpoint that returns an audio URL, we can add a small JavaScript widget to each product page. The script fetches the audio and plays it when the user clicks a “Listen” button.

Create the Script Tag via Admin API

curl -X POST "https://myshop.myshopify.com/admin/api/2023-10/script_tags.json" \
  -H "X-Shopify-Access-Token: $SHOPIFY_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
        "script_tag": {
          "event": "onload",
          "src": "https://cdn.mycdn.com/voice-widget.js"
        }
      }'
Enter fullscreen mode Exit fullscreen mode

voice‑widget.js (client side)

// voice-widget.js
document.addEventListener("DOMContentLoaded", function () {
  // Only run on product pages
  if (!window.location.pathname.includes("/products/")) return;

  // Extract product handle from URL
  const handle = window.location.pathname.split("/products/")[1].split("?")[0];
  const productId = document.querySelector("[data-product-id]").dataset.productId;

  // Build UI
  const btn = document.createElement("button");
  btn.textContent = "🔊 Listen to description";
  btn.style.marginTop = "1rem";
  btn.style.padding = "0.5rem 1rem";
  btn.style.fontSize = "1rem";

  btn.addEventListener("click", async () => {
    btn.disabled = true;
    btn.textContent = "Loading…";

    try {
      const resp = await fetch(`/api/voice/${productId}`);
      const { audio_src } = await resp.json();

      const audio = new Audio(audio_src);
      audio.play();
    } catch (e) {
      console.error("Voice AI error:", e);
      alert("Sorry, we couldn’t load the audio right now.");
    } finally {
      btn.disabled = false;
      btn.textContent = "🔊 Listen again";
    }
  });

  // Insert button after the product title
  const title = document.querySelector("h1.product-single__title");
  title.parentNode.insertBefore(btn, title.nextSibling);
});
Enter fullscreen mode Exit fullscreen mode

The widget is deliberately tiny (≈30 lines) and works on any Shopify theme that respects the data-product-id attribute – most modern themes do.


5. Dealing with CORS and Security

  • CORS: Because the front‑end calls /api/voice/... on the same domain, you won’t hit CORS issues. If you host the backend elsewhere, add Access-Control-Allow-Origin: * (or restrict to your shop’s domain) on the Flask response.
  • API Key Safety: Never expose ELEVENLABS_KEY to the browser. Keep it on the server side, as shown in the Flask example. If you need client‑side access for voice cloning (e.g., user‑generated text), consider generating a short‑lived token via your backend.

6. Going Further – Voice Cloning & Multi‑Language Support

ElevenLabs lets you upload a few minutes of reference audio and create a custom voice that matches your brand’s personality. Once you have a voice ID, replace the default voice_id in the synthesize_text function.

For multilingual stores, you can pass the language parameter in the payload (supported languages are listed in the ElevenLabs docs). The same endpoint will give you native‑like pronunciation for Spanish, French, German, etc.


7. Testing & Debugging Tips

Issue Quick Fix
No audio plays Open dev tools → Network → Verify /api/voice/… returns a 200 and a data:audio/mpeg URL.
High latency (>2 s) Cache the MP3 in a CDN or S3 bucket; only synthesize when the description changes.
Voice sounds robotic Tune stability and similarity_boost in the payload; experiment with a different voice ID.
Script tag not loading Confirm the script URL is reachable and that the script_tag was created (GET /admin/api/2023-10/script_tags.json).

8. Scaling Up

  • Batch Generation: For large catalogs, run a background job that pre‑generates audio for every product and stores the URL in a metafield. Then your front‑end can simply read the metafield, eliminating on‑the‑fly synthesis.
  • Analytics: Hook into Shopify’s Events API to track voice_play events and see how many shoppers use the feature. Combine this data with conversion metrics to quantify ROI.

9. Wrap‑Up

Integrating voice AI into a Shopify store is now a matter of wiring three pieces together:

  1. ElevenLabs for high‑quality TTS (and optional voice cloning).
  2. A private Shopify app or serverless endpoint that safely calls the ElevenLabs API.
  3. A lightweight front‑end widget injected via a Script Tag.

With just a few dozen lines of code you can give your customers a richer, more inclusive shopping experience.

Ready to give your store a voice? Sign up for ElevenLabs using my affiliate link and start experimenting today: https://try.elevenlabs.io/kr07zfuqn1bp

Happy coding! 🚀

Top comments (0)