Guide: MuleSoft Integration
Chapter
8

MuleSoft integration with Salesforce: Tutorial & Best Practices

Salesforce is the world’s leading customer relationship management (CRM) system. When integrated with Mulesoft, it unlocks numerous capabilities. Together, they can create a flexible ecosystem to automate repetitive workflows, unlock data across the organization, transfer large volumes of data across enterprises, and enable real-time synchronization with organization-wide systems.

MuleSoft provides an out-of-the-box Salesforce connector that supports a wide range of operations, making it easy to build fast, efficient, secure, and robust integrations. As the building blocks are already available, the time to deliver a production-ready integration is substantially reduced.

This article explains the why, what, and how of integrating Salesforce with MuleSoft.

Summary of key concepts related to MuleSoft integration with Salesforce

Concept Description
Why integrate Salesforce with Mulesoft? Integrating Salesforce with MuleSoft enables real-time data sync between systems and facilitates decision-making.
Connecting to Salesforce Connection methods include basic authentication, OAuth 2.0, and OAuth JWT to support flexible access for different integration needs.
Real-time data sync Using the publish-subscribe model, real-time sync leverages platform events or change data capture to enable instant system updates.
Bulk data processing Bulk data processing supports asynchronous processing of large data volumes using Salesforce Bulk API operations.
Error handling Use a try-catch strategy to handle operation-specific mistakes and ensure reliable communication by managing various error scenarios.
Technical Challenges Technical challenges include various authentication problems and managing relationships between objects in Salesforce while syncing data.
Best practices Best practices include choosing the correct integration pattern, optimizing integrations to avoid bottlenecks, and implementing robust error handling for reliable integrations.

Why integrate Salesforce with MuleSoft?

Integrating Salesforce with MuleSoft can enable data flow between Salesforce and other systems like ERPs, databases, legacy systems, cloud services, and third-party applications. It helps eliminate data silos and automate workflows. MuleSoft's out-of-the-box support for Salesforce helps accelerate development time and efforts. MuleSoft can be used to build real-time and batch synchronizations, enhancing organization-wide decision-making with increased visibility.

API-led connectivity: unlocking data within the organization

API-led connectivity is an architectural style that connects data applications using reusable and purposeful APIs. It enables an efficient and secure approach to integrating systems within an organization. Integrating Salesforce with MuleSoft by creating system APIs as building blocks can unlock the ability to build extensive, complex business processes that interact with Salesforce.

The API-led approach can enable organizations to build more processes and integrations with Salesforce using existing reusable components, such as the system and process APIs.

MuleSoft integration with Salesforce: Tutorial & Best Practices
API-led connectivity (source)

You can use CurieTech’s API Spec Generator tool to further enhance this approach by accelerating the creation of system and process APIs, ensuring consistency, and reducing development time to generate API specifications with simple natural language prompts. CurieTech AI is a specialized AI platform built and optimized for MuleSoft, offering AI agents that help you code, test, and document entire workflows. CurieTech has specialized AI tools to help you create simple, complex integrations with simple prompts.

Let's explore an example of generating a simple API spec to retrieve and create accounts in Salesforce that are secured with client ID enforcement. Once the tool receives and processes the prompt, it generates the complete RAML specification with the specified requirements.

MuleSoft integration with Salesforce: Tutorial & Best Practices

Here is a snapshot of the RAML generated by CurieTech’s API Spec Generator tool.

MuleSoft integration with Salesforce: Tutorial & Best Practices

AI agent integration

AI agent integration in the Agentforce ecosystem within Salesforce can leverage MuleSoft to bridge the gap between autonomous AI agents and enterprise systems. Agentforce agents use natural language processing backed by large language models to process and execute complex business tasks. MuleSoft can enable these agents to interact with other systems and access the required information securely across systems.

For example, MuleSoft can integrate HR and IT systems with AI agents to automate employee onboarding with AI instructions. Salesforce has built-in capabilities to import and connect to MuleSoft APIs from Anypoint Exchange, making the process fast and easy.

Enable real-time data synchronization

MuleSoft has out-of-the-box capabilities to listen and react to real-time Salesforce changes. These capabilities allow MuleSoft to build highly scalable, efficient, and robust integrations requiring real-time data syncing. When combined with MuleSoft’s ability to interact with any system, Salesforce CRM capabilities can unlock immense possibilities.

For example, an e-commerce company must notify customers when their orders ship. MuleSoft can listen to events when an order ships to build this integration with Salesforce. Then it can retrieve the shipping and customer information and push a notification to the customer’s email or phone with the tracking information.

High-volume data migration

In today’s world, new systems are added frequently, catering to specific organizational needs. However, migrating data between systems can be very complex. Tackling relations between various data objects, handling large volumes of data, filtering out unnecessary records, and cleaning up insufficient data can be tremendous obstacles when dealing with data loads. MuleSoft can tackle all these challenges, efficiently handling large volumes of data from one system to another using its batch processing and streaming capabilities.

{{banner-large-graph="/banners"}}

Connecting to Salesforce

MuleSoft supports various authentication methods to connect to Salesforce, enabling secure and quick integration setup. This section examines three authentication methods: basic, OAuth 2.0, and OAuth JWT.

Basic authentication

Basic authentication is the easiest way to connect to Salesforce. It requires an account username, password, and security token. However, this method is considered less secure for production environments, and you should only use it to test connectivity with Salesforce and quickly build proofs of concept.

To start, you only need a security token from Salesforce to set up basic authentication for your account. Follow these steps: 

  1. To obtain the security token, navigate to View Profile -> Settings -> My Personal Information -> Reset my security token -> Click on Reset Security Token. Salesforce will send the security token to your account’s email address.
  2. In the MuleSoft application, create a new Salesforce configuration.
  3. Select Basic Authentication as the connection method.
  4. Enter your account’s username and password along with the security token obtained previously.
  5. Set the authorization URL to https://login.salesforce.com/services/Soap/u/61.0. The URL may differ depending on the Salesforce SOAP service version.
  6. Test the connection once the configuration is complete to ensure it is successful.
MuleSoft integration with Salesforce: Tutorial & Best Practices

OAuth 2.0

OAuth 2.0 is an industry-standard authorization framework that allows third-party applications to securely access users’ resources without exposing their credentials. It uses access tokens issued by an authorization server to grant limited access to APIs or services. Connecting to Salesforce using OAuth 2.0 consists of three steps:

  1. Create a connected app in Salesforce to initiate the OAuth flow on behalf of the MuleSoft application.
  2. Configure the MuleSoft application using Salesforce's connected app credentials.
  3. Authenticate to Salesforce with user credentials and receive the authorization code.

Here’s how to configure MuleSoft, step by step:

  1. In the MuleSoft application, create a new Salesforce configuration.
  2. Select OAuth 2.0 as the connection method.
  3. Configure the consumer key and secret from the connected app created in Salesforce. The authorization and access token URLs are prefilled in the OAuth 2.0 configuration. Change the URLs according to the environment you are connecting to.
  4. For this example, set the resource owner ID to demo. The resource owner ID typically refers to the account's Salesforce username (or user ID) that owns the requested access token.
  5. Now, configure the callback details. Create an HTTP listener config and enter the callback path /callback and authorize path /authorize. The authorization endpoint initiates the authorization process with Salesforce from MuleSoft, and the callback endpoint receives the authorization code back from Salesforce after successful authorization.
  6. Configure the external callback URL. It should be the same URL as the one configured in Salesforce's connected app: http://localhost:8082/callback.
  7. By default, Mule stores the obtained access tokens in the app’s default object store, but you can define a custom object store to store access tokens, as in the following example.
MuleSoft integration with Salesforce: Tutorial & Best Practices
  1. When running the app for the first time, you must obtain the authorization code from Salesforce. Call the URL configured in the OAuth config; in this case, the URL configured is http://localhost:8082/authorize. Note that this only needs to be performed when initializing the app for the first time. The Salesforce connector will then automatically refresh the token after it expires.
  2. This URL redirects to the Salesforce login page. Enter the account credentials to authenticate. Once the OAuth dance is complete, the authorization code is handed over to the application using the configured callback URL. The authorization code will be used for subsequent requests.
MuleSoft integration with Salesforce: Tutorial & Best Practices

You can use CurieTech’s Code Enhancer tool to create connections or update your existing connections to OAuth 2.0 with simple natural language prompts.

Here's an example of how the Code Enhancer can update all Mule flows with minimal effort. Upload the code package and specify the required enhancements. In this case, the goal is to replace the existing authentication with OAuth 2.0 in all relevant flows.

MuleSoft integration with Salesforce: Tutorial & Best Practices

After submitting the task, Code Enhancer finds the references to existing Salesforce connections in all files and replaces them with the new OAuth 2.0 config.

MuleSoft integration with Salesforce: Tutorial & Best Practices

OAuth JWT

OAuth 2.0 with JSON Web Token (JWT) uses JWTs as access tokens to transmit claims between parties securely. These digitally signed tokens allow the resource server to verify authenticity and user permissions without calling the authorization server. Connecting to Salesforce using OAuth JWT consists of three steps:

  1. Create a signed certificate.
  2. Create a connected app in Salesforce using the signed certificate.
  3. Configure the MuleSoft application with the connected app credentials from Salesforce and the keystore version of the certificate.

Here are the specific MuleSoft configuration steps:

  1. In the MuleSoft application, create a new Salesforce configuration.
  2. Select OAuth JWT as the connection method.
  3. Enter the consumer key from the connected app created in Salesforce.
  4. Provide the path to the JKS keystore generated previously and used in the connected app in Salesforce. Remember: This should be the generated key pair and exported in JKS format.
  5. Enter the keystore password and alias.
  6. Fill in the principal details; this should be the username of the account used to create the connected app.
  7. Set the token endpoint according to the Salesforce environment you are working with. This example uses https://login.salesforce.com/services/oauth2/token.
MuleSoft integration with Salesforce: Tutorial & Best Practices
  1. Test the connection once the configuration is complete to check if it is successful.

Real-time data sync

Real-time data sync is ideal for cases requiring instant updates and consistent information across systems. For example, customer data must remain synchronized between Salesforce and an ERP system to prevent mismatches. Salesforce supports real-time integration through two powerful event-driven features: 

  • Change Data Capture (CDC) in Salesforce lets you track and capture changes to Salesforce records in real time, such as create, update, delete, and undelete operations. It's helpful in syncing data across systems.
  • Platform events are custom event messages used for event-driven architecture in Salesforce. They enable apps to communicate asynchronously inside and outside Salesforce and support publish-subscribe messaging patterns.

To implement real-time sync with Salesforce using MuleSoft, follow these steps:

  1. Create a platform event in Salesforce and trigger it based on business requirements. Platform events exchange real-time data within and between Salesforce and external platforms.
    Salesforce creates a platform event for the change, acting as an event producer, and it gets added onto the event bus, which acts as a queue, executing events one after another in order. Event subscribers subscribe to the event from the event bus, acting on the changes from Salesforce.
  1. Subscribe to the platform event in MuleSoft and execute the necessary business logic.

The following guide walks you through an example of building a real-time sync using MuleSoft. The integration listens for new account record creations in Salesforce, retrieves the necessary fields, and inserts the data into a database.

MuleSoft can be configured to subscribe to the platform event and execute the required business process. This flow subscribes to the platform event triggered on new account creation, retrieves the required fields from Salesforce, and inserts them into a database table: account.

  1. First, create a database table account with fields Account SF ID, Name, and Phone to house data coming from Salesforce.
MuleSoft integration with Salesforce: Tutorial & Best Practices
  1. To subscribe to the platform event from Salesforce, create a new flow in the Mule application and drag the SF: Subscribe Channel Listener component from the SF connector; this will be the source of the flow. This component listens to any events on the channel it subscribes to.
  2. Configure the streaming channel for the platform event set up in Salesforce. (The Platform Event should already be available if metadata is loaded in Anypoint Studio; simply select the correct platform event.)
  3. In this example, three fields—Account SF ID, Name, and Phone—are synced to the database. Salesforce triggers the platform event, and the Mule application receives it with the account ID (configured when publishing from the Salesforce flow). You can then use the account ID to retrieve the three fields from Salesforce.
  4. Add SF: Query operation to the flow, which retrieves the Account SF ID, Name, and Phone values based on the record account ID from Salesforce.
MuleSoft integration with Salesforce: Tutorial & Best Practices
  1. After this operation, the details to be inserted into the database are available. Transform the payload per the database table fields and configure the DB: Insert operation to insert the data into the database.
MuleSoft integration with Salesforce: Tutorial & Best Practices
MuleSoft integration with Salesforce: Tutorial & Best Practices
  1. Run the application and test the flow by creating a new account record in Salesforce.
  2. The platform event will be triggered and received in MuleSoft, inserting the data into the Database table account.
MuleSoft integration with Salesforce: Tutorial & Best Practices

You may have noticed that the flow is missing details like error handling, operation-level connection retries, and a redelivery policy for the channel listener. With AI tools such as CurieTech’s Code Enhancer, you can easily find and fix such omissions through AI.

The following example uses CurieTech’s Code Enhancer tool. The code package is provided, and a step-by-step prompt is added in the description box, describing what needs to be enhanced. Error handling, operation-level retries, and a redelivery policy for the channel listener need to be added to the real-time sync flow.

MuleSoft integration with Salesforce: Tutorial & Best Practices

After submitting the task, CurieTech’s Code Enhancer successfully generated the new files with the enhanced code changes. It added the redelivery policy to the Salesforce channel listener.

MuleSoft integration with Salesforce: Tutorial & Best Practices

It also updated the SF: Query operation to include reconnection configuration with externalized properties.

MuleSoft integration with Salesforce: Tutorial & Best Practices

In addition, it added the error handler to gracefully handle errors, with standard logging messages for each error.

MuleSoft integration with Salesforce: Tutorial & Best Practices

Here is how the flow looks when imported into Anypoint Studio. As instructed, CurieTech’s Code Enhancer updated the flow with all points.

MuleSoft integration with Salesforce: Tutorial & Best Practices

{{banner-large="/banners"}}

Bulk data processing

Building synchronous processes for large-volume data migrations can stress the systems, causing overload and inefficiency. This is where bulk data processing comes into the picture. It is ideal for migrating large amounts of data between systems or syncing high-volume data regularly. 

Salesforce provides bulk data APIs based on REST principles, which are optimized for working with large data sets. Salesforce says any data operation, including more than 2000 records, is a good candidate for bulk operations to execute and manage the workflow asynchronously.

The following example uses a scheduled flow running at a fixed frequency. It then retrieves the data from the file and pushes it to Salesforce by creating a bulk job.

A CSV file is the data source containing three fields: Record ID, Account Name, and Account Phone. This data is read in MuleSoft using the file read operation.

MuleSoft integration with Salesforce: Tutorial & Best Practices

After reading the file, the data is transformed according to Salesforce. The transformation has deferred set to true, enabling data streaming while transforming. This is important when handling massive amounts of data between systems. Streaming helps avoid memory overload by efficiently streaming data into memory from disk.

%dw 2.0
output application/csv lineSeparator = "\n", deferred = true, quoteValues = true
---
(payload default []) map((item, index) -> {
	Name: item.Name,
	Phone: item.Phone
})

MuleSoft supports Salesforce bulk API operations. To create a bulk job, use the Create Bulk Job API V2 operation. This operation accepts data in CSV format and can be configured to insert/update/delete records for any of Salesforce's objects.

This example configures the operation to insert account records in Salesforce. The external ID field name must be configured when performing operations that require an external ID to identify existing records in Salesforce, like updating or deleting.

<salesforce:create-job-bulk-api-v2 
	objectType="Account" 
	operation="insert" 
	doc:name="SF: Create Account Bulk Job" 
	doc:id="d30a21af-2328-4112-a20a-77c7510a9043" 
	config-ref="salesforce-config-jwt" 
	externalIdFieldName="Id">
	<reconnect />
</salesforce:create-job-bulk-api-v2>

A job ID is returned once the batch job is created in Salesforce. This is the unique identifier for the job, which can be used to track its status and perform operations on it.

Here is the complete flow for creating a bulk job in Salesforce.

MuleSoft integration with Salesforce: Tutorial & Best Practices

Bulk job creation flow in Salesforce.

Error handling

MuleSoft can catch, categorize, and handle error types such as authentication failures, validation issues, or network timeouts. Effective error handling can minimize downtime and ensure smooth processing between flows. This topic covers handling both fatal and non-fatal Salesforce errors.

Handling fatal Salesforce errors

Here are some of the errors Salesforce can generate, failing the current transaction in progress:

  • SALESFORCE:INVALID_INPUT: The input request or query data is invalid. Salesforce returns the exact reason for the error in the response.
  • SALESFORCE:CONNECTIVITY: The connection with Salesforce could not be established due to an error. Make sure to configure operation-level retries to retry the connection attempts.
  • SALESFORCE:LIMIT_EXCEEDED: The request exceeds the specified limit. For example, sending a request to Salesforce to create over 200 account records will throw the limit exceeded error.
  • SALESFORCE:TIMEOUT: A specific request takes longer than a configured amount of time to complete. You can configure retries using the until-successful component or increase the configured timeout parameter per the operation requirements.

Use a try-catch strategy to handle operation-specific mistakes, and a standard error handler to capture the mistakes not specific to the operation. Here is an example for catching the SALESFORCE: INVALID_INPUT error.

MuleSoft integration with Salesforce: Tutorial & Best Practices

Here is the DataWeave script to extract error details. This DataWeave script can catch any errors from Salesforce and be expanded to include more information.

%dw 2.0
output application/json
---
{
	namespace: error.errorType.namespace,
	errorType: error.errorType.identifier,
	description: error.description,
	failingComponent: error.failingComponent
}


Here’s the DataWeave error response.

{
  "namespace": "SALESFORCE",
  "errorType": "INVALID_INPUT",
  "description": "Invalid ID field = 1",
  "failingComponent": "sf-extract-data-flow/processors/1 @ sf-sync-app:extract-and-upsert.xml:17 (SF: Retrieve Account Data)"
}

Handling non-fatal Salesforce errors

When operating Salesforce with multiple records in a single transaction, some records might be successful while others might fail. In such scenarios, Salesforce doesn’t fail the whole transaction; instead, it returns which records succeeded and failed in the response. Salesforce contains an error object in the response for each record for failed records, containing the error code and error message. 

Here is a DataWeave example that extracts the errors from the Salesforce response for account records failing due to the Name field not being present in the request payload. This DataWeave script will work to extract any soft errors from the Salesforce response and can be expanded as needed.

%dw 2.0
output application/json
---
payload.items map {
	id: $.id, // Salesforce ID of the record
	success: $.successful, // Was the operation successful for this record?
	errors: $.payload.errors map {
		code: $.statusCode, // Error status code
		message: $.message // Error description
	}
}

Here is the DataWeave error response.

[
  {
    "id": null,
    "success": false,
    "errors": [
      {
        "code": "REQUIRED_FIELD_MISSING",
        "message": "Required fields are missing: [Name]"
      }
    ]
  },
  {
    "id": null,
    "success": false,
    "errors": [
      {
        "code": "REQUIRED_FIELD_MISSING",
        "message": "Required fields are missing: [Name]"
      }
    ]
  }
]

Technical challenges

Technical challenges often arise when integrating with Salesforce. Authentication can be challenging due to configuration and permission issues. Managing relationships between objects, especially lookup and master detail relationships, requires understanding Salesforce’s data model and proper sequencing of data operations to maintain referential integrity.

Authentication challenges

Authentication challenges can arise due to incorrectly configured connected apps or invalid credentials. These issues can lead to token refresh failures or unauthorized access errors while connecting to Salesforce.

Ensuring proper end-system configuration, including error handlers, is essential for maintaining reliable connectivity and avoiding authentication issues. Here are some common specific authentication challenges while setting up OAuth configurations:

  • Audience is invalid in OAuth JWT connection: This issue can occur when the audience URL is invalid in the Salesforce connector config. Use the correct audience URL for the environment, such as https://login.salesforce.com, https://test.salesforce.com, or a Salesforce org-specific URL.
  • User hasn't approved this consumer in OAuth JWT connection: This error may happen when connected app permissions are not configured correctly. To resolve this, follow these steps: 
    • Under the profiles section, assign the System Administrator profile. Navigate to Setup -> Apps -> App Manager -> Select Connected App -> Manage -> Profiles -> Assign System Administrator.
    • Also, navigate to the Edit Policies section. Under the Permitted Users tab, select Admin-approved user pre-authorized and save.
  • OAuth authorization dance has not yet been performed for resourceOwnerId: This error occurs when the call to the actual Salesforce resource is made without authorizing the Mule application first. When running the application for the first time, allow the Mule application by calling the /authorize endpoint.

Managing relationships between objects in Salesforce

There are scenarios when objects in Salesforce have relationships with each other. For example, assume there is an existing integration where Salesforce syncs records with a database with its unique ID per record. The ID syncs back to Salesforce (DB_Account_ID__c) to identify records in Salesforce using the database account ID uniquely. Now, there is a new requirement to sync contact records to Salesforce from the database, which is linked to an account with a unique account ID as the foreign key.

While pulling the record from the database, you have the database account ID, which can link the correct account record to the contact using it as an external ID. Here is how it can be done using DataWeave:

%dw 2.0
output application/json
---
{
  // Relationship name in contact object
   Account: {
        // External ID field used to identify the account record
        DB_Account_ID__c: payload.accountId
    }
}

Best practices

When integrating Salesforce with MuleSoft, sticking to best practices makes your integrations easier to maintain, more scalable, and less likely to break. Picking the correct pattern from the start and optimizing the flows helps avoid headaches later. Good error handling means you’re not left guessing when something goes wrong, and documenting what you build saves a ton of time, especially when someone new joins the team or something needs to be fixed.

To support adherence to best practices in MuleSoft code, you can use CurieTech’s Single Repo Code Lens agent to analyze MuleSoft automatically flows for quality, security, and maintainability. Using a simple prompt, the agent provides detailed findings, reasoning, and code recommendations to improve the code.

In the example below, the tool flags hardcoded credentials, inadequate error handling, excessive logging, and a lack of test coverage for the provided flow. These insights can help proactively identify and remediate issues early in the development lifecycle.

MuleSoft integration with Salesforce: Tutorial & Best Practices

 

MuleSoft integration with Salesforce: Tutorial & Best Practices

The following sections highlight specific best practices for MuleSoft development.

Choose the correct integration pattern

While building integrations with Salesforce, it's essential to identify and choose the correct integration pattern. Building deep into the wrong integration pattern can cause significant issues with scaling and efficiency, leading to high costs in terms of development effort and time.

You can choose from multiple integration patterns, depending on the requirements. Here are some examples:

  • Request and reply: This integration pattern can be used when you need to initiate a process in a remote system with the required information, receive a response from the system, and then use it to update information in Salesforce. For example, Salesforce can call a MuleSoft API connecting to the remote system to create an order, get the response back, and update the order number from the system back to Salesforce.
  • Fire and forget: The system initiates a request to the remote system but doesn’t wait to complete it. Use this pattern when the calling system doesn’t have to wait for the transaction to complete. For example, Salesforce calls a MuleSoft API to connect to the remote system to create an order, but doesn’t wait for the order. The remote system can optionally call Salesforce back in a separate transaction to update the order number.
  • Batch data synchronization: Use batch data syncs to sync large amounts. Handling large data sets requires efficiently pulling/transforming/pushing data, as doing so can easily overload the applications and cause them to fail.
  • Pub-sub model: The publisher-subscriber model can decouple the sender and receiver, enabling the subscriber to react to changes in Salesforce in real time. For example, MuleSoft can listen to any new orders created in Salesforce and sync them to the remote system in real time using Salesforce platform events.

Optimize integrations

While building integrations, continuously optimize your integrations for performance and scalability to avoid bottlenecks. Unoptimized integrations tend to fail fast when scaled for higher transaction volumes. Utilizing capabilities like streaming for large payloads, caching, reusable flows, and connection pooling to reuse connections can largely optimize integrations. Also, use the Mule execution engine to your advantage by combining expensive operations and optimizing DataWeave operations.

Implement a robust error-handling framework

Implementing effective error-handling strategies is essential to building sustainable and resilient integrations in MuleSoft. Here are some best practices for error handling:

  • Use global error handlers: Define global error handlers to catch and report common errors that remain uncaught at the flow level. Build a notification system to notify the concerned point of contact when an error occurs. This can help significantly narrow down issues and let you fix them quickly.
  • Follow a standard error structure: Define a typical structure to log and propagate errors. A clear structure helps identify the error type and reason quickly. Define error codes to identify different errors and log and route errors intelligently.
  • Implement retries: Use retry scopes for intermittent connection errors and configure reconnection strategies on components where they’re supported, like Salesforce operations. Use the until-successful component to add retries while connecting to end systems.
  • Use transaction management: Implement transaction management to maintain data integrity across systems. Wrap components in a single transaction where multiple operations must occur as a whole or not occur at all.

CurieTech’s AI tools can enhance already built flows with a robust error-handling framework that captures errors, transforms them to a standard format, and pushes the notification to an external service like Slack for error reporting. To demonstrate, let's build an error handler using CurieTech’s Integration Generator tool, with a step-by-step prompt on how the error handler functions.

MuleSoft integration with Salesforce: Tutorial & Best Practices

Integration Generator generates the standard error handler flow that captures connectivity errors for HTTP, Salesforce, and the database, along with transformation errors. It converts these to a standard format and pushes them to a Slack channel for error reporting.

MuleSoft integration with Salesforce: Tutorial & Best Practices

Here is how the flows look after being imported into the Anypoint Studio.

The standard error handler flow captures all the specified errors using dedicated error strategies, logs the details, invokes the process, and notifies the error sub-flow.

MuleSoft integration with Salesforce: Tutorial & Best Practices

The process and notify flow creates a standard error format with all the required details, builds a payload for a Slack notification request, and pushes the notification to Slack by calling Slack’s chat.postMessage API.

MuleSoft integration with Salesforce: Tutorial & Best Practices

Here’s the DataWeave script for the standard error structure generated by the AI tool:

%dw 2.0
output application/json
var errorTypeToHttpCode = {
  "HTTP:CONNECTIVITY": 503,
  "HTTP:BAD_REQUEST": 400,
  "HTTP:NOT_FOUND": 404,
  "HTTP:METHOD_NOT_ALLOWED": 405,
  "HTTP:UNAUTHORIZED": 401,
  "HTTP:FORBIDDEN": 403,
  "SALESFORCE:CONNECTIVITY": 503,
  "SALESFORCE:INVALID_INPUT": 400,
  "DB:CONNECTIVITY": 503,
  "DB:BAD_SQL_SYNTAX": 400,
  "MULE:EXPRESSION": 500,
  "MULE:TRANSFORMATION": 500
}
var errorSource = vars.errorSource default "Unknown"
---
{
  errorType: error.errorType.asString,
  errorDescription: error.description,
  failingComponent: error.failingComponent,
  errorSource: errorSource,
  httpStatusCode: errorTypeToHttpCode[error.errorType.asString] default 500,
  timestamp: now()
}

Document the integration process

Document all the integration processes with high-level and low-level designs, clearly explaining the integration.

  • Requirements document: This document captures all the integration requirements, acceptance criteria, and high-level designs of the use cases in development.
  • Solution architecture document: This file contains the complete solution architecture for the integrations, with low-level designs and step-by-step process details, along with any assumptions or critical decisions taken while building the integrations.
  • Release notes document: This contains the release process of the integrations, from building the deployable archive to deployment using manual or automated methods.

Also, document any processes specific to the integration, like refreshing tokens for certain systems, turning features on or off on demand, etc. This will help onboarding new team members quickly and make sharing knowledge easier during handover sessions.

Nowadays, with AI agents such as CurieTech’s Document Generator, it has become extremely easy to automatically generate documentation for the provided flows. This example uses the real-time sync flow to create a Sequence diagram and a Flow diagram, along with complete documentation for the flow utilizing the document generator agent.

MuleSoft integration with Salesforce: Tutorial & Best Practices

Below is the sequence diagram that CurieTech’s Document Generator generated based on the provided flow. This diagram explains the end-to-end workings of the real-time sync, picking up even the granular details from the flow.

MuleSoft integration with Salesforce: Tutorial & Best Practices
Sequence diagram for real-time sync flow

Here is another task snapshot with the detailed steps from the Document Generator response.

MuleSoft integration with Salesforce: Tutorial & Best Practices

{{banner-large-table="/banners"}}

Conclusion

In this article, we discussed integrating Salesforce with Mulesoft in detail, covering everything from connecting to Salesforce to handling different integration scenarios. Utilizing MuleSoft’s capabilities to build real-time integrations and bulk data processes lets organizations create efficient, scalable, and secure integrations to support their data needs. Leveraging MuleSoft empowers organizations to unlock Salesforce's full potential as a CRM, enabling data-driven decisions across teams and sustainable growth.

Continue reading this series