# Integrate Google Tag Manager with Advocate

This guide outlines the basic steps needed to leverage Google Tag Manager (GTM) to upsert users to your Advocate program. Learn more about [using Google Tag Manager with impact.com](https://integrations.impact.com/impact-brand/docs/gtm-introduction).

{% stepper %}
{% step %}

### Load the UTT into Google Tag Manager

Follow the instructions in the [standard GTM pre-integration checklist](https://integrations.impact.com/impact-brand/docs/pre-integration-checklist#step-1-the-universal-tracking-tag) for loading the UTT and setting up data layer variables.
{% endstep %}

{% step %}

### Create an Advocate firing trigger

1. In [Google Tag Manager](https://tagmanager.google.com/#/home), go to the *Workplace* screen, then select **Triggers** from the left navigation menu.
2. Select **New** to open the *Trigger Configuration* screen, then select ![](/files/eHosQ7egwdLcFW9kKpVu) **\[Edit]** to choose the base trigger.
3. Select the **Custom Event** trigger type.
4. Enter an **event name**.
5. Select the option to have the trigger fire on **All Custom Events**.
6. Select **Save** at the top right of the window.
   {% endstep %}

{% step %}

### Set up a *user upsert* tag

{% hint style="success" %}
**JWTs are required for user upsert:** To use the User Upsert tag, you must have the ability to generate a JWT on your back-end and pass it through to GTM as a variable. If you can't, then you'll need to use an [API call](https://integrations.impact.com/impact-brand/docs/integrate-google-tag-manager-with-advocate#api-upsert) to upsert the user instead.
{% endhint %}

1. In [Google Tag Manager](https://tagmanager.google.com/#/home), go to the *Workplace* screen, then select **Tags** from the left navigation menu.
2. Select **New** to open the *Tag Configuration screen*, then select **\[Edit]** to choose a tag type.
3. Select **Custom HTML** and paste the following script:

{% tabs %}
{% tab title="JavaScript" %}

```javascript
<script>
  // 1. When UTT is ready, run the following function.
  window.impactOnReady = function() {
    // 2. Configure UTT for your user and widget.
    //  The information provided here is used to track your user and register them in your Advocate program.
    //  This request is authenticated via JWT.
    //  A note about generating JWTs:
    //    JWTs are tokens that are signed with your tenant API key. They must be generated server-side.
    //    To ensure the security of your tenant and program, do not expose your tenant API key to your frontend.
    //    For more information see https://integrations.impact.com/impact-brand/docs/json-web-tokens
    var userConfig = {
      // 2b. Add details about your user.
      //  This must include id and accountId but other fields such as email, firstName, locale,
      //  or even custom fields can be included.
      //  For more details and a list of user fields see https://integrations.impact.com/impact-brand/docs/install-the-utt
      user: {
        id: '{{email}}',
        accountId: '{{email}}',
        locale: 'en_US',
        cookies: '{{advocate}}'
      },
      // 2c. Add your generated JWT here to authenticate your request.
      jwt: '{{jwt}}'
    };

    // 3. Make the request to upsert your user and render your widget.
    impact.api().upsertUser(userConfig).then(function(response) {
      // The widget API automatically inserts the HTML for your widget into your page via an iFrame.
      // However if needed, you can retrieve details about the upserted user and the widget HTML
      // through this function response.
      var user = response.user;
      console.log(user);
      window.dataLayer.push({'event': 'user upserted'});
    }).catch(function(error) {
      console.log(error);
    });
  };
</script>
```

{% endtab %}
{% endtabs %}

4. Expand the **Advanced Settings**.
5. From the *Tag Firing Options* dropdown list, select **Once per event**.
6. Expand the **Tag Sequencing** section.
7. Select the check box for **Fire a tag before Upsert User fires**.
8. From the *Setup tag* dropdown list, select **UTT**.
9. In the *Triggering* section, select the **Advocate** trigger.
10. Select **Save** at the top right of the window.

#### (Optional) Set up an *API upsert* tag <a href="#api-upsert" id="api-upsert"></a>

Follow the steps above and substitute this script **only** if you're unable to generate a JWT and pass it as a variable to GTM.

{% tabs %}
{% tab title="JavaScript" %}

```javascript
<script>
  var username = '{{username}}';     // Replace with your username
  var password = '{{password}}';     // Replace with your password
  var tenantAlias = '{{tenantalias}}';
  var email = '{{email}}';

  var url = 'https://app.referralsaasquatch.com/api/v1/' + tenantAlias + '/open/account/' + email + '/user/' + email;

  var headers = new Headers();
  headers.set('Authorization', 'Basic ' + btoa(username + ':' + password));
  headers.set('Content-Type', 'application/json');

  var userObject = {
    id: '{{email}}',
    accountId: '{{email}}',
    cookies: '{{advocate}}'
  };

  fetch(url, {
    method: 'PUT',
    headers: headers,
    body: JSON.stringify(userObject)
  })
  .then(function(response) {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    console.log(response.body);
    console.log('upserted via API');
  });
</script>
```

{% endtab %}
{% endtabs %}
{% endstep %}

{% step %}

### Set up a tag for the `identify` and `trackConversion` functions

Follow the `identify` function and `trackConversion` function sections of the [standard Pre-Integration Checklist](https://integrations.impact.com/impact-brand/docs/pre-integration-checklist#step-3-the-trackconversion-function) for instructions.
{% endstep %}
{% endstepper %}

#### Next steps

Now that your setup is complete, learn how to publish the [GTM container](https://integrations.impact.com/impact-brand/docs/implementation).


---

# 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://integrations.impact.com/integration-guides/for-brands/advocate/advocate-tracking-integrations/integrate-google-tag-manager-with-advocate.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.
