# GAM Integration

This guide explains how to integrate n360ortb with Google Ad Manager (GAM) using Google Publisher Tag (GPT).

## Overview

When integrating with GAM:

1. Configure GPT with `disableInitialLoad()` to prevent ads from loading automatically
2. Call `n360ortb.fetchBids()` to run the header bidding auction
3. Call `n360ortb.setDisplayBids()` to set targeting on GPT slots
4. Call `googletag.pubads().refresh()` to load ads with bid targeting

This allows Nexx360 bids to compete with your direct campaigns and Google AdX in the GAM unified auction.

## Complete Example

```html
<!DOCTYPE html>
<html>
<head>
  <title>n360ortb GAM Integration</title>

  <!-- Google Publisher Tag -->
  <script async src="https://securepubads.g.doubleclick.net/tag/js/gpt.js"></script>
  <script>
    window.googletag = window.googletag || { cmd: [] };

    googletag.cmd.push(function() {
      // Define your ad slots
      googletag.defineSlot(
        '/12345678/homepage-leaderboard',
        [[728, 90], [970, 250]],
        'div-leaderboard'
      ).addService(googletag.pubads());

      googletag.defineSlot(
        '/12345678/sidebar-mpu',
        [[300, 250], [300, 600]],
        'div-sidebar'
      ).addService(googletag.pubads());

      googletag.pubads().enableSingleRequest();
      googletag.enableServices();

      // IMPORTANT: Disable initial load to wait for header bidding
      googletag.pubads().disableInitialLoad();
    });
  </script>

  <!-- n360ortb loader -->
  <script>
  !function(){if(!window.n360ortb){window.n360ortb={init:function(){e("init",arguments)},fetchBids:function(){e("fetchBids",arguments)},setDisplayBids:function(){},targetingKeys:function(){return[]},que:[]};var n=document.createElement("script");n.async=!0,n.src="https://lib.nexx360.io/nexx360ortb/api.js";var t=document.getElementsByTagName("script")[0];t.parentNode.insertBefore(n,t)}function e(n,t){window.n360ortb.que.push([n,t])}}();
  </script>

  <script>
    // Initialize n360ortb
    n360ortb.init({
      currency: 'EUR',
      gdpr: {
        cmpTimeout: 1000
      }
    });

    // Fetch bids
    n360ortb.fetchBids({
      slots: [
        {
          tagId: 'homepage-leaderboard-tag',
          divId: 'div-leaderboard',
          sizes: [[728, 90], [970, 250]]
        },
        {
          tagId: 'sidebar-mpu-tag',
          divId: 'div-sidebar',
          sizes: [[300, 250], [300, 600]]
        }
      ]
    }, function(bids) {
      // Set bid targeting on GPT slots
      n360ortb.setDisplayBids();

      // Refresh ads to trigger the GAM auction
      googletag.pubads().refresh();
    });
  </script>
</head>
<body>
  <h1>My Website</h1>

  <div id="div-leaderboard">
    <script>
      googletag.cmd.push(function() {
        googletag.display('div-leaderboard');
      });
    </script>
  </div>

  <p>Page content here...</p>

  <div id="div-sidebar">
    <script>
      googletag.cmd.push(function() {
        googletag.display('div-sidebar');
      });
    </script>
  </div>
</body>
</html>
```

## Targeting Keys

When `setDisplayBids()` is called, the following targeting keys are set on each GPT slot:

| Key        | Description           | Example Value    |
| ---------- | --------------------- | ---------------- |
| n360\_bid  | Unique bid identifier | `"abc123def456"` |
| n360\_pb   | Price bucket          | `"2.50"`         |
| n360\_sz   | Ad size               | `"300x250"`      |
| n360\_crid | Creative ID           | `"creative_789"` |
| n360\_ssp  | SSP identifier        | `"appnexus"`     |

These keys are used by the line items in GAM to target winning bids and render the correct creative. See [Line Item Setup](https://developer.nexx360.io/direct-integration-n360ortb/gam-integration/line-item-setup) for full details on price granularity and how line items are configured.

## Key Configuration Points

### 1. Disable Initial Load

```javascript
googletag.pubads().disableInitialLoad();
```

This is **essential**. It prevents GPT from loading ads before the header bidding auction completes.

### 2. Match divId to GPT Slot ID

The `divId` in your n360ortb slot configuration must match the element ID used in `googletag.defineSlot()`:

```javascript
// GPT slot definition
googletag.defineSlot('/12345/my-unit', [[300, 250]], 'div-1');

// n360ortb slot - divId must match 'div-1'
{
  tagId: 'my-tag',
  divId: 'div-1',  // Must match GPT slot ID
  sizes: [[300, 250]]
}
```

### 3. Matching Sizes

The sizes in your n360ortb configuration should match those in your GPT slot definition:

```javascript
// GPT slot with sizes
googletag.defineSlot('/12345/my-unit', [[300, 250], [300, 600]], 'div-1');

// n360ortb slot with matching sizes
{
  tagId: 'my-tag',
  divId: 'div-1',
  sizes: [[300, 250], [300, 600]]  // Should match GPT sizes
}
```

## Automatic Targeting Cleanup

The `setDisplayBids()` method automatically registers an event listener on `slotRenderEnded` to clear n360ortb targeting after each slot renders. This prevents stale targeting from affecting subsequent ad refreshes.

## Refreshing Specific Slots

To refresh only specific slots:

```javascript
function refreshSlot(divId, tagId, sizes) {
  n360ortb.fetchBids({
    slots: [
      { tagId: tagId, divId: divId, sizes: sizes }
    ]
  }, function(bids) {
    n360ortb.setDisplayBids();

    // Refresh only the specific slot
    googletag.cmd.push(function() {
      var slot = googletag.pubads().getSlots().find(function(s) {
        return s.getSlotElementId() === divId;
      });
      if (slot) {
        googletag.pubads().refresh([slot]);
      }
    });
  });
}

// Usage
refreshSlot('div-sidebar', 'sidebar-mpu-tag', [[300, 250], [300, 600]]);
```

## Setup Requirements

Before using the GAM integration, you need to:

1. [Connect your GAM account](https://developer.nexx360.io/direct-integration-n360ortb/gam-integration/connect-your-gam-account) - Grant Nexx360 access to create line items
2. [Line Item Setup](https://developer.nexx360.io/direct-integration-n360ortb/gam-integration/line-item-setup) - Understand how line items and price buckets work
3. [Set up GAM creatives](https://developer.nexx360.io/direct-integration-n360ortb/gam-integration/gam-creative-setup) - Configure the creative template to render bids

## Next Steps

* [Connect your GAM account](https://developer.nexx360.io/direct-integration-n360ortb/gam-integration/connect-your-gam-account)
* [Line Item Setup](https://developer.nexx360.io/direct-integration-n360ortb/gam-integration/line-item-setup)
* [GAM Creative Setup](https://developer.nexx360.io/direct-integration-n360ortb/gam-integration/gam-creative-setup)
* [API Reference](https://developer.nexx360.io/direct-integration-n360ortb/api-reference)
