← Back to Insights

Drupal: OpenAI Ads Pixel and CAPI for Drupal: Complete Setup

Enterprise guide to implementing OpenAI Ads Measurement Pixel and CAPI on Drupal 10/11 with custom modules, Webform handlers, and Guzzle HTTP dispatch.

2026-04-04 • CMS & Website Builders

Organizations deploying Drupal 10 or 11 maintain strict architectural standards. Dropping raw third-party tracking scripts into template files usually breaks because Drupal's render cache, Twig engine, and Content Security Policy directives either strip unmanaged scripts or invalidate page cache tags.

In addition, privacy regulations and enterprise security reviews prohibit transmitting raw, unhashed customer data across browser scripts.

The cleanest solution is packaging your telemetry logic inside a custom Drupal module. The module attaches the browser pixel using Drupal's asset library system (libraries.yml) and page attachment hooks. On the server side, it uses a custom Webform handler plugin to dispatch authenticated, SHA-256 hashed Conversions API events directly from PHP.

Here is how to build and deploy an enterprise-ready OpenAI Ads tracking module on Drupal.

Client pixel attachment via custom module

Create a custom module in your project repository under modules/custom/openai_ads_telemetry.

Define the asset library in openai_ads_telemetry.libraries.yml:

pixel:
  header: true
  js:
    js/openai-pixel-loader.js: {}
  dependencies:
    - core/drupalSettings

Create the JavaScript loader script at js/openai-pixel-loader.js:

(function (drupalSettings) {
  'use strict';

  var pixelId = drupalSettings.openaiAds ? drupalSettings.openaiAds.pixelId : null;
  if (!pixelId) return;

  !function(w,d,e,u,t,s){if(w.openaiAds)return;t=w.openaiAds=function(){
  t.callMethod?t.callMethod.apply(t,arguments):t.queue.push(arguments)};
  if(!w._openaiAds)w._openaiAds=t;t.push=t;t.loaded=!0;t.version='1.0';
  t.queue=[];s=d.createElement(e);s.async=!0;s.src=u;
  var f=d.getElementsByTagName(e)[0];f.parentNode.insertBefore(s,f);
  }(window,document,'script','https://bzrcdn.openai.com/pixel.js');

  openaiAds('init', pixelId);
  openaiAds('track', 'PageView');
})(drupalSettings);

Attach the library and pass the account configuration inside openai_ads_telemetry.module:

<?php

/**
 * Implements hook_page_attachments().
 */
function openai_ads_telemetry_page_attachments(array &$attachments) {
  $config = \Drupal::config('openai_ads_telemetry.settings');
  $pixel_id = $config->get('pixel_id');

  if (!empty($pixel_id)) {
    $attachments['#attached']['library'][] = 'openai_ads_telemetry/pixel';
    $attachments['#attached']['drupalSettings']['openaiAds']['pixelId'] = $pixel_id;
  }
}

Server-side CAPI via Webform handler plugin

When site visitors submit inquiries or register for services, dispatch the lead signal from your server to bypass client-side script blockers.

Create the plugin at src/Plugin/WebformHandler/OpenAiAdsWebformHandler.php:

<?php

namespace Drupal\openai_ads_telemetry\Plugin\WebformHandler;

use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\WebformSubmissionInterface;
use GuzzleHttp\ClientInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Form submission handler to dispatch OpenAI Ads CAPI events.
 *
 * @WebformHandler(
 *   id = "openai_ads_capi",
 *   label = @Translation("OpenAI Ads Conversions API Relay"),
 *   category = @Translation("Telemetry"),
 *   description = @Translation("Sends hashed lead submissions to OpenAI Ads CAPI."),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_SINGLE,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 * )
 */
class OpenAiAdsWebformHandler extends WebformHandlerBase {

  protected ClientInterface $httpClient;

  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    $instance = parent::create($container, $configuration, $plugin_id, $plugin_definition);
    $instance->httpClient = $container->get('http_client');
    return $instance;
  }

  public function postSave(WebformSubmissionInterface $webform_submission, $update = TRUE) {
    if ($update) {
      return; // Only process initial submissions
    }

    $data = $webform_submission->getData();
    $rawEmail = $data['email'] ?? ($data['mail'] ?? null);
    if (!$rawEmail) {
      return;
    }

    $sid = $webform_submission->id();
    $webformId = $webform_submission->getWebform()->id();
    $eventId = 'drupal_lead_' . $webformId . '_' . $sid;

    $hashedEmail = hash('sha256', strtolower(trim($rawEmail)));
    $hashedPhone = null;
    if (!empty($data['phone'])) {
      $cleanPhone = preg_replace('/[^0-9]/', '', $data['phone']);
      $hashedPhone = hash('sha256', $cleanPhone);
    }

    $config = \Drupal::config('openai_ads_telemetry.settings');
    $apiToken = $config->get('api_token');
    if (!$apiToken) {
      return;
    }

    $payload = [
      'data' => [
        [
          'event_name' => 'Lead',
          'event_time' => time(),
          'event_id' => $eventId,
          'user_data' => array_filter([
            'em' => $hashedEmail,
            'ph' => $hashedPhone,
            'client_user_agent' => \Drupal::request()->headers->get('User-Agent'),
            'client_ip_address' => \Drupal::request()->getClientIp(),
          ]),
          'custom_data' => [
            'content_name' => $webform_submission->getWebform()->label(),
            'form_id' => $webformId,
          ],
          'action_source' => 'system_generated',
        ],
      ],
    ];

    try {
      $this->httpClient->postAsync('https://bzr.openai.com/v1/events', [
        'headers' => [
          'Authorization' => 'Bearer ' . $apiToken,
          'Content-Type' => 'application/json',
        ],
        'json' => $payload,
        'timeout' => 3.0,
      ]);
    } catch (\Throwable $e) {
      \Drupal::logger('openai_ads_telemetry')->error('CAPI dispatch failed: @msg', ['@msg' => $e->getMessage()]);
    }
  }
}

Front-end form listener and deduplication

Pair the server submission with a client-side JavaScript behavior so both events carry the same deduplication key:

(function (Drupal) {
  'use strict';

  Drupal.behaviors.openaiAdsFormTracking = {
    attach: function (context) {
      var forms = context.querySelectorAll('.webform-submission-form');
      forms.forEach(function (form) {
        if (!form.getAttribute('data-openai-bound')) {
          form.setAttribute('data-openai-bound', 'true');
          form.addEventListener('submit', function () {
            var webformId = form.getAttribute('data-drupal-selector') || 'form';
            var dedupeId = 'drupal_lead_' + webformId + '_' + Date.now();

            if (window.openaiAds) {
              window.openaiAds('track', 'Lead', {
                content_name: 'Webform Submission'
              }, {
                event_id: dedupeId
              });
            }
          });
        }
      });
    }
  };
})(Drupal);

Verification checklist

Review browser security warnings in the console to confirm https://bzrcdn.openai.com/pixel.js is allowed by your Drupal Content Security Policy settings.

Navigate to Reports and inspect Recent log messages in Drupal to verify that outgoing HTTP POST requests to OpenAI return status 200 without timeout errors.

Open Event Manager inside OpenAI Ads to confirm that browser and backend events match on event_id and merge cleanly.

Frequently asked questions

How do I add the OpenAI Ads Pixel to Drupal without modifying core files?

Implement hook_page_attachments() in a custom module, attaching an asset library that loads https://bzrcdn.openai.com/pixel.js and passes settings through drupalSettings.

How do I capture Webform submissions for OpenAI Ads CAPI in Drupal?

Build a custom WebformHandler extending WebformHandlerBase. In the postSave() method, extract submitted values, hash customer identity fields with SHA-256, and dispatch an asynchronous HTTP POST to https://bzr.openai.com/v1/events using Guzzle.

How does Drupal deduplicate client and server events?

Both the client behavior listener and the server Webform handler format event_id using the webform identifier and submission ID, ensuring both channels emit matching keys.

Does Drupal caching or BigPipe affect CAPI dispatches?

No. Server-side WebformHandlerBase callbacks run when forms are submitted via HTTP POST, entirely outside Drupal's BigPipe and Dynamic Page Cache layers.

Need ChatGPT tracking installed?

Configured, tested, documented.