How to Get Product Usage Data into Salesforce

See who is using your SaaS product without leaving Salesforce. Sync a few usage facts onto the Lead on an External Id, or read live usage through Apex.

By Published

Your product knows who signed up, who finished setup and who has gone quiet. Salesforce usually does not. Sales works the Leads that filled in a form, customer success hears about churn when the cancellation arrives, and the people ready to buy sit in the product database where nobody in the CRM can see them.

This guide writes to Leads, and the same pattern works on Contact or Account. If your org already holds several Leads per person, start with the duplicate Leads guide.

What you need before you start

  • An integration user in Salesforce that the product signs in as, and a sandbox to build in.
  • A user id in the product that never changes. An email address does not qualify.
  • For the live panel, a product API that returns usage per person and accepts OAuth client credentials.

Step 1: Decide what usage means

Sales needs a handful of facts: where each person is in a short journey, and when they last did something that matters. This guide uses one Lead field for each:

FactLead fieldRule
Product userProduct_User_Id__c, TextThe match key, set once
Signed upSignup_At__c, Date/TimeSet once, never cleared
Set upSetup_Completed_At__c, Date/TimeSet once, never cleared
First real useActivated_At__c, Date/TimeSet once, never cleared
Last activeLast_Active_At__c, Date/TimeMoves forward with each qualifying use
Plan statusSubscription_Status__c, picklistMirrors billing, which stays the source of truth
Features in useFeatures_In_Use__c, multi-select picklistReplaced on every write, cleared when empty
Last syncLast_Product_Sync_At__c, Date/TimeWhen the product last wrote successfully

Define first real use strictly and write the definition into the field's description. In one build it was the first successful use of the product's core job, and logins, setup screens, health checks, failures and writes did not count.

Step 2: Choose where each fact lives

Who needs the fact, and what will they do with it?

Reports, list views, flows

Write it onto the Lead

The product upserts a few fields on an External Id, and anything in Salesforce can filter, count or route on them.

Detail that changes hourly

Read it live from the product

A Lightning web component calls the product's API through a Named Credential. Nothing is stored.

A sales and success team

Store the journey, read the detail

Funnel stages from Lead fields, with a per-person usage tab read live beside them.

Stored facts for reports and routing, live reads for per-person detail. Source: the Lead sync and usage panel in a SaaS company's Salesforce org.

A stored fact is as fresh as the last sync, and a live read costs a callout each time the page opens, so decide per fact.

Step 3: Write the facts onto the Lead

  1. In Setup, open Object Manager, then Lead, then Fields & Relationships. Create Product_User_Id__c as Text with External ID and Unique checked, treating ABC and abc as duplicates. An External ID field holds ids from an outside system and can be used to upsert through the API, and Unique prevents duplicate values.
  2. Create the other fact fields and a permission set that gives the integration user Edit on each one.
  3. Send changes in batches through sObject Collections upsert.
Upsert request
PATCH /services/data/vXX.X/composite/sobjects/Lead/Product_User_Id__c {  "allOrNone": false,  "records": [    {      "attributes": { "type": "Lead" },      "Product_User_Id__c": "usr_8231",      "Signup_At__c": "2026-11-02T14:05:00.000+0000",      "Activated_At__c": "2026-11-03T09:12:00.000+0000",      "Features_In_Use__c": "reports;slack_alerts"    }  ]}

One sObject Collections upsert takes up to 200 records of one object. With allOrNone false, each record succeeds or fails on its own and the results come back in order, so the product retries only the failures. An single-record upsert on an External ID creates a record when nothing matches, updates a single match, and returns a 300 error when several match.

On the product side, one build followed five rules, and we recommend them:

  • Never send a null. Leave the field out.
  • Dates are set once and never cleared.
  • State is replaced. The features list is sent in full every time, and an empty string clears it.
  • Only new Leads get identity. Name, email, company and Lead Source go on a new Lead. An existing Lead gets the id and the facts, so reps' edits stay.
  • Converted Leads are skipped.

Send only field names that exist in the target org. In one build, a single field that Production did not have was enough to reject the whole write, so new fields stayed out of the payload until they existed in every org. Deploy fields before the code that writes them. Salesforce returns a 400 for a request it cannot understand.

The product database stays the source of truth, and the sync runs one way. The product marks a user pending when a fact changes, sends the record, and clears the flag only if the row still matches what it sent. Push each change as it happens and sweep for misses on a schedule, for example every 10 minutes, then test the interval your team needs.

Step 4: Read live usage through a Named Credential

  1. In Setup, open Named Credentials, then External Credentials, and click New. Choose OAuth 2.0 and Client Credentials with Client Secret Flow, with the product's token URL as the Identity Provider URL. Add a principal and enter the client ID and secret. Salesforce makes it a Named Principal, one service-level sign-in for the org. Type the secret into each org; keep it out of source control.
  2. Create a Named Credential, Product_API, with the product's API address as the URL and the external credential selected. Keep Generate Authorization Header on.
  3. In a permission set, open External Credential Principal Access and enable the principal. Salesforce checks for it at run time.
  4. Write one Apex client that every read goes through.
ProductApiClient.cls
public with sharing class ProductApiClient {    public class ProductApiException extends Exception {}     public static Object get(String path) {        HttpRequest req = new HttpRequest();        req.setEndpoint('callout:Product_API' + path);        req.setMethod('GET');        req.setHeader('Accept', 'application/json');        req.setTimeout(20000);        HttpResponse res;        try {            res = new Http().send(req);        } catch (CalloutException e) {            throw new ProductApiException('The product did not answer. Try Refresh.');        }        Integer status = res.getStatusCode();        if (status == 401 || status == 403) {            throw new ProductApiException('The product refused the sign-in. '                + 'Check the Product_API credential and its permission set.');        }        if (status != 200) {            throw new ProductApiException('The product answered ' + status + '.');        }        return JSON.deserializeUntyped(res.getBody());    }}

The endpoint is callout: plus the credential's name, and Salesforce adds the sign-in. In one build we set a 20-second timeout; the default is 10 seconds and the most is 120. A 401 or 403 becomes a sentence that names what to check.

The controller checks access before it calls anything. FeatureManagement.checkPermission reads a custom permission, so a user without it gets an error even when calling the method directly. Unknown filter values fall back to a default and never reach the product.

ProductUsageController.cls
public with sharing class ProductUsageController {    private static final Set<String> WINDOWS = new Set<String>{ 'week', 'month', '30', '90' };    @TestVisible private static Boolean permissionOverride;     @AuraEnabled    public static Object getActivePeople(String windowKey) {        Boolean allowed = permissionOverride != null            ? permissionOverride            : FeatureManagement.checkPermission('View_Product_Usage');        if (!allowed) throw fail('You do not have access to product usage.');        String window = WINDOWS.contains(windowKey) ? windowKey : 'week';        try {            return ProductApiClient.get('/usage/people?window=' + window + '&limit=100');        } catch (ProductApiClient.ProductApiException e) {            throw fail(e.getMessage());        }    }     private static AuraHandledException fail(String message) {        AuraHandledException e = new AuraHandledException(message);        e.setMessage(message);        return e;    }}

Before returning, join each person to their Lead with one SOQL query on Product_User_Id__c, link a converted Lead to its ConvertedContactId, and return only the fields the panel shows.

In the Lightning web component's configuration file, list lightning__HomePage or lightning__RecordPage as targets. Read stored Lead facts with @wire on a cacheable=true method and call refreshApex() on Refresh. Salesforce says not to assume a cache duration. In one build the live methods were non-cacheable so Refresh returned current numbers, which meant calling them imperatively.

Give each read its own spinner and error line, so one slow answer leaves the rest of the panel working, and show the message from the AuraHandledException. Ignore an answer that arrives after the user has changed the date range.

Step 5: Decide what the panel shows

PanelReads fromQuestion it answers
Active people this week, against last weekProduct, liveIs usage growing?
Uses per person, with features and connectionsProduct, liveWhat does each account rely on?
Signed up, set up, first real use, paidLead fieldsWhere do people stall?
No setup two days after signup, or no use two days after setupLead fieldsWhom should we call today?
Quiet: first real use done, nothing in seven daysLead fieldsWho might churn?

The two-day and seven-day lines were one build's choices, so set your own. Link each name to its Lead, or to the Contact after conversion. Run weeks Monday to Sunday in one named time zone, keep the team's own accounts out of the numbers, and define each number in a short list under the panel.

Step 6: Set permissions and test the callouts

Permission setAssigned toGrants
Product sync integrationThe integration userEdit on the fact fields
Product usage viewerPeople who see the panelThe controller class and the View_Product_Usage custom permission
Product API credentialThe same viewersExternal Credential Principal Access

Hide the panel from everyone else with a @salesforce/customPermission import, and keep the Apex check, since the method can still be called directly.

By default, Apex tests cannot make callouts, and a deploy needs 75% coverage, so each test sets a mock with Test.setMock.

ProductUsageControllerTest.cls
@IsTestprivate class ProductUsageControllerTest {    private class ProductApiMock implements HttpCalloutMock {        public Integer status = 200;        public HttpResponse respond(HttpRequest req) {            HttpResponse res = new HttpResponse();            res.setStatusCode(status);            res.setBody('{"people":[{"user_id":"usr_8231","uses":9}]}');            return res;        }    }     @IsTest    static void aRefusedSignInSaysWhatToCheck() {        ProductUsageController.permissionOverride = true;        ProductApiMock mock = new ProductApiMock();        mock.status = 401;        Test.setMock(HttpCalloutMock.class, mock);        try {            ProductUsageController.getActivePeople('week');            Assert.fail('Expected an error');        } catch (AuraHandledException e) {            Assert.isTrue(e.getMessage().contains('Product_API'));        }    }}

The tests in that build covered each read, a refused sign-in, a user without the permission (an error and no callout), a filter value that must never be sent, and a response field that must never reach the page. Salesforce's HttpCalloutMock page has the full pattern.

Every setting on one page

SettingWhere it livesValue in this guide
Product_User_Id__cLead, Fields & RelationshipsText, External ID, Unique, case-insensitive
UpsertREST API, sObject CollectionsPATCH on Lead/Product_User_Id__c, 200 per request, allOrNone false
External credentialSetup, Named CredentialsOAuth 2.0, Client Credentials with Client Secret
Product_APISetup, Named CredentialsProduct API URL, Generate Authorization Header on
Callout timeoutProductApiClient20 seconds
View_Product_UsageCustom PermissionsIn the viewer permission set
Component targetsThe component's configuration filelightning__HomePage, lightning__RecordPage

What goes wrong

What you seeLikely causeWhat to do
Two Leads for one customerThe sync matched on emailMatch on the id. Adopt older email-only Leads once by stamping the id; in one build we took the newest and logged a warning when several matched.
Nothing writes after a releaseA field in the request is missing in the target orgDeploy the field, then the code
Numbers look oldA failed sync, or a cached readCheck Last_Product_Sync_At__c, then press Refresh
The panel says the sign-in was refusedNo secret on the principal, or no principal accessStep 4, items 1 and 3
A callout fails after a saveDML ran first in the same transactionCall out before any DML, which blocks callouts while pending
A busy page hits a limitSeveral callouts in one methodOne callout per method; Salesforce allows 100 callouts and 120 seconds of callout time per transaction
Access fails when Salesforce is slowThe product reads access rules from the CRMKeep entitlement in the product database and send Salesforce a copy

Before sales starts using it

  • Agree what active means. Sales, success and product should read first real use the same way.
  • Mark who owns the fields. The product writes them, so say so in each description and keep them off edit layouts.
  • Choose what is sent and who sees it. In one build we sent counts, dates, feature names and outcomes, and kept request contents in the product.
  • Give each signal an owner. A quiet customer needs a person and a list view.

To tie each signup to the ad that brought it, see campaign attribution in Salesforce. For how the credential parts fit, see Salesforce named credentials explained.

Frequently asked questions

Should the product write usage to Leads or to Accounts?

Write where sales already works. In one build every self-serve signup became a Lead, so the product wrote there. A converted Lead was skipped, and mapping the facts onto the Contact or Account was a separate step.

Why not match product users to Salesforce records by email?

Email changes, and several Leads can share one address. An External Id field holds the product's own user id, and marking it Unique makes Salesforce refuse a second record with the same value. Use email once, to adopt Leads that existed before the sync, then match on the id.

How current is product usage data in Salesforce?

As current as the last successful write. Send each change as it happens, retry misses on a schedule (for example every 10 minutes), and keep a Last Product Sync At field that shows when the product last wrote. A live panel reads the product each time it opens or refreshes.

Do I need Apex to get usage data into Salesforce?

Writing facts onto the Lead needs no Apex: the product calls the Salesforce REST API. Reading live usage into a Lightning panel the way this guide does needs Apex, because the callout runs from an Apex class through a Named Credential.

Can Salesforce decide what a customer is allowed to use?

Keep plan checks, credits and access rules in the product database. A copy of the plan status in Salesforce is fine for sales to read, and the product should never wait on Salesforce to decide whether a request may run.

Official references

GAT Solutions is an independent Salesforce consultancy. Salesforce and Lightning are trademarks of Salesforce, Inc.

Continue the decision

View all resources →

Free consultation

Putting product usage in front of sales? Tell us where it stands.

Never send us a key or password.

See Salesforce integrations

Book a call, or send us what is stuck.

Prefer to talk it through?

Pick a 30-minute time with Gray. Bring the backlog or the thing that broke.

Loading available times…