Connect button to Shopify API

Connect button to Shopify API

ww04
New Member
5 0 0

I'm developing a notify-me button for sold out products for my shopify store. However all my knowledge & experience is within the shopify frontend, i simply have no clue how the backend works. What i have done is created a button that shows below the atc-button on sold out product variants where the customer can then input their e-mail adress and then click notify me. 


Skärmbild 2025-01-21 162236.pngSkärmbild 2025-01-21 162252.pngSkärmbild 2025-01-21 162316.png

What i now want it to do is when the form is submitted with an email and the notify me button is clicked = Create a customer for that email and give it the tags "Notify-me" as well as a tag "{{product_id}}" of the sold out variants product id. Or if a customer already exists with that email simply add the tags to the customer. What i can do then is set up an email automation within the shopify flow app to send out a notification when the product is back in stock and remove both tags. By adding the "Notify-me" tag i can easily take a look at all the customers waiting to be notified. 

However as i understand this must be done through the shopify backend. Please let me know if you have any useful information that could help me get this done!

Below i have pasted the notify-me buttons snippet code that i render through the main-product.liquid file using: {% render 'ss-notify-me-button', product: product, variant: product.selected_or_first_available_variant %}

<div 
  class="notify-me-button-wrapper" 
  style="display: none; margin-top: -2rem; margin-bottom: 2.5rem; text-align: center; max-width: 440px;"
>
  <button 
    type="button" 
    class="button button--secondary notify-me-trigger notify-me-button"
    onclick="openNotifyMePopup()"
  >
    {%- if shop.locale == 'sv' -%}
    Meddela mig ✉️
    {%- else -%}
    Notify Me ✉️
    {%- endif -%}
  </button>
</div>



<style>
  .notify-me-button {
    background-color: #000000;
    width: 100%;
    font-size: 15px;
    color: #FFFFFF;
    cursor: pointer;
    transition: background-color 0.5s ease;
    padding: 0;
  }
  .notify-me-button:hover {
    background-color: #404040;
  }
  .notify-me-button::after {
  box-shadow: none !important;
}

  .notify-me-button[data-state="notified"] {
  background-color: #306452;
  cursor: not-allowed;
  opacity: 1;
}
.notify-me-button[data-state="notified"]:hover {
  background-color: #306452;
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function () {
  const notifyMeWrapper = document.querySelector('.notify-me-button-wrapper');
  const variantSelects = document.querySelector('variant-selects');

  if (!notifyMeWrapper || !variantSelects) return;

  /**
   * Function to update the Notify Me button's visibility based on the selected variant's availability.
   * @param {Object} variant - The selected variant object.
   */
  function updateNotifyMeVisibility(variant) {
    if (!variant) return;

    if (variant.available) {
      // Variant is in stock - hide the Notify Me button
      notifyMeWrapper.style.display = 'none';
    } else {
      // Variant is out of stock - show the Notify Me button
      notifyMeWrapper.style.display = 'block';
    }
  }

  /**
   * Get the currently selected variant from the DOM.
   * @returns {Object|null} - The selected variant object, or null if not found.
   */
  function getSelectedVariant() {
    const selectedVariantElement = variantSelects.querySelector('[data-selected-variant]');
    if (selectedVariantElement) {
      try {
        return JSON.parse(selectedVariantElement.innerHTML);
      } catch (e) {
        console.error('Failed to parse selected variant JSON:', e);
      }
    }
    return null;
  }

  /**
   * Handle variant change events from Shopify's PUB_SUB_EVENTS.
   * @param {Object} event - The variant change event data.
   */
  function handleVariantChange({ data: { variant } }) {
    if (!variant) return;
    updateNotifyMeVisibility(variant);
  }

  // Listen for variant change events
  subscribe(PUB_SUB_EVENTS.variantChange, handleVariantChange);

  /**
   * Handle the initial visibility of the Notify Me button on page load.
   * Use a timeout to handle potential delays in Shopify's rendering.
   */
  function initializeNotifyMeButton() {
    setTimeout(() => {
      const initialVariant = getSelectedVariant();
      if (initialVariant) {
        updateNotifyMeVisibility(initialVariant);
      } else {
        console.warn('No initial variant found on page load.');
      }
    }, 50); // Adjust timeout as needed for Shopify's rendering delay
  }

  initializeNotifyMeButton();
});
</script>


<!-- Popup Modal -->
<div 
  id="notify-me-popup" 
  class="notify-me-popup" 
  style="
    display: none; 
    position: fixed; 
    top: 25%; 
    width: 100%; 
    max-width: 440px; 
    background: #F6F6F6; 
    border: 1px solid #ccc; 
    box-shadow: 0 4px 8px rgba(0,0,0,0.1); 
    border-radius: 6px; 
    padding-left: 20px;
    padding-right: 20px;
    padding-top: 25px;
    padding-bottom: 30px;
    z-index: 1000;
  "
>
  <div 
    id="popup-content" 
    style="display: flex; flex-direction: column; gap: 20px;"
  >
    <div style="display: flex; justify-content: space-between; align-items: center;">
      <h3 style="margin: 0; font-size: 20px;">
        {%- if shop.locale == 'sv' -%}
    Produkten är tillfälligt **bleep**
  {%- else -%}
    The product is temporarily out of stock
  {%- endif -%}</h3>
      <button 
        onclick="closeNotifyMePopup()" 
        style="
          background: none; 
          border: none; 
          font-size: 25px; 
          font-weight: bold;
          line-height: 1; 
          cursor: pointer; 
          color: #999;
        "
        aria-label="Close"
      >&times;</button>
    </div>
    <form id="notify-me-form">
      <input 
        type="hidden" 
        name="product_id" 
        value="{{ product.id }}"
      >
      <input 
        type="hidden" 
        name="variant_id" 
        value="{{ variant.id }}"
      >
      <label for="notify-me-email" style="display: block; margin-bottom: 10px; font-size: 13px; color: #555;">
    {%- if shop.locale == 'sv' -%}
       Fyll i din e-postadress så meddelar vi dig när produkten är tillbaka i lager.
    {%- else -%}
       Fill in your email address, and we will notify you when the product is back in stock.
    {%- endif -%}
      </label>
      <input 
        type="email" 
        id="notify-me-email" 
        name="email" 
        placeholder="{%- if shop.locale == 'sv' -%}
       E-postadress
    {%- else -%}
       Email address
    {%- endif -%}"
        required 
        style="
          width: 100%; 
          padding: 10px; 
          font-size: 13px; 
          border: 1px solid #ccc; 
          border-radius: 6px; 
          margin-bottom: 20px;
        "
      >
      <button 
        type="submit" 
        style="
          display: block; 
          width: 100%; 
          padding: 10px; 
          background-color: #000000; 
          color: #fff; 
          border: none; 
          border-radius: 6px;
          font-size: 15px; 
          cursor: pointer;
        "
      >
    {%- if shop.locale == 'sv' -%}
      Meddela mig
    {%- else -%}
      Notify Me
    {%- endif -%}
      </button>
    </form>
  </div>
</div>

<script>
  // Open Popup
  function openNotifyMePopup() {
    const notifyMeButton = document.querySelector('.notify-me-button');

    // Prevent popup if button is in "Notified" state
    if (notifyMeButton.getAttribute('data-state') === 'notified') return;

    document.getElementById('notify-me-popup').style.display = 'block';
  }

  // Close Popup
  function closeNotifyMePopup() {
    document.getElementById('notify-me-popup').style.display = 'none';

    // Reset popup content if it was replaced with success message
    const popupContent = document.getElementById('popup-content');
    const originalContent = `
      <div style="display: flex; justify-content: space-between; align-items: center;">
        <h3 style="margin: 0; font-size: 20px;">
          {%- if shop.locale == 'sv' -%}
          Produkten är tillfälligt **bleep**
          {%- else -%}
          The product is temporarily out of stock
          {%- endif -%}
        </h3>
        <button 
          onclick="closeNotifyMePopup()" 
          style="
            background: none; 
            border: none; 
            font-size: 25px; 
            font-weight: bold;
            line-height: 1; 
            cursor: pointer; 
            color: #999;
          "
          aria-label="Close"
        >&times;</button>
      </div>
      <form id="notify-me-form">
        <input 
          type="hidden" 
          name="product_id" 
          value="{{ product.id }}"
        >
        <input 
          type="hidden" 
          name="variant_id" 
          value="{{ variant.id }}"
        >
        <label for="notify-me-email" style="display: block; margin-bottom: 10px; font-size: 13px; color: #555;">
          {%- if shop.locale == 'sv' -%}
       Fyll i din e-postadress så meddelar vi dig när produkten är tillbaka i lager.
    {%- else -%}
       Fill in your email address, and we will notify you when the product is back in stock.
    {%- endif -%}
        </label>
        <input 
          type="email" 
          id="notify-me-email" 
          name="email" 
          placeholder="{%- if shop.locale == 'sv' -%}
       E-postadress
    {%- else -%}
       Email address
    {%- endif -%}" 
          required 
          style="
            width: 100%; 
            padding: 10px; 
            font-size: 13px; 
            border: 1px solid #ccc; 
            border-radius: 6px; 
            margin-bottom: 20px;
          "
        >
        <button 
          type="submit" 
          style="
            display: block; 
            width: 100%; 
            padding: 10px; 
            background-color: #000000; 
            color: #fff; 
            border: none; 
            border-radius: 6px;
            font-size: 15px; 
            cursor: pointer;
          "
        >
          {%- if shop.locale == 'sv' -%}
            Meddela mig
          {%- else -%}
            Notify Me
          {%- endif -%}
        </button>
      </form>
    `;
    popupContent.innerHTML = originalContent;
  }

  // Handle Form Submission
  document.addEventListener('DOMContentLoaded', function () {
    const notifyMeForm = document.getElementById('notify-me-form');
    const notifyMeButton = document.querySelector('.notify-me-button');
    const popupContent = document.getElementById('popup-content');
    const popup = document.getElementById('notify-me-popup');

    if (!notifyMeForm || !notifyMeButton || !popupContent || !popup) return;

    // Set the button to "Notified" state
    function setNotifiedState(button) {
      button.textContent = `{%- if shop.locale == 'sv' -%}Du blir meddelad ✓{%- else -%}You will be notified ✓{%- endif -%}`;
      button.setAttribute('data-state', 'notified');
      button.setAttribute('disabled', 'disabled'); // Disable the button
      button.style.cursor = 'not-allowed';
    }

    // Handle the form submission
    notifyMeForm.addEventListener('submit', function (event) {
      event.preventDefault();

      const email = notifyMeForm.querySelector('[name="email"]').value;

      // Form submission success content
      popupContent.innerHTML = `
        <div style="text-align: center;">
          <h3 style="color: #000; font-size: 20px; margin-bottom: 15px;">
            {%- if shop.locale == 'sv' -%}
              Tack!
            {%- else -%}
              Thank you!
            {%- endif -%}
          </h3>
          <p style="font-size: 14px; color: #555;">
            {%- if shop.locale == 'sv' -%}
              Vi har tagit emot din förfrågan. Vi skickar ett mail till <strong>${email}</strong> när produkten är tillbaka i lager.
            {%- else -%}
              We've received your request. We will send an email to <strong>${email}</strong> when the product is back in stock.
            {%- endif -%}
          </p>
          <button 
            onclick="closeNotifyMePopup()" 
            style="
              margin-top: 20px;
              display: block; 
              width: 100%; 
              padding: 10px; 
              background-color: #000000; 
              color: #fff; 
              border: none; 
              border-radius: 6px;
              font-size: 15px; 
              cursor: pointer;
            "
          >
            {%- if shop.locale == 'sv' -%}
              Stäng
            {%- else -%}
              Close
            {%- endif -%}
          </button>
        </div>
      `;

      // Update the button to the "Notified" state
      setNotifiedState(notifyMeButton);
    });

    // Close Popup
    window.closeNotifyMePopup = function () {
      popup.style.display = 'none';
    };

    // Open Popup
    window.openNotifyMePopup = function () {
      if (notifyMeButton.getAttribute('data-state') === 'notified') return; // Prevent opening if already "Notified"
      popup.style.display = 'block';
    };
  });
</script>

 

Replies 3 (3)

hardik355
Shopify Partner
251 23 38

Hi @ww04 

Since Shopify doesn't have a built-in backend, you can either. Use a Shopify App  Install a "Back in Stock" app to handle email collection and notifications easily no backend work needed.
Please read this dicussion it will help you.

 

 

If helpful then please Like and Accept Solution.
For App Development and Design changes Hire Me.
Skype: live:hardikradadiya355
Thanks
ww04
New Member
5 0 0

Hi, thanks for your reply. However if i do not want to download an external app, is there any other way to connect the front end button to the Shopify API to make requests for certain data?

hardik355
Shopify Partner
251 23 38

Hi, i don't think so. it's possible.

If helpful then please Like and Accept Solution.
For App Development and Design changes Hire Me.
Skype: live:hardikradadiya355
Thanks