# Abandoned Cart Recovery

### Set Up Wix Automation

{% embed url="<https://youtu.be/L_sOB2vNBck>" %}

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:

{% code title="" overflow="wrap" lineNumbers="true" %}

```javascript
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');

    // 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
};

```

{% endcode %}

{% hint style="info" %}
**Note:🔧 Changes to Make After Copy-Pasting the Code**

1. **Update the Secret Name**

In this line:

```js
const bearerToken = await elevatedGetSecretValue('MERCURI_MESSAGING_API_KEY');
```

replace `'MERCURI_MESSAGING_API_KEY'` with the **Secret Name** you created in **Wix Secret Manager**.<br>

2. **Add Your Phone Number ID**

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

3. **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.***](https://docs.mercuri.cx/features/introduction-mercuri-api/faqs)

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

### &#x20;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.
