# Coletar Avaliações do Google

#### Configurar Wix Automation

1. Vá para **Automations** no **Wix Dashboard** e clique em **Create Automation**.
2. Selecione a automação que deseja acionar (neste caso, **Order Placed**).
3. Em seguida, adicione um atraso de 3 dias clicando no **ícone de mais** e selecionando a opção ***Delay***.
4. Adicione uma **Velo Code Action** e inclua um arquivo .js contendo o seguinte código (dependendo do tipo de comunicação: WhatsApp ou SMS):

{% tabs %}
{% tab title="WhatsApp" %}
{% code overflow="wrap" lineNumbers="true" %}

```
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 %}
{% endtab %}

{% tab title="SMS" %}

```
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: "sms",
      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
};

```

<br>
{% endtab %}
{% endtabs %}

{% 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 ou SMS 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/coletar-avaliacoes-do-google.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.
