How to Send WhatsApp Messages via Mercuri API in Wix Automation

This guide explains how to use the Mercuri API to send WhatsApp messages through Wix Automations.

1. Prepare Your API Token

  1. Go to API Management in Mercuri Dashboard and click on Create token.

  1. Now, enter the description and expiration duration of the API token and then click on Create Token.

  1. After creating the token, copy the token from the API Token Management dashboard.

  2. Open your Wix DashboardDeveloper ToolsSecrets Manager.

  1. Click on Add Secret, paste your Mercuri API token in the Value field, and assign a Secret Name (for example: MERCURI_MESSAGING_API_KEY). Keep this name handy, as you will need to use the same Secret Name in your Velo code in the following steps.

Why use Secret Manager in WIX?

Easy maintenance: If the token expires or needs rotation, you only need to update it in Secrets Manager. You do not have to modify every Velo code file where the token is used.

Centralized management: All Velo code actions can access the same token consistently, reducing errors.

2. Set Up Wix Automation

  1. Go to Automations in the Wix Dashboard and then click on Create Automation.

  2. Select the automation you want to trigger (e.g., Cart Abandonment)

  3. Add a Velo Code Action and add a .js file containing the following code:

import { secrets } from 'wix-secrets-backend.v2';
import { elevate } from 'wix-auth';
import { fetch } from 'wix-fetch';

// Create elevated versions of secrets functions
const elevatedGetSecretValue = elevate(secrets.getSecretValue);

/**
 * Autocomplete function declaration, do not delete
 * @param {import('./__schema__.js').Payload} options
 */
export const invoke = async ({ payload }) => {
  try {
    // Get bearer token securely with elevation
    const bearerToken = await elevatedGetSecretValue('MERCURI_MESSAGING_API_KEY');
    console.log("Bearer Token",bearerToken)
    // Extract contact data
    const firstName = payload.contact?.name?.first || '';
    const lastName = payload.contact?.name?.last || '';
    const recipient = payload.contact?.phone || '';

    if (!recipient) {
      console.error('Recipient phone number missing.');
      return {};
    }

    const apiPayload = {
      phoneNumberId: "xxxxxxxxxxxxxxxxxxx",
      channel: "whatsapp",
      recipient: recipient,
      message: {
        type: "template",
        template: {
          templateId: "xxxxxxxxxxxxxxxxxxx",
          parameters: [
            {
              firstName: firstName,
              lastName: lastName
            }
          ]
        }
      },
      saveToInbox: true
    };

    // Call Mercuri API
    const response = await fetch('https://api.mercuri.cx/v1/send_message', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${bearerToken}`
      },
      body: JSON.stringify(apiPayload)
    });

    if (!response.ok) {
      const errorMsg = await response.text();
      console.error(`Mercuri API error: ${response.status} - ${errorMsg}`);
    } else {
      const respData = await response.json();
      console.log('Message sent successfully:', respData);
    }
  } catch (error) {
    console.error('Error in invoke:', error);
  }

  return {};  // Required empty return object
};




Note:🔧 Changes to Make After Copy-Pasting the Code

  1. Update the Secret Name

In this line:

const bearerToken = await elevatedGetSecretValue('MERCURI_MESSAGING_API_KEY');

replace 'MERCURI_MESSAGING_API_KEY' with the Secret Name you created in Wix Secret Manager.

  1. Add Your Phone Number ID

  • Replace "xxxxxxxxxxxxxxxxxxx" corresponding to phoneNumberId in the code with the Phone Number ID you copied from the Mercuri Dashboard.

  1. Add Your Template ID

  • Replace "xxxxxxxxxxxxxxxxxxx" corresponding to templateId with the Template ID you copied from the Mercuri Dashboard.

Please click on this link to view the instructions for locating the Phone Number ID and Template ID.

The parameters array will automatically map values from the Wix automation payload to your template fields, such as firstName, lastName, and recipient.

3. Final Steps

  1. After uploading the Velo code, save your changes.

  2. Activate the automation in Wix.

  3. Optionally, test with a sample contact to ensure the messages are sent correctly.

Once these steps are completed, you have successfully set up Wix Automation to send WhatsApp messages using the Mercuri API.

Last updated