<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Javin Towers on Medium]]></title>
        <description><![CDATA[Stories by Javin Towers on Medium]]></description>
        <link>https://medium.com/@towersjavin?source=rss-cfebd57ca9b3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*0QuM2UJ54YLA8hBmYcBn-A.jpeg</url>
            <title>Stories by Javin Towers on Medium</title>
            <link>https://medium.com/@towersjavin?source=rss-cfebd57ca9b3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 08:49:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@towersjavin/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Bridging the Gap: A Custom Manychat Pixel Solution for Multi-Platform Tracking]]></title>
            <link>https://medium.com/@towersjavin/bridging-the-gap-a-custom-manychat-pixel-solution-for-multi-platform-tracking-7bf923e9fb5b?source=rss-cfebd57ca9b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bf923e9fb5b</guid>
            <category><![CDATA[marketing-funnels]]></category>
            <category><![CDATA[shopify]]></category>
            <category><![CDATA[manychat]]></category>
            <category><![CDATA[webflow]]></category>
            <category><![CDATA[conversion-tracking]]></category>
            <dc:creator><![CDATA[Javin Towers]]></dc:creator>
            <pubDate>Tue, 29 Apr 2025 14:56:53 GMT</pubDate>
            <atom:updated>2025-04-29T14:56:53.527Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R0UeHLz0MtX4rLhru4C-TQ.png" /></figure><p>I’ve been working with a number of clients who run complex marketing funnels across multiple platforms, and I kept running into the same challenge: tracking user journeys that span across Manychat, Webflow, and Shopify.</p><p>The typical flow looks something like this:</p><ul><li>Customer engages with a Manychat automation in DMs</li><li>They click through to a Webflow landing page for more information</li><li>Finally, they click a purchase button that sends them to Shopify to complete their order</li></ul><p>The problem? Tracking breaks between these platforms. Manychat has a built-in pixel, but standard implementations don’t effectively track across this multi-platform journey.</p><h3>The Multi-Platform Attribution Challenge</h3><p>Manychat tracking works great when customers go directly from a chat flow to a purchase. But when your setup includes intermediate steps through Webflow (or any other platform), that attribution often gets lost.</p><p>What’s supposed to happen is:</p><ol><li>Manychat adds an mcp_token to outbound links</li><li>This token identifies the specific user and their source</li><li>When they eventually purchase, Manychat should attribute that conversion to the original flow</li></ol><p>But with multi-platform setups, that token often disappears during the journey.</p><h3>A Robust Solution</h3><p>To solve this problem, I created a custom Manychat Pixel implementation for Shopify’s Web Pixels API that specifically addresses this multi-platform gap. Here’s what it does:</p><ul><li>Captures the mcp_token when a user first arrives from Manychat</li><li>Stores it in a cookie for 28 days (per Manychat’s requirements)</li><li>Works alongside UTM parameter forwarding from Webflow</li><li>Fires appropriate events back to Manychat when actions happen on Shopify</li><li>Only tracks users who have a valid Manychat token (keeping data clean)</li></ul><p>This means if someone comes from a Manychat flow to your Webflow site, then later visits your Shopify store directly, you’ll still maintain that attribution. When they make a purchase, it gets properly attributed to the original Manychat flow that started their journey.</p><h3>The Implementation: Two Key Components</h3><h3>1. UTM Parameter Forwarding (Webflow)</h3><p>First, you need a script on your Webflow site that preserves both UTM parameters and the Manychat token when users click through to Shopify. Here’s a generalized version you can adapt:</p><pre>javascript</pre><pre>&lt;script&gt;<br>  document.addEventListener(&#39;DOMContentLoaded&#39;, function() {<br>    // Get URL parameters from current page<br>    const queryString = window.location.search;<br>    if (!queryString) return; // Exit if no parameters exist<br>    <br>    // Find all links to your Shopify store<br>    const shopifyLinks = document.querySelectorAll(&#39;a[href*=&quot;yourshopify.com&quot;]&#39;);<br>    if (!shopifyLinks.length) return; // Exit if no matching links<br>    <br>    // Parse the current URL parameters<br>    const currentUrlParams = new URLSearchParams(queryString);<br>    <br>    // Update each Shopify link with the parameters<br>    shopifyLinks.forEach(link =&gt; {<br>      const linkUrl = new URL(link.href);<br>      <br>      // Append all parameters (utm_source, utm_medium, mcp_token, etc.)<br>      for (const [key, value] of currentUrlParams.entries()) {<br>        linkUrl.searchParams.set(key, value);<br>      }<br>      <br>      // Update the link with the new URL<br>      link.href = linkUrl.toString();<br>    });<br>  });<br>&lt;/script&gt;</pre><p>Just replace yourshopify.com with your actual Shopify domain. Add this to the custom code section of your Webflow pages or use Webflow&#39;s custom code embed element.</p><h3>2. Custom Manychat Pixel (Shopify)</h3><p>Next, implement this custom Manychat Pixel code in your Shopify store (Settings &gt; Customer events &gt; Add custom pixel):</p><pre>/**<br> * Manychat Pixel Implementation for Shopify Web Pixels API<br> * <br> * This implementation:<br> * 1. Loads the Manychat Pixel scripts<br> * 2. Validates MCP token presence (required for tracking)<br> * 3. Stores the token in a cookie for 28 days (per Manychat docs)<br> * 4. Tracks Shopify standard events and maps them to Manychat events<br> */</pre><pre>// Manychat Page ID - from the embed script<br>const MANYCHAT_PAGE_ID = &#39;962951_dffce&#39;; // Replace with your Manychat ID</pre><pre>// Initialize Manychat Pixel<br>const initManychatPixel = () =&gt; {<br>  return new Promise((resolve, reject) =&gt; {<br>    // Check if MC_PIXEL is already defined<br>    if (typeof window.MC_PIXEL !== &#39;undefined&#39;) {<br>      resolve();<br>      return;<br>    }</pre><pre>    // Load the Manychat scripts<br>    const script1 = document.createElement(&#39;script&#39;);<br>    script1.src = `//widget.manychat.com/${MANYCHAT_PAGE_ID}.js`;<br>    script1.defer = true;</pre><pre>    const script2 = document.createElement(&#39;script&#39;);<br>    script2.src = &#39;https://mccdn.me/assets/js/widget.js&#39;;<br>    script2.defer = true;</pre><pre>    // Add error handlers for both scripts<br>    script1.onerror = () =&gt; reject(new Error(&#39;Failed to load first Manychat script&#39;));<br>    script2.onerror = () =&gt; reject(new Error(&#39;Failed to load second Manychat script&#39;));</pre><pre>    document.head.appendChild(script1);<br>    document.head.appendChild(script2);</pre><pre>    // Check for MC_PIXEL becoming available<br>    const checkMCPixel = setInterval(() =&gt; {<br>      if (typeof window.MC_PIXEL !== &#39;undefined&#39;) {<br>        clearInterval(checkMCPixel);<br>        clearTimeout(timeout);<br>        resolve();<br>      }<br>    }, 100);</pre><pre>    // Set a timeout to prevent infinite waiting<br>    const timeout = setTimeout(() =&gt; {<br>      clearInterval(checkMCPixel);<br>      reject(new Error(&#39;Timed out waiting for MC_PIXEL to initialize&#39;));<br>    }, 10000);<br>  });<br>};</pre><pre>// Check for MCP token in URL or cookie<br>const checkMCPTokenValidation = async () =&gt; {<br>  try {<br>    // First check URL for mcp_token<br>    const urlParams = new URLSearchParams(window.location.search);<br>    const mcpToken = urlParams.get(&#39;mcp_token&#39;);<br>    <br>    if (mcpToken) {<br>      // If token exists in URL, store it in a cookie for 28 days<br>      try {<br>        await browser.cookie.set(&#39;manychat_mcp_token&#39;, &#39;true&#39;, { <br>          secure: true,<br>          sameSite: &#39;lax&#39;,<br>          maxAge: 60 * 60 * 24 * 28 // 28 days in seconds<br>        });<br>      } catch (error) {<br>        console.error(&#39;Manychat Pixel: Error setting cookie&#39;, error);<br>      }<br>      return true;<br>    }<br>    <br>    // If no token in URL, check if we have a stored cookie<br>    const storedToken = await browser.cookie.get(&#39;manychat_mcp_token&#39;);<br>    return storedToken === &#39;true&#39;;<br>  } catch (error) {<br>    console.error(&#39;Manychat Pixel: Error during token validation&#39;, error);<br>    return false;<br>  }<br>};</pre><pre>// Safely extract data from Shopify events<br>const safeExtract = (obj, path, defaultValue = null) =&gt; {<br>  try {<br>    return path.split(&#39;.&#39;).reduce((o, k) =&gt; (o || {})[k], obj) || defaultValue;<br>  } catch (error) {<br>    return defaultValue;<br>  }<br>};</pre><pre>// Helper function to fire Manychat events<br>const fireManychatEvent = async (eventName, eventData) =&gt; {<br>  // Make sure MC_PIXEL is defined<br>  if (typeof window.MC_PIXEL === &#39;undefined&#39;) {<br>    console.error(&#39;Manychat Pixel: MC_PIXEL is not defined&#39;);<br>    return;<br>  }<br>  <br>  // Check if user has a valid MCP token<br>  const isValidatedUser = await checkMCPTokenValidation();<br>  <br>  if (!isValidatedUser) {<br>    // Skip silently for production - user doesn&#39;t have a token<br>    return;<br>  }</pre><pre>  try {<br>    if (eventData &amp;&amp; eventData.value &amp;&amp; !isNaN(parseFloat(eventData.value))) {<br>      window.MC_PIXEL.fireLogMoneyEvent(<br>        eventName, <br>        parseFloat(eventData.value), <br>        eventData.currency || &#39;USD&#39;<br>      );<br>    } else {<br>      window.MC_PIXEL.fireLogConversionEvent(eventName);<br>    }<br>  } catch (error) {<br>    console.error(&#39;Manychat Pixel: Error firing event&#39;, error);<br>  }<br>};</pre><pre>// Function to handle Shopify events<br>const handleShopifyEvent = async (event) =&gt; {<br>  try {<br>    if (!event || !event.name || !event.data) {<br>      return;<br>    }</pre><pre>    switch(event.name) {<br>      case &#39;page_viewed&#39;:<br>        const pageType = safeExtract(event, &#39;data.page.pageType&#39;, &#39;unknown&#39;);<br>        await fireManychatEvent(&#39;page_viewed&#39;, { page: pageType });<br>        break;<br>        <br>      case &#39;product_added_to_cart&#39;:<br>        const productTitle = safeExtract(event, &#39;data.cartLine.merchandise.product.title&#39;, &#39;&#39;);<br>        const productVariant = safeExtract(event, &#39;data.cartLine.merchandise.title&#39;, &#39;&#39;);<br>        const cartValue = safeExtract(event, &#39;data.cartLine.cost.totalAmount.amount&#39;, 0);<br>        const currency = safeExtract(event, &#39;data.cartLine.cost.totalAmount.currencyCode&#39;, &#39;USD&#39;);<br>        <br>        if (productTitle) {<br>          await fireManychatEvent(&#39;product_added_to_cart&#39;, {<br>            value: parseFloat(cartValue),<br>            currency: currency,<br>            productName: productTitle,<br>            variant: productVariant<br>          });<br>        }<br>        break;<br>        <br>      case &#39;checkout_completed&#39;:<br>        const totalPrice = safeExtract(event, &#39;data.checkout.totalPrice.amount&#39;, 0);<br>        const checkoutCurrency = safeExtract(event, &#39;data.checkout.currencyCode&#39;, &#39;USD&#39;);<br>        const orderId = safeExtract(event, &#39;data.checkout.order.id&#39;, &#39;&#39;);<br>        <br>        await fireManychatEvent(&#39;purchase&#39;, {<br>          value: parseFloat(totalPrice),<br>          currency: checkoutCurrency,<br>          orderId: orderId<br>        });<br>        break;<br>        <br>      case &#39;collection_viewed&#39;:<br>        const collectionId = safeExtract(event, &#39;data.collection.id&#39;, &#39;&#39;);<br>        const collectionTitle = safeExtract(event, &#39;data.collection.title&#39;, &#39;&#39;);<br>        <br>        if (collectionId) {<br>          await fireManychatEvent(&#39;collection_viewed&#39;, { <br>            collectionId: collectionId,<br>            collectionTitle: collectionTitle<br>          });<br>        }<br>        break;<br>        <br>      case &#39;search_submitted&#39;:<br>        const query = safeExtract(event, &#39;data.searchResult.query&#39;, &#39;&#39;);<br>        <br>        if (query) {<br>          await fireManychatEvent(&#39;search_submitted&#39;, { <br>            searchTerm: query <br>          });<br>        }<br>        break;<br>        <br>      // Support for other standard events<br>      case &#39;product_viewed&#39;:<br>        const viewedProductTitle = safeExtract(event, &#39;data.product.title&#39;, &#39;&#39;);<br>        const viewedProductPrice = safeExtract(event, &#39;data.product.price.amount&#39;, 0);<br>        const viewedProductCurrency = safeExtract(event, &#39;data.product.price.currencyCode&#39;, &#39;USD&#39;);<br>        <br>        if (viewedProductTitle) {<br>          await fireManychatEvent(&#39;product_viewed&#39;, {<br>            value: parseFloat(viewedProductPrice),<br>            currency: viewedProductCurrency,<br>            productName: viewedProductTitle<br>          });<br>        }<br>        break;<br>        <br>      case &#39;checkout_started&#39;:<br>        const checkoutStartValue = safeExtract(event, &#39;data.checkout.totalPrice.amount&#39;, 0);<br>        const checkoutStartCurrency = safeExtract(event, &#39;data.checkout.currencyCode&#39;, &#39;USD&#39;);<br>        <br>        await fireManychatEvent(&#39;checkout_started&#39;, {<br>          value: parseFloat(checkoutStartValue),<br>          currency: checkoutStartCurrency<br>        });<br>        break;<br>        <br>      case &#39;payment_info_submitted&#39;:<br>        await fireManychatEvent(&#39;payment_info_submitted&#39;, {});<br>        break;<br>    }<br>  } catch (error) {<br>    console.error(&#39;Manychat Pixel: Error handling event&#39;, error);<br>  }<br>};</pre><pre>// Initialize and run<br>(async () =&gt; {<br>  try {<br>    await initManychatPixel();<br>    <br>    // Subscribe to all standard events<br>    analytics.subscribe(&#39;all_standard_events&#39;, handleShopifyEvent);<br>    <br>    // Initial token validation<br>    await checkMCPTokenValidation();<br>  } catch (error) {<br>    console.error(&#39;Manychat Pixel: Initialization failed&#39;, error);<br>  }<br>})();</pre><p>Make sure to replace &#39;962951_dffce&#39; with your own Manychat Page ID.</p><h3>Why This Matters</h3><p>For businesses operating across multiple platforms, this attribution gap was leading to underreported conversion rates from Manychat campaigns. Marketing decisions were being made on incomplete data, often undervaluing the impact of chat marketing.</p><p>With proper cross-platform tracking:</p><ul><li>You can accurately measure which chat flows are driving purchases</li><li>Your conversion metrics reflect the full customer journey</li><li>You can optimize spend based on complete attribution data</li><li>Segmentation and follow-up flows can be triggered based on purchasing behavior</li></ul><h3>Setting Everything Up</h3><ol><li>Add the UTM forwarding script to your Webflow site</li><li>Implement the custom Manychat Pixel in Shopify (Settings &gt; Customer events)</li><li>Update the Manychat Page ID in the code to match your account</li><li>Make sure your Manychat flows include links to your Webflow pages (they’ll automatically include the mcp_token)</li></ol><p>That’s it! Now your customer’s journey will be tracked properly across all platforms, and you’ll get accurate conversion data in your Manychat dashboard.</p><h3>Key Benefits</h3><p>This implementation provides two major advantages:</p><ol><li><strong>Complete Attribution</strong>: Even when customers navigate through multiple platforms before purchasing, the original Manychat source gets proper credit.</li><li><strong>Clean Data</strong>: The system only tracks events for users who actually came from Manychat, preventing your analytics from getting polluted with unrelated conversions.</li></ol><p>If you implement this in your marketing stack, I’d love to hear how it works for you. And if you have any suggestions for improvements, feel free to reach out.</p><p><em>Looking to improve your marketing attribution across multiple platforms? Let’s connect and discuss how this solution might help your specific setup.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bf923e9fb5b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Free Batch Audio Processing: A DIY script for the frustrated creative]]></title>
            <link>https://medium.com/@towersjavin/free-batch-audio-processing-a-diy-script-for-the-frustrated-creative-595af1fa1428?source=rss-cfebd57ca9b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/595af1fa1428</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Javin Towers]]></dc:creator>
            <pubDate>Mon, 23 Oct 2023 18:49:32 GMT</pubDate>
            <atom:updated>2023-10-23T18:49:32.247Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ioPoc6FQDgrZm0BypxERyw.jpeg" /></figure><p>Hey folks! 👋 Today, I’m excited to share a little project that’s become a real game-changer for my workflow. If you’ve ever found yourself struggling with limited options in free audio tools and needed a quick, reliable solution for compressing audio files, then you’ll love this tutorial on how to set up your own custom compressor.</p><h3>Why Did I Start This Project?</h3><p>It all began when I was working with a client who needed to compress a list of bulk audio files to make them web-friendly for Shopify.</p><p>After scouring the internet for a free and efficient tool, I realized that the options were pretty limited. That&#39;s why I decided to create my own tool. Not only would it address my immediate needs, but it could also be customized to handle any future requirements.</p><h3>What Does This Tool Do?</h3><p>In essence, my tool compresses audio files. Simple, right? But here’s the cool part: it’s entirely customizable. You can set different bitrates and even choose between two compression programs, depending on your needs:</p><ol><li><strong>High-Efficiency Compression:</strong> When you need that file as small as possible and are willing to compromise on quality.</li><li><strong>Quality Balanced Compression:</strong> When you need to strike a good balance between file size and audio quality.</li></ol><p>And guess what? You can process as many files as you want!</p><h3>How Can You Create Your Own?</h3><p>Alright, let’s dive into the nitty-gritty. I promise to keep this as straightforward as possible. Ready? Let’s go!</p><h3>Step 1: Setting Up Your Environment</h3><p>First, you’ll need to have Python installed on your machine. If it’s not already, <a href="https://www.python.org/downloads/">here’s a handy guide</a> to get you started.</p><p>Next, you’ll need to install Flask, a micro web framework for Python, and Pydub, a nifty library to work with audio files. Open your terminal and run:</p><pre>pip install Flask pydub</pre><h3>Step 2: Creating the File Structure</h3><p>Here’s a quick script you can run in your terminal to set up the necessary file structure:</p><pre>mkdir -p ~/Documents/Applications/Audio\ Compressor\ Tools<br>cd ~/Documents/Applications/Audio\ Compressor\ Tools<br>touch app.py<br>mkdir templates<br>touch templates/upload.html</pre><p>This script creates a directory for your project, navigates into it, and creates the necessary files for our application.</p><h3>Step 3: Building the Application</h3><p>Now, the fun part begins! You’re going to code your tool. I’ve included the entire app.py and upload.html files down below. Feel free to customize them as much as you want!</p><h3>Step 4: Running the Application</h3><p>To run the application, you’ll execute the following in your terminal in the main directory:</p><pre>python3 app.py</pre><p>This command runs your application, and you can access it by visiting http://localhost:8080 in your web browser.</p><h3>Step 5: Creating an AppleScript for Convenience</h3><p>If you’re like me and adore convenience, this step is for you. You’ll create an AppleScript that runs your application with a single click and opens it in your default web browser.</p><ul><li>Open Apple’s Script Editor.</li><li>Paste in the AppleScript below.</li></ul><pre>tell application &quot;Terminal&quot;<br>    activate<br>    do script &quot;cd /Users/javintowers/Documents/Applications/Audio\\ Compressor\\ Tools; python3 app.py&quot;<br>end tell<br><br>delay 5 -- Wait for a few seconds for the server to start<br><br>tell application &quot;Safari&quot; -- You can replace this with &quot;Google Chrome&quot;, &quot;Firefox&quot;, etc.<br>    activate<br>    open location &quot;http://localhost:8080&quot;<br>end tell</pre><ul><li>Replace “<strong>/Users/javintowers/Documents/Applications/Audio\\ Compressor\\ Tools</strong>” with your own file path.</li><li>Go to File&gt;Export. Save it as an application.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*RaKEOC4NEKFtujwcpKzzaA.png" /></figure><ul><li>Go to the Application folder and drag the app to your doc.</li></ul><p>Don’t forget, you can also customize the app icon to something snazzy that makes your dock look cool!</p><ul><li>Go to the Application folder</li><li>Right Click on the app and select “Info”</li><li>Now drag a new icon with the file extension .icns into the top left corner of the info panel.</li><li>Done.</li></ul><h3>Final Thoughts</h3><p>Building this audio compressor tool was both a challenge and a delight. It solved a significant problem for me and my client, and I learned a ton along the way. Plus, now I have a custom tool that I can rely on, without fretting about the limitations of free online tools.</p><p>If you’ve ever thought about building a tool or application for yourself but hesitated, I’m here to tell you: go for it! It’s not just about the result; the journey itself is incredibly rewarding.</p><p>Happy coding, everyone!</p><p><em>Thanks for reading! If you have any questions, suggestions, or thoughts, feel free to drop a comment below. Let’s learn and grow together!</em></p><p>App.py</p><pre>from flask import Flask, request, render_template, jsonify, url_for<br>from werkzeug.utils import secure_filename<br>import os<br>from pydub import AudioSegment<br>import tempfile<br>import shutil<br>import zipfile<br><br>app = Flask(__name__, static_folder=&#39;static&#39;)<br><br># Utility function to compress audio<br>def compress_audio(file, output_folder, program, bitrate=&quot;64k&quot;, quality=&quot;4&quot;):<br>    # Your compression logic goes here<br>    format = &quot;mp3&quot;<br>    audio = AudioSegment.from_file(file)<br><br>    new_file_path = os.path.join(output_folder, f&quot;compressed_{secure_filename(file.filename)}&quot;)<br><br>    if program == 1:<br>        # Program 1 logic<br>        bitrate = bitrate or &quot;64k&quot;<br>        audio.export(new_file_path, format=format, bitrate=bitrate)<br>    elif program == 2:<br>        # Program 2 logic<br>        quality = quality or &quot;4&quot;<br>        if audio.channels &gt; 1:<br>            audio = audio.set_channels(1)<br>        if audio.frame_rate &gt; 32000:<br>            audio = audio.set_frame_rate(32000)<br>        audio.export(new_file_path, format=format, parameters=[&quot;-q:a&quot;, quality])<br>    else:<br>        return &quot;Invalid program option&quot;, 400<br><br>    return new_file_path<br><br>@app.route(&#39;/compress&#39;, methods=[&#39;POST&#39;])<br>def compress_files():<br>    # Check if the post request has the file part<br>    if &#39;files&#39; not in request.files:<br>        return jsonify({&#39;error&#39;: &#39;No file part&#39;}), 400<br><br>    files = request.files.getlist(&#39;files&#39;)<br>    program = request.form.get(&#39;program&#39;)<br>    bitrate = request.form.get(&#39;bitrate&#39;)<br>    quality = request.form.get(&#39;quality&#39;)<br><br>    if not files or not program:<br>        return jsonify({&#39;error&#39;: &#39;No files or program selected&#39;}), 400<br><br>    # Create a temporary directory<br>    temp_dir = tempfile.mkdtemp()<br>    output_files = []<br><br>    try:<br>        for file in files:<br>            if file.filename == &#39;&#39;:<br>                continue<br>            output_file = compress_audio(file, temp_dir, int(program), bitrate, quality)<br>            output_files.append(output_file)<br><br>        # Ensure the static directory exists<br>        static_dir = os.path.join(app.root_path, &#39;static&#39;)<br>        os.makedirs(static_dir, exist_ok=True)<br><br>        # Create a zip file with all compressed files<br>        zip_filename = os.path.join(static_dir, &#39;compressed_audio.zip&#39;)<br>        zipf = zipfile.ZipFile(zip_filename, &#39;w&#39;, zipfile.ZIP_DEFLATED)<br><br>        # Add files to the zip file<br>        for file in output_files:<br>            zipf.write(file, os.path.basename(file))<br>        zipf.close()<br><br>        return jsonify({&#39;success&#39;: &#39;Files compressed&#39;, &#39;download_url&#39;: url_for(&#39;static&#39;, filename=&#39;compressed_audio.zip&#39;)})<br><br>    finally:<br>        # Clean up the temporary directory<br>        shutil.rmtree(temp_dir)<br><br>@app.route(&#39;/&#39;)<br>def upload_file():<br>    return render_template(&#39;upload.html&#39;)<br><br>if __name__ == &#39;__main__&#39;:<br>    app.run(host=&#39;0.0.0.0&#39;, port=8080, debug=True)</pre><p>upload.html</p><pre>&lt;!doctype html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>    &lt;title&gt;Audio Compressor&lt;/title&gt;<br>    &lt;link href=&quot;https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css&quot; rel=&quot;stylesheet&quot;&gt;<br>    &lt;script src=&quot;https://code.jquery.com/jquery-3.6.0.min.js&quot;&gt;&lt;/script&gt;<br>    &lt;style&gt;<br>           .hidden { display: none; }<br>    #loader {<br>        border: 16px solid #f3f3f3;<br>        border-top: 16px solid #3498db;<br>        border-radius: 50%;<br>        width: 120px;<br>        height: 120px;<br>        animation: spin 2s linear infinite;<br>        margin: auto;<br>    }<br>    @keyframes spin {<br>        0% { transform: rotate(0deg); }<br>        100% { transform: rotate(360deg); }<br>    }<br><br>    .file-item {<br>        background: #f3f3f3;<br>        border: 1px solid #e2e2e2;<br>        padding: 10px;<br>        margin-bottom: 10px;<br>        border-radius: 4px;<br>        display: flex;<br>        justify-content: space-between;<br>        align-items: center;<br>    }<br>    &lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body class=&quot;bg-gray-100 font-sans leading-normal tracking-normal&quot;&gt;<br>    &lt;div class=&quot;container mx-auto my-5 p-8 bg-white rounded shadow-md&quot;&gt;<br>        &lt;h1 class=&quot;text-2xl mb-5&quot;&gt;Audio Compressor&lt;/h1&gt;<br>        &lt;p&gt;Select audio files to compress using one of the available programs:&lt;/p&gt;<br>        &lt;ul&gt;<br>            &lt;li&gt;&lt;strong&gt;High Efficiency Compression:&lt;/strong&gt; This mode uses a lower bitrate (e.g., 64k) for maximum compression but may reduce quality. Suitable for speech or non-music audios that don&#39;t require high fidelity.&lt;/li&gt;<br>            &lt;li&gt;&lt;strong&gt;Quality Balanced Compression:&lt;/strong&gt; This mode offers a balance between file size and audio quality, using variable bitrate encoding. The quality setting scales from 0 (highest) to 9 (lowest); a typical setting is around 4 for a good balance.&lt;/li&gt;<br>        &lt;/ul&gt;<br><br>        &lt;form method=&quot;post&quot; enctype=&quot;multipart/form-data&quot; id=&quot;upload-form&quot; class=&quot;mt-5&quot;&gt;<br>            &lt;div class=&quot;flex flex-col space-y-4&quot;&gt;<br>                &lt;input type=&quot;file&quot; id=&quot;file&quot; name=&quot;file&quot; multiple class=&quot;border-2 p-2 rounded&quot;&gt;<br>                &lt;select name=&quot;program&quot; id=&quot;program&quot; class=&quot;border-2 p-2 rounded&quot;&gt;<br>                    &lt;option value=&quot;1&quot;&gt;High Efficiency Compression&lt;/option&gt;<br>                    &lt;option value=&quot;2&quot;&gt;Quality Balanced Compression&lt;/option&gt;<br>                &lt;/select&gt;<br>                &lt;div id=&quot;program-options&quot;&gt;<br>                    &lt;div id=&quot;program-1-options&quot; class=&quot;hidden space-y-4&quot;&gt;<br>                        &lt;label for=&quot;bitrate&quot;&gt;Set Bitrate for High Efficiency Compression:&lt;/label&gt;<br>                        &lt;input type=&quot;text&quot; id=&quot;bitrate&quot; name=&quot;bitrate&quot; placeholder=&quot;Enter bitrate, e.g., 64k&quot; class=&quot;border-2 p-2 rounded&quot;&gt;<br>                    &lt;/div&gt;<br>                    &lt;div id=&quot;program-2-options&quot; class=&quot;hidden space-y-4&quot;&gt;<br>                        &lt;label for=&quot;quality&quot;&gt;Set Quality for Quality Balanced Compression:&lt;/label&gt;<br>                        &lt;input type=&quot;text&quot; id=&quot;quality&quot; name=&quot;quality&quot; placeholder=&quot;Enter quality level, e.g., 4&quot; class=&quot;border-2 p-2 rounded&quot;&gt;<br>                    &lt;/div&gt;<br>                &lt;/div&gt;<br>                &lt;input type=&quot;submit&quot; value=&quot;Upload and Compress&quot; class=&quot;bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded&quot;&gt;<br>            &lt;/div&gt;<br>        &lt;/form&gt;<br>        &lt;div id=&quot;file-list&quot; class=&quot;mt-5&quot;&gt;&lt;/div&gt;<br>        &lt;div id=&quot;loader&quot; class=&quot;loader hidden&quot;&gt;&lt;/div&gt;<br>    &lt;/div&gt;<br><br>    &lt;script&gt;<br>        $(document).ready(function(){<br>            function updateProgramOptions() {<br>                var selectedProgram = $(&#39;#program&#39;).val();<br>                if(selectedProgram == &#39;1&#39;) {<br>                    $(&#39;#program-1-options&#39;).removeClass(&#39;hidden&#39;);<br>                    $(&#39;#program-2-options&#39;).addClass(&#39;hidden&#39;);<br>                } else if(selectedProgram == &#39;2&#39;) {<br>                    $(&#39;#program-1-options&#39;).addClass(&#39;hidden&#39;);<br>                    $(&#39;#program-2-options&#39;).removeClass(&#39;hidden&#39;);<br>                } else {<br>                    $(&#39;#program-1-options&#39;).addClass(&#39;hidden&#39;);<br>                    $(&#39;#program-2-options&#39;).addClass(&#39;hidden&#39;);<br>                }<br>            }<br><br>            // Call updateProgramOptions to show the relevant options on page load<br>            updateProgramOptions();<br><br>            $(&#39;#program&#39;).change(function() {<br>                updateProgramOptions();<br>            });<br><br><br>            $(&#39;#file&#39;).change(function() {<br>            $(&#39;#file-list&#39;).html(&#39;&#39;); // Clear the current file list<br>            var files = $(this)[0].files;<br><br>            for(var i = 0; i &lt; files.length; i++) {<br>                var fileSize = (files[i].size / 1024 / 1024).toFixed(2); // size in MB<br>                $(&#39;#file-list&#39;).append(<br>                    &#39;&lt;div class=&quot;file-item&quot;&gt;&#39; + <br>                        &#39;&lt;span&gt;&#39; + files[i].name + &#39;&lt;/span&gt;&#39; + <br>                        &#39;&lt;span&gt;&#39; + fileSize + &#39; MB&lt;/span&gt;&#39; + <br>                    &#39;&lt;/div&gt;&#39;<br>                ); // Append to the file list<br>            }<br>        });<br><br>            $(&#39;form&#39;).on(&#39;submit&#39;, function(event){<br>                event.preventDefault();<br>                var files = $(&#39;#file&#39;)[0].files;<br>                var program = $(&#39;#program&#39;).val();<br>                var bitrate = $(&#39;#bitrate&#39;).val();<br>                var quality = $(&#39;#quality&#39;).val();<br><br>                if(files.length === 0) {<br>                    alert(&quot;No files selected.&quot;);<br>                    return;<br>                }<br><br>                var formData = new FormData();<br>                for(var i = 0; i &lt; files.length; i++) {<br>                    formData.append(&#39;files&#39;, files[i]);<br>                }<br>                formData.append(&#39;program&#39;, program);<br>                formData.append(&#39;bitrate&#39;, bitrate);<br>                formData.append(&#39;quality&#39;, quality);<br><br>                $(&#39;#loader&#39;).removeClass(&#39;hidden&#39;);<br>                $(&#39;#file-list&#39;).html(&#39;&#39;);<br><br>                $.ajax({<br>                    type: &#39;POST&#39;,<br>                    url: &#39;/compress&#39;,<br>                    data: formData,<br>                    contentType: false,<br>                    processData: false,<br>                    success: function(response) {<br>                    $(&#39;#loader&#39;).addClass(&#39;hidden&#39;);<br>                    alert(&quot;Files compressed successfully!&quot;);<br><br>                    // Create an anchor link with download attribute and simulate click<br>                    var link = document.createElement(&#39;a&#39;);<br>                    link.href = response.download_url;<br>                    link.download = &#39;&#39;;<br>                    document.body.appendChild(link);<br>                    link.click();<br>                    document.body.removeChild(link);<br><br>                    // List the uploaded files<br>                    for(var i = 0; i &lt; files.length; i++) {<br>                        var fileSize = (files[i].size / 1024 / 1024).toFixed(2); // in MB<br>                        $(&#39;#file-list&#39;).append(&#39;&lt;p&gt;&#39; + files[i].name + &#39; - &#39; + fileSize + &#39; MB&lt;/p&gt;&#39;);<br>                    }<br>                },<br>                error: function() {<br>                    $(&#39;#loader&#39;).addClass(&#39;hidden&#39;);<br>                    alert(&quot;An error occurred.&quot;);<br>                }<br>            });<br>        });<br>    });<br>&lt;/script&gt;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=595af1fa1428" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating Webflow Forms with Klaviyo: A Simple Connection]]></title>
            <link>https://medium.com/@towersjavin/integrating-webflow-forms-with-klaviyo-a-simple-connection-af6de4f76568?source=rss-cfebd57ca9b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/af6de4f76568</guid>
            <category><![CDATA[email-marketing]]></category>
            <category><![CDATA[klaviyo-email-marketing]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[digital-marketing-tips]]></category>
            <category><![CDATA[webflow]]></category>
            <dc:creator><![CDATA[Javin Towers]]></dc:creator>
            <pubDate>Tue, 03 Oct 2023 20:58:11 GMT</pubDate>
            <atom:updated>2024-05-10T13:57:55.609Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ORMFDisIoHgr7iG0jPjU4g.jpeg" /></figure><p>What this guide can do for you:</p><ul><li><strong>Use the provided script to simplify Webflow-Klaviyo connection</strong></li><li><strong>Seamlessly send user data from Webflow forms to Klaviyo</strong></li><li><strong>Set up Webflow standard and custom embed forms to work with Klaviyo</strong></li><li><strong>Map Webflow form fields to Klaviyo attributes for accurate data flow</strong></li><li><strong>Thoroughly test your integration</strong></li></ul><p>Webflow doesn&#39;t have a great way to send information from forms made in Webflow to external services like Klaviyo.</p><p>You may have tried using the POST field in the Webflow designer but found it doesn&#39;t work. Maybe, like me, you thought of using Zapier but felt like adding another service was unnecessary.</p><p>This guide will help you send form data to Klaviyo, whether you&#39;ve built a standard Webflow or bespoke form.</p><p>Feel free to watch along.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F72PnkmUOi9w%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D72PnkmUOi9w&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F72PnkmUOi9w%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/53618071539623dd00464a29dd7a9b12/href">https://medium.com/media/53618071539623dd00464a29dd7a9b12/href</a></iframe><p>If you have a question or need help, message me. I’m happy to chat: <a href="/service/mailto:towersjavin@gmail.com">towersjavin@gmail.com</a></p><h3>Preliminary Steps</h3><p>Here, we will get the List ID and the Company ID or Public API Key</p><h4>1. Setting Up a Test List in Klaviyo</h4><p>Before you start, create a test list in Klaviyo. This list will be separate from your main audience or user list and used exclusively for testing purposes.</p><ul><li>Login to Klaviyo.</li><li>Navigate: Audience → Lists &amp; Segments.</li><li>Create a new static test list.</li></ul><p>Once you create the list, you can find the list ID by clicking on the list from the Lists &amp; Segments panel and looking at the URL.</p><p>The URL will look something like: <strong>http://www.klaviyo.com/list/TWQ4EC</strong></p><p>In this example, your list ID is: <strong>TWQ4EC</strong></p><h4>2. Finding your Klaviyo public API key</h4><p>From any signed-in page on Klaviyo, click on your profile at the bottom left of the navigation panel.</p><ul><li>Go to settings → Account → API Keys.</li><li>Copy the Public API Key and save it for later.</li></ul><p>Your public API key will look something like: <strong>9EUZR</strong></p><h3>1. Standard Webflow Form Setup</h3><p>Start by designing your Webflow form as you normally would. When you finish designing, move on to the next steps.</p><ol><li>Select the <strong>Form Block Container</strong> and add a class called<strong>Klaviyo-form</strong></li><li>Head to the <strong>Element Settings ⚙️</strong>panel.</li><li>Under the <strong>Custom Attributes</strong> section, click on &quot;+ Add New Attribute.&quot;</li><li>For the name field, enter <strong>data-klaviyo-list-id</strong>. For the value, input your specific Klaviyo list ID (<em>example:</em> <strong>TWQ4EC</strong> ). This tells the script where to send the form data within Klaviyo.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*felMEYd9n0A1vSTGff0M5Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*ESuGZ61qfcmj6haLlI5c7g.png" /><figcaption>Adding a custom attribute to the form component in Webflow</figcaption></figure><p>For instance, your form code in Webflow might look something like:</p><pre>htmlCopy code<br>&lt;form class=&quot;klaviyo-form&quot; data-klaviyo-list-id=&quot;YOUR_KLAVIYO_LIST_ID&quot;&gt;<br>   &lt;!-- Form Fields Here --&gt;<br>&lt;/form&gt;</pre><h3>Naming Input Fields Correctly in Webflow</h3><p>This is a critical step. Klaviyo attributes act as data containers; the data might not sync correctly if your Webflow input fields don’t match these attribute names. Any attributes that don’t match will be treated as custom attributes.</p><h4>Standard Klaviyo Attributes</h4><p>For clarity, it’s crucial to know which attributes are considered standard by Klaviyo. Here they are:</p><p><a href="https://developers.klaviyo.com/en/reference/create_client_profile">https://developers.klaviyo.com/en/reference/create_client_profile</a></p><ul><li><strong>email</strong>: Individual&#39;s email address.</li><li><strong>phone_number</strong>: Individual&#39;s phone number in E.164 format.</li><li><strong>external_id</strong>: A unique identifier used by customers to associate Klaviyo profiles with profiles in an external system.</li><li><strong>anonymous_id</strong>: To identify a profile using Klaviyo&#39;s web tracking.</li><li><strong>_kx</strong>: Also known as the exchange_id.</li><li><strong>first_name</strong>: Individual&#39;s first name.</li><li><strong>last_name</strong>: Individual&#39;s last name.</li><li><strong>organization</strong>: Name of the company/organization.</li><li><strong>title</strong>: Individual&#39;s job title.</li><li><strong>image</strong>: URL pointing to a profile image.</li></ul><p>The script will pick up these default attributes. See the code snippet below:</p><pre>// Define a list of all the standard attributes we expect based on the Klaviyo API documentation<br>            const standardAttributes = [<br>                &quot;email&quot;, <br>                &quot;phone_number&quot;, <br>                &quot;external_id&quot;, <br>                &quot;anonymous_id&quot;,<br>                &quot;_kx&quot;, <br>                &quot;first_name&quot;, <br>                &quot;last_name&quot;, <br>                &quot;organization&quot;,<br>                &quot;title&quot;, <br>                &quot;image&quot;<br>            ];</pre><p>Here, we make sure that the form inputs match the expected Klaviyo names.</p><p>Steps:</p><ol><li>In the Webflow designer, select the form input field you wish to set.</li><li>Navigate to the <strong>Element Settings ⚙</strong>panel.</li><li>Under the <strong>Text Field Settings</strong> section, you&#39;ll find the field name and type, such as<strong>Name </strong>or<strong> </strong><strong><em>email</em></strong></li><li>Set this name to correspond with a Klaviyo attribute. For instance, if you’re capturing emails, the input field name should be <strong>email</strong> to match Klaviyo&#39;s <strong>email</strong> attribute (see the list above).</li><li>Repeat this for all fields, ensuring names match those in Klaviyo’s attribute list.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lZWhD6GToth4Uvx1hjo1Fg.png" /></figure><p>The more accurately you align your Webflow form fields with these standard Klaviyo attributes, the smoother your integration will be. Proper mapping ensures the data flows correctly, allowing you to take advantage of Klaviyo’s marketing and analytics features.</p><blockquote><strong>Note</strong>: You can name any custom attributes not present in Klaviyo’s standard list, and the script will dynamically create custom properties assigned to the profile in Klaviyo.</blockquote><p>And that’s it. Your form is configured once you add the Klaviyo list ID, attributes, and custom properties.</p><h3>Custom Webflow Forms</h3><p>Using a custom form is just as straightforward. Follow the same steps for the standard webflow form. Below is an example of a custom form with placeholders:</p><pre>&lt;form class=&quot;klaviyo-form&quot; data-klaviyo-list-id=&quot;YOUR_KLAVIYO_LIST_ID&quot; data-name=&quot;YOUR_CUSTOM_SOURCE_NAME&quot;&gt;<br>    &lt;!-- Standard Klaviyo Attributes --&gt;<br>    &lt;input type=&quot;text&quot; name=&quot;email&quot; placeholder=&quot;Enter your email&quot;&gt;<br>    &lt;input type=&quot;text&quot; name=&quot;first_name&quot; placeholder=&quot;Enter your first name&quot;&gt;<br>    &lt;input type=&quot;text&quot; name=&quot;last_name&quot; placeholder=&quot;Enter your last name&quot;&gt;<br>    &lt;!-- ... Other standard attributes ... --&gt;<br>&lt;!-- Custom attributes for your unique needs --&gt;<br>    &lt;input type=&quot;text&quot; name=&quot;custom_attribute_1&quot; placeholder=&quot;Custom Attribute 1&quot;&gt;<br>    &lt;!-- ... Any other custom attributes ... --&gt;<br>    &lt;input type=&quot;submit&quot; value=&quot;Submit&quot;&gt;<br>&lt;/form&gt;</pre><p>Ensure to replace placeholders with your actual values.</p><h3>Implementing the Script</h3><p>The provided script ensures that when a user submits a form on a Webflow site, the data is sent to Klaviyo and stored appropriately.</p><p>The script ensures that form submissions go to Webflow forms and Klaviyo. It is also dynamic, meaning you can add any field from Klaviyo’s attributes list, along with custom properties, and the script will handle it.</p><p>To integrate the script into your Webflow project:</p><ol><li>Open the page setting and scroll to the bottom.</li><li>Paste the provided script into the <strong>Before &lt;/body&gt; tag</strong> section.</li></ol><p>You only need to edit one value in this script. You must replace the value <strong>YOUR-KLAVIYO_COMPANY_ID </strong>with the public API key. I’ve highlighted the code section in the snippet below.</p><p>Remember from up above; your public API key will look something like: <strong>T9EUZR</strong></p><p>The script will go from:</p><pre>// Execute the HTTP POST request to the Klaviyo API endpoint<br>            fetch(&#39;https://a.klaviyo.com/client/subscriptions/?company_id=YOUR_KLAVIYO_COMPANY_ID&#39;, options)</pre><p>To the following:</p><pre>// Execute the HTTP POST request to the Klaviyo API endpoint<br>            fetch(&#39;https://a.klaviyo.com/client/subscriptions/?company_id=T9EUZR&#39;, options)</pre><h3>The Full Script</h3><pre>&lt;script&gt;<br>document.addEventListener(&#39;DOMContentLoaded&#39;, function() {<br>    // Convert given phone number to the format +12345678901<br>    function formatPhoneNumber(number) {<br>        let cleaned = (&#39;&#39; + number).replace(/\D/g, &#39;&#39;);<br>        let match = cleaned.match(/^1?(\d{10})$/);<br>        if (match) {<br>            return &#39;+1&#39; + match[1];<br>        }<br>        return null;<br>    }<br><br>    const klaviyoForms = document.querySelectorAll(&#39;.klaviyo-form&#39;);<br><br>    klaviyoForms.forEach((form) =&gt; {<br>        form.addEventListener(&#39;submit&#39;, function(event) {<br>            // Always prevent the default form submission<br>            event.preventDefault();<br><br>            // Form Data Extraction<br>            const formData = new FormData(form);<br>            const attributes = {};<br>            const standardAttributes = [&quot;email&quot;, &quot;phone_number&quot;, &quot;external_id&quot;, &quot;anonymous_id&quot;, &quot;_kx&quot;, &quot;first_name&quot;, &quot;last_name&quot;, &quot;organization&quot;, &quot;title&quot;, &quot;image&quot;];<br>            const nestedObjects = {<br>                &quot;location&quot;: [&quot;address1&quot;, &quot;address2&quot;, &quot;city&quot;, &quot;country&quot;, &quot;region&quot;, &quot;zip&quot;, &quot;timezone&quot;, &quot;ip&quot;]<br>            };<br><br>            for (let [key, value] of formData.entries()) {<br>                if (standardAttributes.includes(key)) {<br>                    attributes[key] = value;<br>                } else {<br>                    let addedToNested = false;<br>                    for (const [objectName, fields] of Object.entries(nestedObjects)) {<br>                        if (fields.includes(key)) {<br>                            if (!attributes[objectName]) attributes[objectName] = {};<br>                            attributes[objectName][key] = value;<br>                            addedToNested = true;<br>                            break;<br>                        }<br>                    }<br>                    if (!addedToNested) {<br>                        if (!attributes.properties) attributes.properties = {};<br>                        attributes.properties[key] = value;<br>                    }<br>                }<br>            }<br><br>            // Phone Number Formatting<br>            if (attributes.phone_number) {<br>                attributes.phone_number = formatPhoneNumber(attributes.phone_number);<br>                if (!attributes.phone_number) {<br>                    console.error(&#39;Error: Invalid phone number format.&#39;);<br>                    let customErrorElement = form.querySelector(&#39;.custom-error&#39;);<br>                    if (customErrorElement) {<br>                        customErrorElement.textContent = &#39;Invalid phone number format. Please use a format like 123-456-7890 or 1234567890.&#39;;<br>                        customErrorElement.style.display = &#39;block&#39;;<br>                    }<br>                    return;<br>                }<br>            }<br><br>            // Klaviyo API Configuration<br>            const klaviyoListId = form.getAttribute(&quot;data-klaviyo-list-id&quot;);<br>            const options = {<br>                method: &#39;POST&#39;,<br>                headers: {<br>                    &#39;revision&#39;: &#39;2023-08-15&#39;,<br>                    &#39;content-type&#39;: &#39;application/json&#39;<br>                },<br>                body: JSON.stringify({<br>                    data: {<br>                        type: &#39;subscription&#39;,<br>                        attributes: {<br>                            custom_source: form.getAttribute(&quot;data-name&quot;),<br>                            profile: {<br>                                data: {<br>                                    type: &#39;profile&#39;,<br>                                    attributes: attributes<br>                                }<br>                            }<br>                        },<br>                        relationships: { list: { data: { type: &#39;list&#39;, id: klaviyoListId }}}<br>                    }<br>                })<br>            };<br><br>            // Klaviyo API Call<br>            fetch(&#39;https://a.klaviyo.com/client/subscriptions/?company_id=YOUR_KLAVIYO_COMPANY_ID&#39;, options)<br>            .then(response =&gt; {<br>                if (!response.ok) {<br>                    return response.json().then(err =&gt; Promise.reject(err));<br>                } else {<br>                    // Display the success message on successful submission<br>                    let customSuccessElement = form.querySelector(&#39;.custom-success&#39;);<br>                    if (customSuccessElement) customSuccessElement.style.display = &#39;block&#39;;<br>                }<br>            })<br>            .catch(err =&gt; {<br>                console.error(&#39;Error sending data to Klaviyo:&#39;, err);<br>                <br>                // Display the error message on error<br>                let customErrorElement = form.querySelector(&#39;.custom-error&#39;);<br>                if (customErrorElement) customErrorElement.style.display = &#39;block&#39;;<br>            });<br>        });<br>    });<br>});<br><br>&lt;/script&gt;</pre><h3>Testing the Integration: Making Sure Your Webflow-Klaviyo Connection Works</h3><p>Testing is one of the most crucial steps before launching any feature or integration into production. A thorough testing process ensures that you provide a seamless user experience and that your data flows correctly. In this section, we’ll walk through a comprehensive guide on how to test the script and its integration.</p><h4>Webflow Setup and Code Integration</h4><p>Design your Webflow form and implement the script as described in the previous sections.</p><p>For testing purposes, set the <strong>data-klaviyo-list-id</strong> attribute of your form to your Klaviyo test list ID.</p><pre>htmlCopy code<br>&lt;form class=&quot;klaviyo-form&quot; data-klaviyo-list-id=&quot;YOUR_KLAVIYO_TEST_LIST_ID&quot;&gt;<br>   &lt;!-- Form Fields Here --&gt;<br>&lt;/form&gt;</pre><h4>Publish to Staging</h4><p>Always test on a staging domain first. This ensures that your live audience won’t encounter potential issues. After setting up, publish your Webflow project to your staging domain.</p><h4>Test Submission with a Temporary Email</h4><ol><li>Head over to <a href="https://tempmailo.com/"><strong>TempMailo</strong></a>. This service allows you to access a temporary email inbox. It’s perfect for testing because you won’t clutter your primary email with test messages.</li><li>Copy the temporary email provided by TempMailo.</li><li>Navigate to your staging domain and fill out the form using the temporary email.</li></ol><h4>Verify the Klaviyo Opt-in Email</h4><ol><li>Return to TempMailo and refresh the page to check for new emails.</li><li>You should receive an opt-in email from Klaviyo (if you have double opt-in enabled). This confirms that the data has been sent to Klaviyo correctly and that the opt-in process works.</li></ol><h4>Additional Testing Recommendations</h4><p>While the steps above ensure basic functionality, consider these additional testing recommendations:</p><ul><li><strong>Multiple Data Points</strong>: Ensure to test all fields in your form, especially custom attributes. Verify that this data is correctly stored in Klaviyo.</li><li><strong>Error Handling</strong>: Enter incorrect data or leave mandatory fields empty. This tests how the script and integration handle errors.</li><li><strong>User Experience</strong>: Check if the user gets appropriate feedback upon form submission, whether it’s a success message or an error prompt.</li></ul><h3>Conclusion: Cleaning Up and Moving Forward</h3><p>After you’re satisfied with your testing:</p><ol><li>Replace the test list ID with your main list ID in the <strong>data-klaviyo-list-id</strong> attribute.</li><li>Publish your changes to your main domain.</li></ol><p>Remember, consistent testing is key. Every time you make significant modifications to your form or integration, rerun these tests to ensure continuous, smooth operation.</p><p>Testing might seem like an additional layer of work, but it’s an essential one. It guarantees that your users have a flawless experience, and you can be confident that your data is being managed and sent correctly.</p><p><strong>Tip</strong>: Always clear test data from Klaviyo after your testing phase to maintain a clean and accurate dataset. If you’ve added many test entries, Klaviyo allows for bulk actions to make this cleanup process faster.</p><p>If you have a question or need some help shoot me a message, i’m happy to chat: <a href="/service/mailto:towersjavin@gmail.com">towersjavin@gmail.com</a></p><h3>Wrapping Up</h3><p>Congratulations! You now have a dynamic integration between Webflow and Klaviyo. With every form submission, the data will flow effortlessly into your designated Klaviyo lists.</p><p>This script simplifies the integration process and makes it adaptable to any future modifications you might need. You’ve created a bridge that unifies your design and marketing tools.</p><p><em>If you found this tutorial helpful or have any further questions, please leave a comment or share it with your network.</em></p><h3>Deep Dive: Understanding the Core Script</h3><p>Let’s dissect the key portions of our integration script for a comprehensive understanding, aiding future customizations and troubleshooting.</p><h3>1. Document Loading Check</h3><pre>javascriptCopy code<br>// Ensure that the entire HTML document is fully loaded before executing our script<br>document.addEventListener(&#39;DOMContentLoaded&#39;, function() {</pre><p>Before executing, the script ensures that the entire HTML document is fully loaded. This is crucial as attempting to access DOM elements before they are fully loaded could result in errors or undesired behavior.</p><h3>2. Selecting Klaviyo Forms</h3><pre>javascriptCopy code<br>// Gather all forms on the webpage that have the class &#39;klaviyo-form&#39;<br>const klaviyoForms = document.querySelectorAll(&#39;.klaviyo-form&#39;);</pre><p>The script gathers all the forms with the class ‘klaviyo-form’. This allows you to designate which forms should be processed by the script, giving you control and flexibility.</p><h3>3. Form Submission Event Listener</h3><pre>javascriptCopy code<br>form.addEventListener(&#39;submit&#39;, function(event) {<br>    // Prevent the default form submission action<br>    event.preventDefault();</pre><p>For each form, an event listener is attached to intercept form submissions. The <strong>event.preventDefault()</strong> method is called to prevent the form from submitting in the traditional way, allowing the script to handle the submission.</p><h3>4. FormData Object</h3><pre>javascriptCopy code<br>// Create a new FormData object from the form to easily extract its values<br>const formData = new FormData(form);</pre><p>A <strong>FormData</strong> object is created from the form, making it simple to extract the values that users have entered into the form.</p><h3>5. Processing Form Entries</h3><pre>javascriptCopy code<br>// Iterate over each form entry to process its values<br>for (let [key, value] of formData.entries()) {</pre><p>Each form entry is iterated over to process its values. Here, key-value pairs for each form field are used to populate the <strong>attributes</strong> object, which will be sent to Klaviyo.</p><h3>6. Handling Standard and Nested Attributes</h3><pre>javascriptCopy code<br>// Check if the key is a standard attribute<br>if (standardAttributes.includes(key)) {<br>    attributes[key] = value;<br>}<br>// Loop through the nested objects to determine if the current key belongs to any<br>for (const [objectName, fields] of Object.entries(nestedObjects)) {<br>    if (fields.includes(key)) {<br>        if (!attributes[objectName]) attributes[objectName] = {};<br>        attributes[objectName][key] = value;<br>        addedToNested = true;<br>        break;<br>    }<br>}</pre><p>The script checks each form field name (<strong>key</strong>) to determine if it is a standard attribute or belongs to a nested object. If it is a standard attribute, it is added to the <strong>attributes</strong> object. If it belongs to a nested object, a corresponding nested object is created within <strong>attributes</strong>.</p><h3>7. Handling Custom Attributes</h3><pre>javascriptCopy code<br>// If the key doesn&#39;t belong to any standard or nested attributes, consider it a custom attribute<br>if (!addedToNested) {<br>    if (!attributes.properties) attributes.properties = {};<br>    attributes.properties[key] = value;<br>}</pre><p>If the form field does not match any standard or nested attributes, it is considered a custom attribute and is added under the <strong>properties</strong> object within <strong>attributes</strong>.</p><h3>8. Klaviyo API Request</h3><pre>javascriptCopy code<br>// Construct the HTTP request options, including headers and body payload<br>const options = {<br>    method: &#39;POST&#39;,<br>    headers: {<br>        &#39;revision&#39;: &#39;2023-08-15&#39;,<br>        &#39;content-type&#39;: &#39;application/json&#39;<br>    },<br>    body: JSON.stringify({<br>        data: {<br>            type: &#39;subscription&#39;,<br>            attributes: {<br>                custom_source: form.getAttribute(&quot;data-name&quot;),<br>                profile: {<br>                    data: {<br>                        type: &#39;profile&#39;,<br>                        attributes: attributes<br>                    }<br>                }<br>            },<br>            relationships: { list: { data: { type: &#39;list&#39;, id: klaviyoListId }}}<br>        }<br>    })<br>};<br>// Execute the HTTP POST request to the Klaviyo API endpoint<br>fetch(&#39;&lt;https://a.klaviyo.com/client/subscriptions/?company_id=T9EUXT&gt;&#39;, options)</pre><p>A HTTP POST request is constructed and executed to send the form data to Klaviyo. This section includes the <strong>klaviyoListId</strong> and other attributes in its payload to ensure the data is associated with the correct Klaviyo list and profile.</p><h3>9. Handling Response and Errors</h3><pre>javascriptCopy code<br>.then(response =&gt; {<br>    // If the request was successful, display a success message<br>    if (response.ok &amp;&amp; response.status === 202) {<br>        form.nextElementSibling.style.display = &#39;block&#39;;<br>        form.nextElementSibling.textContent = &#39;Thanks, be on the lookout for info about our community!&#39;;<br>    } else {<br>        // If there was an error with the request, extract the error details from the response<br>        return response.json().then(err =&gt; Promise.reject(err));<br>    }<br>})<br>.catch(err =&gt; {<br>    // Handle any exceptions or errors that occurred during the fetch operation<br>    console.error(&#39;Error:&#39;, err);<br>    form.nextElementSibling.nextElementSibling.style.display = &#39;block&#39;;<br>    form.nextElementSibling.nextElementSibling.textContent = &#39;Oops! Something went wrong while submitting the form.&#39;;<br>});</pre><p>Lastly, the script handles the API response. On a successful request, a success message is displayed to the user. If an error occurs during the fetch operation, the error is logged to the console, and an error message is shown to the user.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af6de4f76568" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>