← Blog
MarketingPerfex CRMIntegrations

UTM Parameters to Your CRM: Keep the Lead Source Intact

Pass UTM parameters to your CRM the only way that survives: captured at first landing, stored in a first-touch cookie, and written to named custom fields.

Someone clicks a Google Ads headline, lands on /services/bookkeeping/?utm_source=google&utm_medium=cpc&utm_campaign=bk-q1-brand, reads for two minutes, clicks through to the pricing page, then to the contact page, and fills in the enquiry form. A lead appears in the CRM with a name, an email address and a source field that says “Website”.

That lead cost about forty pounds to acquire, and there is now no way to prove it. Campaign, ad group and keyword lived in the URL of the first page only, and three navigations later the query string was gone.

The reason to pass UTM parameters to your CRM at the moment of capture, rather than reconstruct attribution later from analytics, is that later is too late: nothing downstream of the form knows which click paid for it. What follows is a working pattern for capturing that data at the form and landing it somewhere your reports can group by. We build and sell some of the products named below, so weigh the recommendations accordingly.

Where the campaign data actually goes

Three separate things quietly destroy campaign context, and they all happen before anyone clicks submit.

The query string only exists on the landing page. Internal links do not carry utm_* forward, and you should not make them - propagating UTMs across internal navigation corrupts your own analytics by starting a fresh session on every click. The parameters live for exactly one pageview unless something stores them.

document.referrer is thinner than you think. It tells you google.com at best and increasingly nothing at all, cannot distinguish paid from organic, and is empty for app clicks, most email clients and anything behind a noreferrer policy.

The form has no memory. A contact form posts the fields it renders. If the form does not render a field containing utm_campaign, that value cannot reach the CRM, however good the integration behind it is.

This is why the source dropdown on most self-hosted CRM lead forms degenerates into Website, Referral, Other within a quarter. Nobody is lying. The data was never delivered.

How to pass UTM parameters to your CRM: capture at first landing

The fix is fifteen lines of JavaScript that run on every page and do nothing on all but the first.

(function () {
  var KEY = 'ts_first_touch';
  if (document.cookie.indexOf(KEY + '=') > -1) return; // first touch wins

  var q = new URLSearchParams(location.search);
  var touch = {
    utm_source:   q.get('utm_source')   || '',
    utm_medium:   q.get('utm_medium')   || '',
    utm_campaign: q.get('utm_campaign') || '',
    utm_term:     q.get('utm_term')     || '',
    utm_content:  q.get('utm_content')  || '',
    gclid:        q.get('gclid')        || '',
    referrer:     document.referrer,
    landing:      location.pathname,
    first_seen:   new Date().toISOString()
  };

  document.cookie = KEY + '=' + encodeURIComponent(JSON.stringify(touch)) +
    ';path=/;max-age=' + (60 * 60 * 24 * 90) + ';SameSite=Lax';
})();

Two details in there matter more than the rest.

The cookie is written even when there are no UTM parameters at all. An organic visitor gets an empty utm_source and a referrer of google.com. That looks useless, and it is the most important line in the script: without it, a visitor who arrives organically in March and returns via a paid ad in May is recorded as paid, and you pay again for a lead you already had. The empty record is what makes first touch mean first touch.

A max-age of 90 days is a decision, not a default. A long B2B consideration window justifies 90; an impulse purchase does not, and 30 days there stops stale campaigns claiming credit. Write whichever you pick next to your attribution model - together they define what every report built on them means.

One honest caveat: in the EU this cookie is analytics-adjacent rather than strictly necessary, so it belongs behind consent. A share of your leads will carry no attribution at all, and a report that silently drops those rows overstates every channel it does show. Count them as “unknown”.

Hidden UTM fields in the contact form

At submit time, read the cookie back and stamp its values into hidden inputs. Any form plugin that renders a hidden field will do - Contact Form 7, Gravity Forms, an embedded widget or a plain <form>.

var raw = document.cookie.replace(
  /(?:^|.*;\s*)ts_first_touch\s*=\s*([^;]*).*$|^.*$/, '$1');

if (raw) {
  var t = JSON.parse(decodeURIComponent(raw));
  document.querySelectorAll('form[data-attribution]').forEach(function (form) {
    Object.keys(t).forEach(function (key) {
      var input = form.querySelector('[name="' + key + '"]');
      if (input) input.value = t[key];
    });
  });
}

Populate the fields on page load, not inside a submit handler: a handler that throws leaves you with a form that no longer submits at all, a far worse bug than a missing utm_term.

Treat these as untrusted input on the server: anyone can post anything into a hidden field. Truncate to a sane length, strip anything that is not alphanumerics, dashes, dots and underscores, and never interpolate them into SQL or an email body unescaped.

Named custom fields beat a free-text notes box

This is where most implementations throw the work away: the values arrive and the integration concatenates them into the lead description or a note, because that is the field that always exists.

A CRM cannot group by a paragraph. “Cost per qualified lead by campaign for Q1” needs utm_campaign to behave like a column, and a note is not a column. In Perfex the REST API module exposes custom fields as a first-class resource - add, update, delete, request fields and their values, and search field values - alongside the leads endpoints, so an integration can create the fields once and then write to them by name on every lead it posts. Notes exist too, as polymorphic records attached to leads among eleven other entity types. They are the right home for a human comment and the wrong home for a dimension you intend to report on.

Captured valueCustom fieldWhat it answers
utm_sourceUTM SourceWhich platform sent them
utm_mediumUTM MediumPaid, organic, email or social
utm_campaignUTM CampaignWhich budget line to charge
utm_term / utm_contentUTM Term, UTM ContentWhich keyword or which creative
referrer + landingReferrer, Landing PageThe fallback when UTMs are absent
first_seenFirst SeenDays from first touch to enquiry

Two operational notes for the API call. Send the token as a Bearer header, not an authtoken query parameter, or the credential lands in every access log between you and the CRM. And use the module’s Idempotency-Key support on POST, which replays a stored response instead of re-executing within a 24-hour window - a double-clicked submit otherwise produces two leads with identical attribution, corrupting the very report you built this for.

The leads a form-side script will never see

Sign-up syncs map fields, not sources

Registration syncs solve a different problem, and solve it well. WordFex picks up every new WordPress or WooCommerce sign-up and creates the matching record in Perfex, with one setting deciding whether it lands in Leads or in Customers. What it maps is exactly four fields: first name, last name, email address and website.

That is the correct scope for a sign-up plugin, and it means attribution stays your job. If a WooCommerce checkout is the moment that matters, the campaign data has to be attached to the WordPress user at registration - your own user_register hook writing the cookie contents into user meta - then pushed onward as a second step. A four-field map will not invent it for you.

In-platform lead forms never had a UTM

A Facebook or LinkedIn lead form is completed inside the platform: no landing page, no query string, no cookie. The same is true of a WhatsApp enquiry, a directory listing and a phone call.

The rule is simple: if the click never touched your site, the integration stamps the channel, not the browser. A connector ingesting Facebook Lead Ads should write utm_source=facebook, utm_medium=paid_social and the campaign name from the platform’s own payload as it creates the record. Platforms built around multi-channel capture do this natively - LeadHub ingests leads from nineteen channels and enriches each with source, campaign and UTM tags as part of the lead record rather than an afterthought.

What you must not do is leave the field blank. Blank aggregates into “Direct” in every reporting tool ever built, and Direct is where unattributed paid spend goes to hide.

First touch vs last touch attribution: decide before anyone builds a report

First touch credits the click that created awareness. Last touch credits the click that produced the enquiry. Both are defensible; running both without saying which is which is not, because two people will pull the same number and get different answers.

The rule we would use: if you are deciding where next month’s budget goes, use first touch. Discovery is what you are buying. Retargeting and brand search reliably win last-touch reports while creating almost none of the demand they claim.

If you want last touch too, keep the first-touch cookie immutable and add a second, short-lived cookie that overwrites on every UTM-carrying visit. Store both and label both; what breaks reports is one cookie drifting between behaviours depending on who last edited the script.

Before you trust the first report

  1. Load a landing page with a full set of utm_* parameters, browse three pages deep, and confirm the cookie still holds the original values.
  2. Submit the form and read the raw POST body. Every hidden field should be present and populated.
  3. Open the created lead and confirm the values sit in named custom fields, not concatenated into a note.
  4. Repeat the submission with an identical payload and confirm you get one lead, not two.
  5. Run it again from a private window with no UTMs at all, and confirm the lead records an empty source plus a referrer rather than nothing.
  6. Write the window and the model - “90-day first touch” - at the top of every report using them.

Step five is the one people skip, and it is the one that decides whether the number you show the board next quarter is real.