Developer Guide: Implementing PartnerTrack.js
This developer guide provides comprehensive technical documentation for implementing PartnerTrack.js tracking across different form platforms and website environments. The guide includes code examples, integration patterns, and troubleshooting guidance for developers responsible for deploying partner attribution tracking to web properties.
Prerequisites and Requirements
Before implementing PartnerTrack.js integration, ensure the following prerequisites are met:
Administrative Configuration Complete: Referral Settings must be configured by administrators including Enable Referral Tracking, attribution model selection, cookie-less tracking settings, and domain whitelisting. The PartnerTrack.js script must be generated and provided to developers from Setup → Partner Management → Deal Settings → Referral Settings.
Script Deployment Verified: The PartnerTrack.js tracking script must be deployed to the <head> section of all pages where attribution should function, including landing pages, form pages, and any pages prospects may visit after clicking referral links. Verify script deployment by checking browser developer console for "PartnerTrack initialized" confirmation message.
Form Fields Identified: Developers must identify which form fields map to required tracking parameters: name (customer full name), email (customer email address), and customerKey (unique customer identifier, typically email). Additional optional fields may include LeadSource, product, or custom attributes based on organizational requirements.
Integration Approach Determined: Confirm whether your organization is using Magentrix-created leads (script handles lead creation) or external system-created leads (form system handles lead creation with partner attribution). This determines whether your integration must capture and store Partner Contact ID or simply trigger tracking events.
Understanding PartnerTrack.js Architecture
Script Operation Model
PartnerTrack.js operates as a passive tracking mechanism that activates only when explicitly called by form submission events. The script does not automatically track page views, user behavior, or general browsing activity. Instead, it waits for your integration code to trigger the trackSignup() method when forms are submitted.
When a visitor clicks a partner referral link, Magentrix redirects them to your landing page and appends two URL parameters: magpk (Partner Contact CRM ID) and magkey (unique session identifier). PartnerTrack.js reads these parameters, generates a privacy-compliant device fingerprint, and stores the partner association locally without using browser cookies.
When your form integration code calls the trackSignup() method with customer information, PartnerTrack.js sends attribution data to Magentrix, creating a Referral record that connects the prospect to the referring partner. Depending on configuration, this may also trigger automatic CRM lead creation with partner attribution fields populated.
Required Callback Function
All PartnerTrack.js integrations must implement the onInitPartnerTracker() callback function. This function is automatically invoked by PartnerTrack.js when the script finishes loading and is ready to receive tracking calls. Your integration code should be placed inside this callback to ensure the tracking API is available before attempting to bind form events.
function onInitPartnerTracker(tracker) {
// Your integration code goes here
// The 'tracker' parameter provides access to PartnerTrack API methods
}
Global API Access
In addition to the callback-based approach, PartnerTrack.js exposes a global object mgxPartnerTrack that provides access to tracking methods from anywhere in your page code. This is useful for scenarios where you need to access partner information outside the initialization callback or when integrating with third-party form platforms that have their own initialization timing.
// Access Partner Contact ID
var partnerContactId = mgxPartnerTrack.getPartnerKey();
// Trigger tracking event
mgxPartnerTrack.trackSignup({
name: "John Smith",
email: "john.smith@example.com",
customerKey: "john.smith@example.com"
});
Standard HTML Form Integration
Standard HTML forms provide the most direct integration approach with complete control over form submission behavior and field access.
Basic Implementation Pattern
function onInitPartnerTracker(tracker) {
// Bind to form submit button click event
document.getElementById("btnSubmit").addEventListener("click", function() {
// Extract form field values
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
var email = document.getElementById("email").value;
var product = document.getElementById("product").value;
// Call trackSignup with customer data
tracker.trackSignup({
name: firstName + " " + lastName,
email: email,
customerKey: email,
product: product,
LeadSource: "Partner Referral"
});
});
}
Form Submission Handling
The above example binds to the button click event rather than the form submit event. This ensures tracking fires before form submission prevents page navigation. If your form uses AJAX submission or prevents default form submission, you can safely bind to the form submit event instead:
function onInitPartnerTracker(tracker) {
document.getElementById("signupForm").addEventListener("submit", function(e) {
// Extract and track form data
tracker.trackSignup({
name: document.getElementById("fullName").value,
email: document.getElementById("email").value,
customerKey: document.getElementById("email").value,
LeadSource: "Partner Referral"
});
});
}
Required and Optional Fields
The trackSignup() method requires three mandatory fields:
- name: Customer full name (string)
- email: Customer email address (string)
- customerKey: Unique customer identifier, typically email (string)
Optional fields can be included to populate additional lead data when Magentrix creates CRM leads. These optional fields must correspond to actual fields on your CRM Lead object:
Understanding Optional Fields:
- Optional field names must match the API names or field labels in your CRM Lead object
- For Salesforce, use API names like "LeadSource", "Company", "Phone", "Industry"
- For native Magentrix or other CRMs, use the field names as they appear in your Lead entity configuration
- Custom fields follow the same naming convention as standard fields in your CRM
- If a field name does not exist on the Lead object, it will be ignored during lead creation
- Only include fields that exist in your CRM to avoid confusion and ensure data populates correctly
Example with CRM Lead Fields:
tracker.trackSignup({
// Required fields
name: "Jane Doe",
email: "jane.doe@example.com",
customerKey: "jane.doe@example.com",
// Optional standard Lead fields (must exist in your CRM)
LeadSource: "Partner Referral",
Company: "Acme Corporation",
Phone: "+1-555-0123",
Title: "VP of Marketing",
Industry: "Technology",
// Optional custom fields (examples - must exist in your CRM)
Product_Interest__c: "Enterprise Plan",
Campaign_Code__c: "Q2-2025-PROMO",
Partner_Tier__c: "Gold"
});
Important Notes About Optional Fields:
- Consult your CRM administrator to identify correct field API names
- For Salesforce custom fields, API names typically end with "__c"
- Test with a few fields first before including many optional fields
- Review created leads in CRM to verify optional fields populate correctly
- Remove any optional fields that are not populating to keep integration code clean
Magentrix Lead Form Integration
Magentrix Lead forms provide native integration with minimal configuration required. The integration adds a hidden Partner Contact field and binds tracking to form submission.
Hidden Field Configuration
Add a hidden field to your Lead form layout that maps to the Partner Contact lookup field in your CRM:
- Field Type: Hidden
- Field Mapping (Salesforce): MagentrixOne__PartnerContact_mgtrx__c
- Field Mapping (Native): PartnerContactId
- HTML ID: partnerContact
Complete Integration Script
function onInitPartnerTracker(tracker) {
// Populate hidden Partner Contact field with partner ID
try {
var partnerKey = (window.mgxPartnerTrack && mgxPartnerTrack.getPartnerKey)
? mgxPartnerTrack.getPartnerKey()
: "";
if (partnerKey) {
document.getElementById("partnerContact").value = partnerKey;
}
} catch(e) {
console.warn("Partner key not set:", e);
}
// Bind tracking to form submit button
var submitButton = document.getElementById("btnSubmit") ||
document.querySelector(".btn-primary");
if (submitButton) {
submitButton.addEventListener("click", function() {
// Build full name from first and last name fields
var firstName = document.getElementById("FirstName").value || "";
var lastName = document.getElementById("LastName").value || "";
var fullName = (firstName + " " + lastName).trim();
var email = document.getElementById("Email").value;
// Trigger tracking event
tracker.trackSignup({
name: fullName,
email: email,
customerKey: email,
LeadSource: "Partner Referral"
});
});
}
}
Field ID Reference
Adjust field IDs in the integration code to match your actual form field IDs. Common Magentrix Lead form field IDs include:
- FirstName: First name input field
- LastName: Last name input field
- Email: Email input field
- Company: Company name input field
- Phone: Phone number input field
- partnerContact: Hidden partner contact lookup field
- btnSubmit: Primary submit button
Lead Ownership Configuration
Set the Lead Ownership field default value to "Partner" in your form layout to ensure leads are assigned to partners rather than internal sales teams. This supports proper lead routing and partner relationship management.
HubSpot Forms Integration
HubSpot forms require custom JavaScript to access form fields and bind to HubSpot's form submission events. The integration must account for HubSpot's dynamic form rendering and field ID management.
Integration Approach
HubSpot forms may randomize element IDs, making it unreliable to select fields by ID. Instead, access form fields using their name attribute which remains consistent. Bind to the form submit event after ensuring the form has fully loaded.
Complete Integration Code
function onInitPartnerTracker(tracker) {
function registerSignup(e) {
// Prevent premature form submission if needed
// e.preventDefault(); // Uncomment if tracking must complete before submit
console.log('Registering partner referral signup');
// Access HubSpot form fields by name attribute
var firstName = document.querySelector('input[name="firstname"]').value;
var lastName = document.querySelector('input[name="lastname"]').value;
var email = document.querySelector('input[name="email"]').value;
// Optional: access additional fields if present
var product = document.querySelector('input[name="product"]')
? document.querySelector('input[name="product"]').value
: "";
// Trigger tracking
tracker.trackSignup({
name: firstName + " " + lastName,
email: email,
customerKey: email,
product: product,
LeadSource: "Partner Referral"
});
}
// Access HubSpot form element
var hubspotForm = document.getElementsByClassName('hs-form')[0];
// Handle delayed form rendering
if (!hubspotForm) {
console.log('HubSpot form not found, waiting 2 seconds...');
setTimeout(function() {
hubspotForm = document.getElementsByClassName('hs-form')[0];
if (hubspotForm) {
hubspotForm.addEventListener("submit", registerSignup);
} else {
console.error('HubSpot form still not found after delay');
}
}, 2000);
} else {
// Form already loaded, bind immediately
hubspotForm.addEventListener("submit", registerSignup);
}
}
HubSpot Field Name Reference
Common HubSpot form field names include:
- firstname: First name
- lastname: Last name
- email: Email address
- company: Company name
- phone: Phone number
- product: Product interest (custom field)
Verify actual field names by inspecting your HubSpot form HTML in browser developer tools.
Handling iFrame Embeds
If your HubSpot form is embedded within an iframe, the above approach may not work due to cross-origin restrictions. In this scenario, you may need to use HubSpot's Forms API with event listeners or deploy PartnerTrack.js within the iframe context itself.
Marketo Forms Integration
Marketo forms provide a JavaScript API for accessing form data and binding to submission events. The integration uses Marketo's MktoForms2 object to interact with forms.
Integration Pattern
// Load Marketo form with PartnerTrack integration
MktoForms2.loadForm("//your-marketo-instance.marketo.com", "YOUR_MUNCHKIN_ID", FORM_ID, function(form) {
// Add onSubmit handler to Marketo form
form.onSubmit(function() {
// Get form field values using Marketo API
var values = form.vals();
// Trigger PartnerTrack attribution
mgxPartnerTrack.trackSignup({
name: values.FirstName + " " + values.LastName,
email: values.Email,
customerKey: values.Email,
product: values.Product || "",
LeadSource: "Partner Referral"
});
// Allow form submission to proceed
return true;
});
});
Complete Implementation Example
// Ensure PartnerTrack is initialized before Marketo form loads
function onInitPartnerTracker(tracker) {
console.log('PartnerTrack initialized, loading Marketo form...');
}
// Load Marketo form after PartnerTrack initialization
MktoForms2.loadForm("//app-ab12.marketo.com", "123-ABC-456", 1234, function(form) {
form.onSubmit(function() {
console.log('Marketo form submitted, triggering PartnerTrack...');
var formData = form.vals();
// Build full name from separate first/last name fields
var fullName = (formData.FirstName || "") + " " + (formData.LastName || "");
fullName = fullName.trim();
// Trigger attribution tracking
mgxPartnerTrack.trackSignup({
name: fullName,
email: formData.Email,
customerKey: formData.Email,
company: formData.Company || "",
phone: formData.Phone || "",
LeadSource: "Partner Referral"
});
// Return true to allow form submission
return true;
});
// Optional: handle form success event
form.onSuccess(function(values, followUpUrl) {
console.log('Marketo form submission successful');
// Custom success handling if needed
return true;
});
});
Marketo Field Reference
Access Marketo form fields using the form.vals() method which returns an object with field values. Common field names include:
- FirstName: First name
- LastName: Last name
- Email: Email address
- Company: Company name
- Phone: Phone number
Field names in Marketo are case-sensitive and must match your form configuration exactly.
Script Loading Order
Ensure PartnerTrack.js loads before your Marketo integration code. If PartnerTrack.js is not yet loaded when Marketo form initialization occurs, the mgxPartnerTrack object may not be available. Place the PartnerTrack.js script tag before your Marketo form embedding code in your page HTML.
External System Lead Creation Integration
When external systems (HubSpot, Marketo, or custom forms) handle lead creation, your integration must capture the Partner Contact ID and pass it to your lead creation process.
Accessing Partner Contact ID
Use the getPartnerKey() method to retrieve the Partner Contact CRM ID for attribution:
function onInitPartnerTracker(tracker) {
// Get Partner Contact ID
var partnerContactId = mgxPartnerTrack.getPartnerKey();
if (partnerContactId) {
console.log('Partner Contact ID:', partnerContactId);
// Store in hidden form field for submission
document.getElementById("hiddenPartnerField").value = partnerContactId;
} else {
console.log('No partner attribution for this visitor');
}
}
Passing Partner ID to Form System
Different form platforms require different approaches for passing the Partner Contact ID:
Hidden Form Field Approach:
// Add hidden field to form
<input type="hidden" name="partnerContactId" id="hiddenPartnerField" value="">
// Populate in PartnerTrack callback
function onInitPartnerTracker(tracker) {
var partnerId = mgxPartnerTrack.getPartnerKey();
if (partnerId) {
document.getElementById("hiddenPartnerField").value = partnerId;
}
}
Direct Variable Assignment:
// Store in global variable for access by form handler
var globalPartnerContactId = null;
function onInitPartnerTracker(tracker) {
globalPartnerContactId = mgxPartnerTrack.getPartnerKey();
}
// Access in form submission handler
function handleFormSubmit() {
var leadData = {
firstName: "John",
lastName: "Smith",
email: "john.smith@example.com",
partnerContactId: globalPartnerContactId
};
// Submit to your backend
submitLeadToBackend(leadData);
}
CRM Field Mapping
Ensure your lead creation process maps the Partner Contact ID to the correct CRM lookup field:
- Salesforce: MagentrixOne__PartnerContact_mgtrx__c
- HubSpot: Custom property mapped to partner contact
- Dynamics: Custom lookup field configured in CRM
Additionally, set the Lead Source field to "Partner Referral" and Lead Ownership to "Partner" to support proper lead routing and attribution reporting.
Testing and Validation
Browser Console Verification
Open browser developer console (F12) when testing attribution to verify PartnerTrack.js operation:
Expected Console Messages:
PartnerTrack initialized
Partner Contact ID: 0031234567890ABC
PartnerTrack signup tracked successfully
Common Error Messages:
Error: PartnerTrack not initialized
Warning: Partner key not set
Error loading the script
Testing Checklist
Complete the following testing steps to validate integration:
- Script Loading: Verify PartnerTrack.js script loads without errors in browser console
- URL Parameters: Confirm
magpk and magkey parameters appear in landing page URL after clicking referral link - Partner Key Access: Verify
mgxPartnerTrack.getPartnerKey() returns expected Partner Contact ID - Form Submission: Submit test form and verify console shows successful tracking event
- CRM Lead Creation: Check CRM for test lead record with Partner Contact field populated
- Referral Report: Verify referral appears in Setup → Partner Management → Referral Reports
- Cross-Page Attribution: Navigate to different page before form submission and verify attribution persists
Common Integration Issues
PartnerTrack undefined error:
- Cause: Script not loaded or callback function called before initialization
- Solution: Verify script placement in
<head> and ensure code is inside onInitPartnerTracker() callback
No partner attribution on leads:
- Cause: Hidden field ID mismatch or getPartnerKey() not called
- Solution: Verify field mapping to correct CRM lookup field and confirm partner ID retrieval logic
Form submission tracking not firing:
- Cause: Button selector incorrect or event binding fails
- Solution: Verify button ID/class matches actual form element and check console for binding errors
CORS or 403 errors:
- Cause: Domain not whitelisted in Referral Settings
- Solution: Add domain to Setup → Security → Whitelisted URLs
Advanced Integration Patterns
Multiple Forms on Single Page
When multiple forms exist on a single page, bind tracking to each form independently:
function onInitPartnerTracker(tracker) {
// Form 1 integration
document.getElementById("form1Submit").addEventListener("click", function() {
tracker.trackSignup({
name: document.getElementById("form1Name").value,
email: document.getElementById("form1Email").value,
customerKey: document.getElementById("form1Email").value,
product: "Product A"
});
});
// Form 2 integration
document.getElementById("form2Submit").addEventListener("click", function() {
tracker.trackSignup({
name: document.getElementById("form2Name").value,
email: document.getElementById("form2Email").value,
customerKey: document.getElementById("form2Email").value,
product: "Product B"
});
});
}
Conditional Tracking Logic
Implement conditional tracking when forms should only trigger attribution under certain conditions:
function onInitPartnerTracker(tracker) {
document.getElementById("btnSubmit").addEventListener("click", function() {
var formType = document.getElementById("formType").value;
// Only track for specific form types
if (formType === "trial" || formType === "demo") {
tracker.trackSignup({
name: document.getElementById("fullName").value,
email: document.getElementById("email").value,
customerKey: document.getElementById("email").value,
product: formType,
LeadSource: "Partner Referral"
});
}
});
}
Custom Callback Handling
Implement custom logic after tracking events complete:
function onInitPartnerTracker(tracker) {
document.getElementById("btnSubmit").addEventListener("click", function() {
var trackingData = {
name: document.getElementById("name").value,
email: document.getElementById("email").value,
customerKey: document.getElementById("email").value
};
// Trigger tracking
tracker.trackSignup(trackingData);
// Custom post-tracking logic
console.log('Partner referral tracked:', trackingData);
// Optional: trigger analytics events
if (window.gtag) {
gtag('event', 'partner_referral', {
'event_category': 'engagement',
'event_label': trackingData.email
});
}
});
}
Security and Best Practices
Data Validation
Always validate form data before passing to trackSignup() to ensure data quality:
function onInitPartnerTracker(tracker) {
document.getElementById("btnSubmit").addEventListener("click", function() {
var email = document.getElementById("email").value;
var name = document.getElementById("name").value;
// Validate required fields
if (!email || !name) {
console.error('Missing required fields for partner tracking');
return;
}
// Validate email format
var emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailPattern.test(email)) {
console.error('Invalid email format for partner tracking');
return;
}
// Proceed with tracking
tracker.trackSignup({
name: name,
email: email,
customerKey: email,
LeadSource: "Partner Referral"
});
});
}
Error Handling
Implement proper error handling to prevent integration failures from breaking form functionality:
function onInitPartnerTracker(tracker) {
document.getElementById("btnSubmit").addEventListener("click", function() {
try {
// Attempt tracking
tracker.trackSignup({
name: document.getElementById("name").value,
email: document.getElementById("email").value,
customerKey: document.getElementById("email").value
});
} catch (error) {
// Log error but allow form submission to proceed
console.error('PartnerTrack error:', error);
// Optional: send error to monitoring service
if (window.errorTracking) {
window.errorTracking.logError('PartnerTrack Integration', error);
}
}
});
}
Performance Considerations
PartnerTrack.js is designed to be lightweight and non-blocking. The script loads asynchronously and does not impact page load performance. Tracking events are fire-and-forget, meaning form submission proceeds immediately without waiting for tracking requests to complete.
For optimal performance:
- Deploy script to
<head> for early initialization - Avoid redundant tracking calls for single form submissions
- Minimize custom logic within tracking event handlers
- Use browser console to verify tracking completes quickly (typically <100ms)
The Developer Guide: Implementing PartnerTrack.js provides comprehensive technical documentation for integrating partner attribution tracking across diverse form platforms and website environments, enabling developers to implement accurate, reliable partner referral attribution that supports organizational lead generation and partner program objectives.
Jump to Referral Links and Attribution Checklist
<< Referral Links and Attribution Checklist | Understanding Attribution Models >>