Get your dream built 10x faster

How to integrate Salesforce with OpenClaw

We build custom applications 5x faster and cheaper 🚀

Book a Free Consultation
4.9
Clutch rating 🌟
600+
Happy partners
17+
Countries served
190+
Team members
Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Stuck on an error? Book a 30-minute call with an engineer and get a direct fix + next steps. No pressure, no commitment.

How to integrate Salesforce with OpenClaw

 

Direct answer

 

Integrate Salesforce with OpenClaw by: (1) creating a Salesforce Connected App (OAuth client) with the right scopes or a JWT certificate for server-to-server; (2) installing/configuring an OpenClaw skill in ClawHub and storing the Salesforce credentials (client id/secret, private key, refresh token, integration username, instance URL) in secrets/environment variables; (3) implementing the skill’s runtime code to perform OAuth token exchange (JWT or authorization-code/refresh flow), call Salesforce REST APIs using the returned access token, and handle errors/refreshes; and (4) routing Salesforce push events (Outbound Messages, Platform Events, Change Data Capture/Streaming) to an external, durable webhook or worker (not inside ephemeral agent runtime) that validates requests and invokes the OpenClaw skill through its configured entrypoint. Follow least-privilege permissions, use a dedicated integration user or scoped Connected App, and debug by inspecting token/API responses, ClawHub and skill logs, and Salesforce connected-app settings and user permissions.

 

Overview — what “integrating Salesforce with OpenClaw” means

 

  • Salesforce is an external HTTP API and events source. You must authenticate and call its REST endpoints explicitly.
  • OpenClaw (via ClawHub) runs skills/agents that can call external APIs if you give them credentials and code to do so; nothing is automatic.
  • Stateful or always-on pieces (webhook endpoints, streaming subscriptions, durable queues) should live outside the short-lived agent process; the agent should be invoked explicitly when work arrives.

 

Preflight checklist

 

  • Decide authentication mode: JWT Bearer (server-to-server) or Authorization Code with refresh token. Use JWT for backend-to-backend integrations without interactive users.
  • Create a Salesforce Connected App and pick scopes you need (e.g., api, refresh\_token or equivalent). Use a dedicated integration user when appropriate.
  • Plan how to handle inbound events: outbound messages, platform events, or Streaming API — these need a reachable webhook or a streaming worker outside the ephemeral agent runtime.
  • Choose secure secret storage: ClawHub secret store or a cloud secret manager. Never hard-code client secrets or private keys in source.

 

Create the Salesforce Connected App (high level)

 

  • In Salesforce Setup → App Manager → New Connected App (or similar): register your integration.
  • Enable OAuth settings. For web flows provide redirect URLs (for interactive auth). For JWT, upload a signing certificate/public key and enable “Use digital signatures.”
  • Select scopes: at minimum include the api scope; add refresh\_token if you use the authorization-code flow and need long-lived access.
  • Note the Generated Client ID (Consumer Key) and Client Secret (if applicable), or download your certificate/private key for JWT.
  • Ensure the integration user profile has API access and the required object/field permissions.

 

Configure the OpenClaw skill in ClawHub

 

  • Install or upload your skill package to ClawHub per your organization’s process.
  • Add required environment variables and secrets to the skill configuration: e.g., SF_CLIENT_ID, SF_CLIENT_SECRET (if using auth code), SF_PRIVATE_KEY (for JWT), SF_USERNAME (for JWT subject), and optionally SF_INSTANCE\_URL if you need to override sandbox vs production.
  • If using an interactive OAuth flow, configure the skill to accept the authorization callback (or use an external auth handler that stores refresh tokens into ClawHub secrets).
  • Set the skill’s runtime settings and ensure outbound network access to Salesforce endpoints (login.salesforce.com or test.salesforce.com and the REST API base).

 

Authentication options (patterns)

 

  • JWT Bearer (recommended for backend integrations)
    • Create/upload a certificate in the Connected App and use the corresponding private key to sign a short-lived JWT.
    • Exchange the JWT at Salesforce’s token endpoint to receive an access token. No interactive user is required.
  • Authorization Code + Refresh Token
    • Use a one-time interactive user consent to obtain a code, exchange it for an access token and refresh token, and store the refresh token securely. Use the refresh token to get new access\_tokens when needed.

 

Example: JWT Bearer token exchange (Node.js)

 

  • This is a minimal, real example that signs a JWT and exchanges it for an access token at Salesforce.
// Dependencies: npm install jsonwebtoken node-fetch
const jwt = require('jsonwebtoken');
const fetch = require('node-fetch');

const SF_CLIENT_ID = process.env.SF_CLIENT_ID; // Connected App Consumer Key
const SF_USERNAME = process.env.SF_USERNAME;   // Salesforce integration username (sub)
const SF_PRIVATE_KEY = process.env.SF_PRIVATE_KEY; // PEM string, keep in secret storage
const SF_LOGIN_AUD = 'https://login.salesforce.com'; // or https://test.salesforce.com for sandbox
const SF_TOKEN_URL = `${SF_LOGIN_AUD}/services/oauth2/token`;

async function getAccessTokenWithJWT() {
  const now = Math.floor(Date.now() / 1000);
  const payload = {
    iss: SF_CLIENT_ID,    // issuer = client id
    sub: SF_USERNAME,     // subject = username of integration user
    aud: SF_LOGIN_AUD,    // audience = login URL
    exp: now + 3 * 60     // short expiry, e.g., 3 minutes
  };

  // // Sign the JWT with RS256 using your private key
  const assertion = jwt.sign(payload, SF_PRIVATE_KEY, { algorithm: 'RS256' });

  // // Exchange assertion for token
  const params = new URLSearchParams();
  params.append('grant_type', 'urn:ietf:params:oauth:grant-type:jwt-bearer');
  params.append('assertion', assertion);

  const res = await fetch(SF_TOKEN_URL, { method: 'POST', body: params });
  if (!res.ok) {
    const text = await res.text();
    throw new Error(`Token endpoint error: ${res.status} ${text}`);
  }
  const tokenResponse = await res.json();
  // tokenResponse.access_token and tokenResponse.instance_url are returned
  return tokenResponse;
}

 

Example: call Salesforce REST API after you have access_token

 

// // Use instance_url returned from token response and the access_token
async function queryAccounts(accessToken, instanceUrl) {
  // // Replace vXX.X with the API version you target, or use the latest supported
  const apiVersion = 'vXX.X';
  const q = encodeURIComponent('SELECT Id, Name FROM Account LIMIT 5');
  const url = `${instanceUrl}/services/data/${apiVersion}/query?q=${q}`;
  const res = await fetch(url, {
    headers: { 'Authorization': `Bearer ${accessToken}`, 'Accept': 'application/json' }
  });
  if (!res.ok) {
    const body = await res.text();
    throw new Error(`API error: ${res.status} ${body}`);
  }
  return res.json();
}

 

Handling inbound events (webhooks / streaming)

 

  • Do not rely on an ephemeral agent runtime to accept long-lived streaming connections (CometD) or to be always reachable for webhooks. Run a small external web service or worker that is always reachable and durable.
  • The external service should validate incoming requests per Salesforce’s recommended method (signature, session validation, or SOAP outbound message validation). Use Salesforce documentation to confirm the exact validation header/approach for the event type you use.
  • After validation, the external service should call the OpenClaw skill by making an explicit API call to its entrypoint (or enqueue a job that a skill picks up). Do not assume the agent automatically receives Salesforce pushes.
  • Use a queue (SQS, Pub/Sub, RabbitMQ) between the webhook receiver and the OpenClaw skill for retries, back-pressure, and decoupling.

 

Runtime architecture and state

 

  • Keep ephemeral logic (transform, enrich, synchronous requests) inside the skill code. Keep durable state (failed jobs, checkpoints, subscription offsets) in external storage (database, object store).
  • For streaming/CDC, persist offsets and rehydrate on restart from an external store. For webhooks, persist delivery status and implement retries externally.
  • Limit long-running blocking work inside the agent. If a job takes >120 seconds (or your platform’s timeout), hand it to a background worker outside the agent runtime.

 

Security and permission guidance

 

  • Use least privilege: only grant API/object permissions required by the integration user or Connected App.
  • Store secrets (client secrets, private keys, refresh tokens) in ClawHub secret storage or a secure secret manager and reference them from the skill configuration.
  • Rotate keys and client secrets periodically; for JWT rotate certificates and update the Connected App’s public key accordingly.
  • Use dedicated integration users or Named Credentials (on Salesforce) when appropriate to reduce blast radius.

 

Common errors and debugging checklist

 

  • Authentication failures: inspect token endpoint response body for error and error\_description. Check that your iss, sub, aud, and certificate are correct for JWT; check redirect URL and client secret for auth-code flows.
  • Insufficient scope / permission errors: verify Connected App scopes and the integration user’s profile/permission sets include API and object access required.
  • Wrong instance URL: after token exchange use the returned instance\_url for API calls. If you hardcode production vs sandbox endpoints, you can call the wrong host.
  • Network/connectivity: confirm your skill’s runtime has outbound access to login.salesforce.com and the Salesforce instance host; check proxies and firewall rules.
  • Rate limits and API errors: check returned error codes and the Salesforce headers for limits; implement exponential backoff and retries where appropriate.
  • Webhook delivery issues: confirm the external webhook receiver is reachable from Salesforce, log the full request body/headers, and confirm your validation logic matches Salesforce docs.
  • ClawHub/skill invocation: confirm the skill is deployed, environment variables are present, and logs show the skill starting and performing the exchange. If you expect the agent to be invoked, verify the external trigger calls the skill’s configured entrypoint/API.

 

Operational notes

 

  • Test against a Salesforce sandbox (test.salesforce.com) before production. Swap endpoints and Connected App settings accordingly.
  • Log token responses and errors (without logging secrets). Keep sufficient telemetry in both the external webhook service and the OpenClaw skill so you can trace a request end-to-end.
  • Monitor quota usage and add visibility into failed auth attempts, webhook failures, and API throttles.

Book Your Free 30‑Minute Migration Call

Speak one‑on‑one with a senior engineer about your no‑code app, migration goals, and budget. In just half an hour you’ll leave with clear, actionable next steps—no strings attached.

Book a Free Consultation

Troubleshooting Salesforce and OpenClaw Integration

1

Why does the OpenClaw Connector for Salesforce return "invalid_grant" when exchanging the OAuth authorization code?

The short answer: invalid_grant means Salesforce rejected the authorization code grant—most commonly because the code expired or was already used, the redirect_uri in the token request doesn’t exactly match the one used during authorization, client credentials are wrong, or you hit the wrong Salesforce token endpoint (sandbox vs production).

 

Troubleshoot and fixes

 
  • Check code reuse/expiry — auth codes are single-use and short-lived.
  • Ensure redirect_uri exact match — must be byte-for-byte identical.
  • Validate client_id/secret — from the Connected App in Salesforce.
  • Use correct token URL — login.salesforce.com vs test.salesforce.com.
  • Inspect response body and server clocks — clock skew can matter.
// Exchange code for token (Node fetch)
const res = await fetch('https://login.salesforce.com/services/oauth2/token', {
  method: 'POST',
  headers: {'Content-Type':'application/x-www-form-urlencoded'},
  body: new URLSearchParams({
    grant_type: 'authorization_code',
    code: AUTH_CODE,
    client_id: CLIENT_ID,
    client_secret: CLIENT_SECRET,
    redirect_uri: REDIRECT_URI
  })
});
const body = await res.json(); // inspect body.error_description for details

2

Why do OpenClaw Sync Jobs fail with REQUEST_LIMIT_EXCEEDED or API limit errors during bulk upserts to Salesforce?

OpenClaw Sync Jobs hit REQUEST_LIMIT_EXCEEDED or API limit errors because bulk upserts generate more API calls or concurrent work than Salesforce allows — either per-minute REST calls, concurrent Bulk API jobs, or org-wide daily limits — and the agent/skill isn't throttling or batching requests to respect those limits.

 

Why this happens

 

Salesforce enforces per‑org and per‑user API limits and concurrency rules; bursty upserts, parallel jobs, or small batches multiply calls. OpenClaw skills run in the agent runtime and will exceed limits if they send many concurrent requests without client-side throttling, batching, or using the correct Bulk API.

  • Check Salesforce limits endpoint (/services/data/vXX.0/limits) and OpenClaw logs to see exact failures.

 

Mitigations

 
  • Batch records and use Bulk API (or Bulk API 2.0) for large datasets.
  • Throttle within the skill: limit concurrency, add exponential backoff + jitter on 4xx/5xx errors.
  • Serialise or queue work outside the runtime for large imports, move stateful rate control off-agent.
  • Monitor API usage and add retries, logging, and alerts in your OpenClaw skill.

3

Why are custom Salesforce fields not appearing in OpenClaw Mapping Rules after performing a schema refresh?

Direct answer: Custom Salesforce fields usually don't appear in OpenClaw Mapping Rules because the Salesforce API describe call returned no access to them for the integration user or OpenClaw is still using a cached schema. Common root causes are field‑level security / permission sets, wrong API name or namespace, the field not deployed in that org, or the schema refresh failed/was cached.

 

Quick checks

 
  • Verify API visibility: confirm the integration user/profile has FLS and API access to the custom field.
  • Confirm API name: custom fields end with __c and may have a namespace prefix.
  • Check deployment: field exists in the same org/environment used by OpenClaw.
  • Inspect describeSObject: use Workbench/sfdx to call describe; compare response to OpenClaw logs.
  • Clear / re-run schema refresh: ensure cache cleared and watch the refresh logs for errors.

4

Why are OpenClaw Platform Event subscriptions missing events or showing replayId gaps when connected to the Salesforce Streaming API?

 

Direct answer

 

Short answer: missing events and replayId gaps happen because Salesforce only retains platform events for a limited replay window and because disconnects, reconnections, subscription scope/permissions, or API limits can cause you to ask for a replayId that Salesforce no longer has — producing gaps. Network blips, broker failover, or filtering can also make sequences appear non‑contiguous.

 

Details and actions

 
  • Retention window: if you reconnect after the retention period the older replayId is expired — you’ll see gaps.
  • Disconnects/handshake: abrupt disconnects or missed handshake/replay negotiation result in lost events.
  • Permissions/filters: misconfigured event filters or insufficient permissions can drop events for a subscriber.
  • Mitigations: persist last seen replayId immediately, reconnect quickly, inspect Streaming/CometD handshake logs, check Salesforce event retention and limits, or use durable delivery patterns (store events on producer side or use a polling backup).
Book a Free Consultation

Still stuck?
Copy this prompt into ChatGPT and get a clear, personalized explanation.

This prompt helps an AI assistant understand your setup and guide you through the fix step by step, without assuming technical knowledge.

AI AI Prompt


Recognized by the best

Trusted by 600+ businesses globally

From startups to enterprises and everything in between, see for yourself our incredible impact.

RapidDev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with.

They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

Arkady
CPO, Praction
Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost.

He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Donald Muir
Co-Founder, Arc
RapidDev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space.

They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Mat Westergreen-Thorne
Co-CEO, Grantify
RapidDev is an excellent developer for custom-code solutions.

We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Emmanuel Brown
Co-Founder, Church Real Estate Marketplace
Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 

This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Samantha Fekete
Production Manager, Media Production Company
The pSEO strategy executed by RapidDev is clearly driving meaningful results.

Working with RapidDev has delivered measurable, year-over-year growth. Comparing the same period, clicks increased by 129%, impressions grew by 196%, and average position improved by 14.6%. Most importantly, qualified contact form submissions rose 350%, excluding spam.

Appreciation as well to Matt Graham for championing the collaboration!

Michael W. Hammond
Principal Owner, OCD Tech

We put the rapid in RapidDev

Need a dedicated strategic tech and growth partner? Discover what RapidDev can do for your business! Book a call with our team to schedule a free, no-obligation consultation. We’ll discuss your project and provide a custom quote at no cost.Â