```html Salesforce Integration Guide | Knowledge Base

Knowledge Base

Salesforce Integration Guide

Integrate your application with Salesforce to sync contacts, leads, and opportunities securely and efficiently.

Overview

This guide walks you through creating a connected app in Salesforce, authenticating via OAuth 2.0, and using the REST API to exchange data.

Prerequisites

Setup Steps

  1. Create a Connected App:
    1. Log in to Salesforce → Setup → App Manager → New Connected App
    2. Enter App Name and Contact Email
    3. Enable OAuth Settings and add https://yourapp.com/oauth/callback as a callback URL
    4. Select scopes: Full access (full), Perform requests on your behalf at any time (refresh_token, offline_access)
    5. Save – note the generated Consumer Key and Consumer Secret
  2. Configure environment variables:
    SALESFORCE_CLIENT_ID=YOUR_CONSUMER_KEY
    SALESFORCE_CLIENT_SECRET=YOUR_CONSUMER_SECRET
    SALESFORCE_REDIRECT_URI=https://yourapp.com/oauth/callback
  3. Install required libraries:
    npm install axios qs

Authentication (OAuth 2.0)

Redirect users to Salesforce to authorize your app, then exchange the authorization code for an access token.

https://login.salesforce.com/services/oauth2/authorize?response_type=code&client_id=$SALESFORCE_CLIENT_ID&redirect_uri=$SALESFORCE_REDIRECT_URI&scope=full%20refresh_token

Backend token exchange (Node.js example):

const axios = require('axios');
const qs = require('qs');

async function getToken(code) {
  const data = qs.stringify({
    grant_type: 'authorization_code',
    code,
    client_id: process.env.SALESFORCE_CLIENT_ID,
    client_secret: process.env.SALESFORCE_CLIENT_SECRET,
    redirect_uri: process.env.SALESFORCE_REDIRECT_URI
  });
  const resp = await axios.post('https://login.salesforce.com/services/oauth2/token', data);
  return resp.data; // { access_token, refresh_token, instance_url, … }
}

Sample Code – Create a Contact

async function createContact(token, instanceUrl, contact) {
  const url = \`\${instanceUrl}/services/data/v57.0/sobjects/Contact\`;
  const resp = await axios.post(url, contact, {
    headers: { Authorization: \`Bearer \${token}\` }
  });
  return resp.data; // Id of the new contact
}

// Example usage
const tokenInfo = await getToken('AUTH_CODE');
const newContact = {
  FirstName: 'Jane',
  LastName: 'Doe',
  Email: 'jane.doe@example.com'
};
const result = await createContact(tokenInfo.access_token, tokenInfo.instance_url, newContact);
console.log('Created Contact Id:', result.id);

Troubleshooting

SymptomPossible CauseResolution
401 UnauthorizedExpired or invalid access tokenRefresh the token using the refresh_token endpoint or re‑authenticate.
Invalid client_idIncorrect Consumer Key in env varsVerify the Consumer Key matches the Connected App.
Redirect URI mismatchCallback URL not whitelistedAdd the exact URL to the Connected App OAuth settings.
```