# Recuperação de Carrinho Abandonado

#### Configurar Wix Automation

1. Vá para **Automations** no **Wix Dashboard** e clique em **Create Automation**.
2. Selecione a automação que deseja acionar (ex.: Cart Abandonment).
3. Adicione uma **Velo Code Action** e inclua um arquivo .js contendo o seguinte código:

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

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

// Cria versões elevadas das funções de secrets
const elevatedGetSecretValue = elevate(secrets.getSecretValue);

/**
 * Declaração da função invoke, não deletar
 * @param {import('./__schema__.js').Payload} options
 */
export const invoke = async ({ payload }) => {
  try {
    // Obter bearer token de forma segura com elevação
    const bearerToken = await elevatedGetSecretValue('MERCURI_MESSAGING_API_KEY');

    // Extrair dados do contato
    const firstName = payload.contact?.name?.first || '';
    const lastName = payload.contact?.name?.last || '';
    const recipient = payload.contact?.phone || '';

    if (!recipient) {
      console.error('Número de telefone do destinatário ausente.');
      return {};
    }

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

    // Chamar 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(`Erro na Mercuri API: ${response.status} - ${errorMsg}`);
    } else {
      const respData = await response.json();
      console.log('Mensagem enviada com sucesso:', respData);
    }
  } catch (error) {
    console.error('Erro na função invoke:', error);
  }

  return {};  // Objeto de retorno vazio obrigatório
};
```

{% endcode %}

{% hint style="info" %}
**Nota:🔧 Alterações para fazer após copiar e colar o código**

1. **Atualize o Secret Name**

Na linha:

{% code overflow="wrap" %}

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

{% endcode %}

substitua `'MERCURI_MESSAGING_API_KEY'` pelo **Secret Name** que você criou no **Wix Secret Manager**.

2. **Adicione seu Phone Number ID**

* Substitua `"xxxxxxxxxxxxxxxxxxx"` correspondente a **phoneNumberId** no código pelo **Phone Number ID** que você copiou do Mercuri Dashboard.

3. **Adicione seu Template ID**

* Substitua `"xxxxxxxxxxxxxxxxxxx"` correspondente a **templateId** pelo **Template ID** que você copiou do Mercuri Dashboard.

***Clique neste link para ver as instruções de como localizar o Phone Number ID e o Template ID.***

O array de parameters mapeará automaticamente os valores do payload da automação Wix para os campos do seu template, como firstName, lastName e recipient.
{% endhint %}

#### Etapas Finais

1. Após enviar o código Velo, salve suas alterações.
2. Ative a automação no Wix.
3. Opcionalmente, teste com um contato de exemplo para garantir que as mensagens sejam enviadas corretamente.

Após concluir essas etapas, você terá configurado com sucesso a Wix Automation para enviar mensagens WhatsApp usando a Mercuri API.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.mercuri.cx/mercuri-docs-pt/caracteristicas/introducao-mercuri-api/casos-de-uso-como-usar-a-mercuri-api-no-wix-velo-+-automations/recuperacao-de-carrinho-abandonado.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
