Nav

Salesforce Connector

Select

The Anypoint Salesforce Connector lets you connect to the Salesforce platform APIs. This connector exposes methods for accessing Salesforce, including working with the Salesforce Apex classes.

This connector works with the Salesforce SOAP API, REST API, Bulk API, and Streaming API, depending on the operation you configure. Each API call uses an XML request and response over an HTTPS connection. All required request headers, error handling, and HTTPS connection configurations are built into the connector.

There are three ways to use a Salesforce connector in your application: as an outbound connector, an inbound connector, or a streaming inbound connector. These are discussed later in this document.

Prerequisites

This document assumes that you are familiar with Salesforce, HTTP, SOAP, REST, Bulk and Streaming APIs, Mule, Anypoint Connectors, Anypoint Studio, Mule concepts, elements in a Mule flow, and Global Elements.

Requirements for using the connector:

  • Salesforce developer account.

  • Security token - You can receive a new security token by email if you run Reset Security Token through My Personal Information from the Salesforce Setup pages.

  • Consumer key and Secret - Required if you are using the OAuth API. 

  • Namespace and schema location: If you plan to create the XML for your Mule application by hand, you need to include the correct namespace and schema location in your XML file. Anypoint Studio adds this information to the XML file automatically when you add the Salesforce connector to a flow in a Mule app.

Notes:

Developing an Application

Build an application in this order:

  1. Configure the connector.

  2. Test the connection.

  3. Build the rest of your flow.

  4. Add and configure DataWeave.

When developing an app, the Salesforce connector provides these integration patterns you can use with the Salesforce APIs:

  • Batch Data Synchronization - An external system accesses, changes, deletes, or adds data in Salesforce in batches, and vice versa (Salesforce to external system).

  • Remote Call-In - An external system accesses, changes, deletes or adds data in Salesforce, and vice versa (Salesforce to external system).

  • Fire and Forget Remote Process Invocation - Salesforce initiates a process in a third-party system and receives an acknowledgment that the process has started. The third-party system continues processing independent of Salesforce.

  • Request-Reply Remote Process Invocation - Salesforce kicks off a process in a remote system, waits for the remote system to finish processing, then accepts control back again from the remote system.

  • User Interface Update Based on Data Changes - The Salesforce UI updates in response to a change in a third-party system.

The Salesforce connector works with these APIs:

Apex SOAP API:

The Salesforce Apex SOAP API exposes Apex class methods as custom SOAP Web service calls. This allows an external application to invoke an Apex Web service to perform an action in Salesforce.

SOAP API:

The Salesforce SOAP API provides secure access to your organization’s information on Salesforce. Most of the operations that the Salesforce connector performs map to this API.

All the Salesforce operations performed through the SOAP API have an optional parameter called "Headers" that can take any of the following Salesforce SOAP Headers: AllOrNoneHeader, AllowFieldTruncationHeader, AssignmentRuleHeader, CallOptions, EmailHeader, LocaleOptions, MruHeader, OwnerChangeOptions, QueryOptions, UserTerritoryDeleteHeader, DuplicateRuleHeader

Apex REST API:

The Salesforce Apex REST API creates your own REST-based web services using Apex. It has all of the advantages of the REST architecture, and provides the ability to define custom logic and includes automatic argument/object mapping.

Bulk API:

The Salesforce Bulk API quickly and securely load batches of your organization’s data into Salesforce. See also: Loading Data in Batches.

Streaming API:

The Salesforce Streaming API securely receives notifications for changes to your organization’s information in Salesforce. See Receiving Inbound Data From Salesforce for more information on the use of the Streaming API.

Metadata API

The Salesforce Metadata API manages customizations and build tools that work with the metadata model, not the data itself.

Configuring in Design Center

  1. In Anypoint Platform > Design Center, click Create > Mule Application.

  2. Click a trigger to initiate access to your flow. To have Salesforce send content to your application, select Salesforce as the trigger and choose one of the following triggers:

    Triggers in Design Center

    • New Object - Create a new object. Possible object types are Contact, Lead, Account, Contracts, Opportunity, and custom objects. The object types correspond to the Salesforce object you want to create, modify, or delete.

    • Modified Object - Modify an object.

    • Deleted Object - Delete an object.

    • Replay Channel - Subscribe to a streaming channel. This trigger provides channel-related notification settings for new events and events stored by Salesforce within the 24-hour retention period. Events that take place in the specified channel trigger the flow.

      Note: A channel or topic must be published to Salesforce before a subscription to the channel can be created.

    • Replay Topic - Subscribe to a topic. This trigger provides topic-related notification settings for new events and events stored by Salesforce within the 24-hour retention period. Events that take place on records in the specified topic trigger the flow.

    • Subscribe Channel - Subscribe to a streaming channel. This trigger provides channel-related notification settings for new events that take place after you subscribe.

    • Subscribe Topic - Subscribe to a topic. This trigger provides topic-related notification settings for new events that take place after you subscribe.

      Alternatively, you can use an HTTP Listener or Scheduler trigger.

Configuring a Salesforce New Object Trigger

The following shows how to configure the Salesforce New Object trigger.

  1. Create a New Mule Application in Design Center.

  2. Set the trigger. For example, you can use Salesforce > New Object.

  3. Click Set up.

    New Object Configuration Screen

  4. Specify the Connection Type:

    Authentication Options

    Connection Type Salesforce Information Site

    Username Password

    SOAP API Username Password Login

    OAuth 2

    OAuth 2.0 Web Server Authentication Flow

    OAuth JWT

    OAuth 2.0 JWT Bearer Token Flow

    OAuth SAML

    OAuth 2.0 SAML Bearer Assertion Flow

    OAuth Username Password

    OAuth 2.0 Username-Password Flow

  5. Specify the parameters as required for each configuration type, and click Test to ensure you have a valid connection to Salesforce.

  6. If needed, configure the Apex tab to decide what metadata to fetch, and to add Apex class names.

    Apex configuration screen

  7. If you haven’t specified a Connection Type, and if needed, configure the Advanced tab to set the Max Idle Time and Time Units for how long to hold open a connection before it expires.

    Advanced Tab when no Connection Type specified

    After you specify a Connection Type, if needed, you can use the Advanced tab to change values for the Reconnection Strategy, Pooling Profile, and Expiration Policy.

    Advanced Tab for Connection Type

  8. If needed, set the Redelivery Policy on the main Configuration screen. Redelivery indicates the maximum number of tries to deliver trigger content.

    Redelivery Policy

Configuring Salesforce as a Component

After creating a trigger, click the plus sign. If needed, click Transform to use DataWeave to map fields between your received data and what to use with your Salesforce component.

The following are examples of the operations in the Salesforce component:

Create:

sfdc-create

Query:

  • Salesforce Query: Salesforce query to retrieve objects.

  • Parameters: Values for placeholders in the Salesforce query.

sfdc-query

Update:

sfdc-update

Delete:

sfdc-delete

Configuring Username Password Authorization

  • Username: Enter the Salesforce username.

  • Password: Enter the corresponding password.

  • Security Token: Enter the corresponding security token.

Implementing OAuth 2.0-based authentication mechanisms involves extra steps, but may be preferred if your service is exposed to external users, as it ensures better security.

Username Password Configuration

Configuring OAuth v2.0 Authorization

  • Display: How to optimize the display: PAGE = Full-page authorization screen (default), POPUP = Compact dialog optimized for modern web browser popup windows, and TOUCH = Mobile-optimized dialog designed for modern smart phones, such as Android and iPhone.

  • Consumer Key: The consumer key for the Salesforce connected app. See Creating a Consumer Key.

  • Consumer Secret: The consumer secret for the connector to access Salesforce.

  • Listener Config: Configuration for the listener, for example, HTTP_Listener_config.

  • Callback Path: Path for the callback, for example, /callback

  • Authorize Path: Path for authorization, for example, /authorize

  • External Callback URL: Callback URL, for example, http://localhost:8085/callback

OAuth v2.0 Configuration

Configuring OAuth JWT Authorization

  • Consumer Key: The consumer key for the Salesforce connected app. See Creating a Consumer Key.

  • Key Store: The path to the key store used to sign data during authentication. Only Java key store format is allowed. See Generating a Keystore File.

  • Store Password: The password for the keystore.

  • Principal: The Salesforce username that you want to use.

OAuth JWT Configuration

Configuring OAuth SAML Authorization

  • Consumer Key: The consumer key for the Salesforce connected app. See Creating a Consumer Key.

  • Key Store: The path to the key store used to sign data during authentication. Only Java key store format is allowed. See Generating a Keystore File.

  • Store Password: Key store password

  • Principal: Username of desired Salesforce user

OAuth SAML Configuration

Configuring OAuth Username Password Authorization

  • Consumer Key: The consumer key for the Salesforce connected app. See Creating a Consumer Key.

  • Consumer Secret: The consumer secret for the connector to access Salesforce.

  • Username: Enter the Salesforce username.

  • Password: Enter the corresponding password.

  • Security Token: Enter the corresponding security token.

    OAuth User Password

Installing and Configuring in Studio

  1. In Anypoint Studio, click the Exchange icon in the Studio taskbar.

  2. Click Login in Anypoint Exchange.

  3. Search for this connector and click Install.

  4. Follow the prompts to install this connector.

When Studio has an update, a message displays in the lower right corner, which you can click to install the update.

To configure:

  1. Drag and drop the connector to the Studio Canvas.

  2. To create a global element for the connector, set these fields:

    Username Password Authentication:

    • Username: Enter the Salesforce username.

    • Password: Enter the corresponding password.

    • Security Token: Enter the corresponding security token.

      Studio Username Password Authentication

      OAuth v2.0:

    • Display: How to optimize the display: PAGE = Full-page authorization screen (default), POPUP = Compact dialog optimized for modern web browser popup windows, and TOUCH = Mobile-optimized dialog designed for modern smart phones, such as Android and iPhone.

    • Consumer Key: The consumer key for the Salesforce connected app. See Creating a Consumer Key.

    • Consumer Secret: The consumer secret for the connector to access Salesforce.

    • Listener Config: Configuration for the listener, for example, HTTP_Listener_config.

    • Callback Path: Path for the callback, for example, /callback

    • Authorize Path: Path for authorization, for example, /authorize

    • External Callback URL: Callback URL, for example, http://localhost:8085/callback

      Studio OAuth 2

      OAuth 2 JWT:

    • Consumer Key: The consumer key for the Salesforce connected app. See Creating a Consumer Key.

    • Key Store: See Generating a Keystore File.

    • Store Password: The password for the keystore.

    • Principal: The password for the keystore.

      Studio OAuth 2 JWT

      OAuth 2 SAML:

    • Consumer Key: The consumer key for the Salesforce connected app. See Creating a Consumer Key.

    • Key Store: See Generating a Keystore File.

    • Store Password: The password for the keystore.

    • Principal: The password for the keystore.

      Studio OAuth 2 SAML

      OAuth Username and Password:

    • Consumer Key: The consumer key for the Salesforce connected app. See Creating a Consumer Key.

    • Consumer Secret: The consumer secret for the connector to access Salesforce.

    • Username: Enter the Salesforce username.

    • Password: Enter the corresponding password.

    • Security Token: Enter the corresponding security token.

      Studio OAuth 2 Username and Password

  3. Based on the operation that you have dragged on the canvas configure the following fields:

    Create:

    • Type: Salesforce object type.

    • Records: Function editor expression.

      sfdc-create

      Query:

    • Salesforce Query: Salesforce query to retrieve objects.

    • Parameters: Values for placeholders in the salesforce query.

      sfdc-query

      Update:

    • Type: Salesforce object type.

    • Records: Function editor expression to produce a collection of Salesforce objects to be updated.

      sfdc-update

      Delete:

    • Records To Delete Ids: Function editor expression to produce a collection of Salesforce objects to be deleted.

      sfdc-delete

Keeping a Session Alive

For the Mule 4 Salesforce Connector, for all the configurations except OAuth v2, you have the option to keep the session alive until it expires by setting the Disable session invalidation field.

The Mule app controls the lifecycle connections. When the app determines that a given connection is not needed anymore, it checks the setting of Disable Session Invalidation. When the setting is False (the default), the connector automatically destroys the connection for the session. To prevent a session from closing in this case, you can set the Disable Session Invalidation field to True or provide a function expression.

Salesforce uses the same session for all your threads, so for example, if your session is active and you log in again, Salesforce uses the existing session instead of creating a new one.

If the Disable session invalidation field is set to False, the connector automatically destroys the session after it’s no longer needed.

You should keep the session alive when you are working with threads or concurrency in general. Salesforce uses the same session for all your threads (for example, if you have an active session and you log in again, Salesforce uses the existing session instead of creating a new one). To make sure the connection doesn’t close when a thread is finished, you should set the Disable session invalidation field to True in the Connection section of the connector’s global element properties.

Disable Session Field

Setting Apex and Proxy

The Invoke Apex REST and Invoke Apex Soap methods work with Apex Class Name settings. When you connect to Salesforce, the Salesforce connector gets the names of the Apex classes and methods belonging to them that can be invoked.

All Salesforce connection configurations support these Apex settings:

  • Fetch All Apex SOAP Metadata - Fetches the metadata of all the Apex SOAP classes. Takes precedence over Apex Class Name settings.

  • Fetch All Apex REST Metadata - Fetches the metadata of all the all Apex REST classes. Takes precedence over Apex Class Name settings.

  • Apex Class Name - List of Apex class names to use for limiting the set of classes you fetch along with the methods they expose. This setting can speed the fetch process if there are a lot of classes that you do not need to fetch.

You can set Apex and Proxy settings in Design Center and in Anypoint Studio 7.

Configure the Apex and Proxy Settings:

Apex Settings values:

  • Fetch All Apex SOAP Metadata - Fetches the metadata of all the Apex SOAP classes.

  • Fetch All Apex REST Metadata - Fetches the metadata of all the all Apex REST classes.

Apex Class Name:

  • None - No Apex class name is mentioned for DataSense to acquire.

  • From Message - Lets you specify the class name from a MEL expression.

  • Create Object manually - A user creates a list and adds class names to the list - only those classes and their methods are acquired by DataSense.

    The Fetch All Apex SOAP Metadata and Fetch All Apex REST Metadata check boxes take precedence over the Apex Class Name settings. If these boxes are selected, they fetch all the Apex SOAP metadata or Apex REST metadata regardless of your selection in the Apex Class Names section.

Proxy Settings values:

  • Host - Host name of the proxy server.

  • Port - The port number the proxy server runs on.

  • Username - The username to log in to the server.

  • Password - The corresponding password.

After configuring, click OK.

In the Mule Palette, choose a Salesforce connector operation.

Creating a Consumer Key

A consumer key is required when setting up OAuth 2.0 configurations for the Salesforce connector. It is used by the OAuth 2.0 JWT and SAML bearer configurations and by the OAuth 2.0 Username Password configuration.

This procedure provides guidance on using Salesforce to create a consumer key. It explains how to create a connected app in Salesforce. However, note that the steps might differ somewhat in your Salesforce instance

Prerequisite:

This procedure assumes that you already have a certification file (such as salesforce-cert.crt). If not, you can produce one by generating a Java KeyStore and Public Key.

  1. Log into Salesforce, and go to Setup > Build > Create > Apps.

  2. Under the Connected App section, click New.

  3. Follow these steps to create a new connected app, and enter the following information in the appropriate fields:

    • A name for the connected app.

    • The API name.

    • Contact email.

  4. Under API (Enable OAuth Settings), select Enable OAuth Settings:

    • Enter the Callback URL.

    • Select the Use Digital Signatures checkbox.

    • Click Browse (or Choose File), and load your Salesforce certificate (for example, salesforce-cert.crt), which contains your public key.

      In Studio, you typically store this in the workspace that contains your Mule application.

  5. Add and Save these OAuth scopes to Selected OAuth Scopes:

    Full Access (full) and Perform Requests On Your Behalf At Any Time (refresh_token, offline_access)

  6. Configure the Authorization Settings for the app:

    Click Manage. Then under the OAuth Policies section, expand the Permitted Users dropdown, and select Admin Approved Users are Pre-Authorized. Then Save.

  7. Under the Profiles section, click Manage Profiles.

  8. Select your user profile, and then click Save.

  9. Go back to the list of Connected Apps: Build > Create > Apps.

  10. Under the Connected Apps section, select the connected app you created.

You can see the Consumer Key that you need to provide in your connector’s configuration.

Generating a Keystore File

The Keystore is the path to the keystore used to sign data during authentication. Only Java keystore format is allowed.

To generate a keystore file:

  1. Go to your Mule workspace, and open the command prompt (for Windows) or Terminal (for Mac).

  2. Type keytool -genkeypair -alias salesforce-cert -keyalg RSA -keystore salesforce-cert.jks and press enter.

  3. Enter the following:

    • Password for the keystore.

    • Your first name and last name.

    • Your organization unit.

    • Name of your city, state, and the two letters code of your county.

      The system generates a java keystore file containing a private/public key pair in your workspace.

  4. Provide the file path for the Keystore in your connector configuration.

    Type keytool -exportcert -alias salesforce-cert -file salesforce-cert.crt -keystore salesforce-cert.jks and press enter.

    The system now exports the public key from the keystore into the workspace. This is the public key that you need to enter in your Salesforce instance.

  5. Make sure that you have both the keystore (salesforce-cert.jks) and the public key (salesforce-cert.crt) files in your workspace.

Handling Events and Topics

Your application can receive events by subscribing to a Salesforce topic.

Each event that travels through your flows contains information about the Salesforce data that has changed, how it changes, and when. The connector parses this information and sends you information that a flow can work with.

Inbound properties of events:

  • payload

  • createdDate

  • replayId

Salesforce stores events for 24 hours, so you can retrieve stored events during that retention window. A subscriber (to a topic or channel) can retrieve events at any time and is not restricted to listening to events at the time they are sent.

Each broadcast event is assigned a numeric ID. IDs are incremented and not guaranteed to be contiguous for consecutive events. Each ID is guaranteed to be higher than the ID of the previous event. For example, the event following the event with ID 999 can have an ID of 1,025. The ID is unique for the organization and the channel. The IDs of deleted events are not reused.

See also Receiving Inbound Data From Salesforce for event processing when streaming data to an application from Salesforce.

Topics:

Subscribing to a Topic

After you create a topic, you can start receiving events by subscribing to the topic. To do so, you add the Subscribe Topic (subscribe-topic) or a Replay Topic (replay-topic) trigger to your flow. The trigger acts as an inbound endpoint. Every time the subscription receives an event, the trigger executes the rest of the flow in your Mule app. In the case of the XML example below, it prints a message to the log at INFO level.

In Design Center, you use Subscribe Topic or Replay Topic operations for the Salesforce connector as the trigger.

In XML, you use subscribe-topic or replay-topic as the trigger:


          
       
1
2
3
4
5
6
<flow name="accountUpdatesSubscription">
    <!-- INBOUND ENDPOINT -->
    <sfdc:subscribe-topic topic="AccountUpdates"/>
    <!-- REST OF YOUR FLOW -->
    <logger level="INFO" message="Received an event for Salesforce Object ID #[map-payload:Id]"/>
</flow>

Note: When subscribing to a topic that was not previously published in Salesforce, the subscription is successful. When the topic is later published, the user who is already subscribed to it does NOT receive notifications regarding that topic. The user has to resubscribe after the topic creates.

Receiving Events for a Topic

Before you can receive events for Salesforce changes that are associated with a topic, you must first create a topic (a PushTopic). A PushTopic is a special object in Salesforce that binds a name (the topic’s name) and Salesforce Object Query Language (SOQL) query together. Once a PushTopic is created, you can subscribe to it by using its name.

In Design Center, you can either use the Create (create) or Publish Topic (publish-topic) operation to create a topic. Example of the required fields for these operations:

  • Topic Name: AccountUpdates

  • Query: SELECT Id, Name FROM Account

Example in XML for publish-topic:

<sfdc:publish-topic name="AccountUpdates" query="SELECT Id, Name FROM Account"/>

Alternatively, in Salesforce you might create a topic by executing code like this from an Enter Apex Code window, accessible through your system logs:


          
       
1
2
3
4
5
6
7
PushTopic pushTopic = new PushTopic();
pushTopic.ApiVersion = 23.0;
pushTopic.Name = 'AllAccounts';
pushTopic.Description = 'All records for the Account object';
pushTopic.Query = 'SELECT Id, Name FROM Account';
insert pushTopic;
System.debug('Created new PushTopic: '+ pushTopic.Id);

Receiving Custom Event Notifications

The Salesforce connector provides two operations that are useful for getting custom event notifications. These notifications pertain to general events that are not tied to Salesforce data changes.

  1. Create a streaming channel with the Publish Channel operation.

    A StreamingChannel is a special Salesforce object that represents a channel used for notifying listeners of generic Streaming API events.

    Note that you can also create a streaming channel through the Salesforce or through Workbench.

  2. Subscribe to the channel through the Subscribe Channel operation.

    The Salesforce connector converts the custom events in your streaming channel to Mule events and dispatches them to your flows.

Replaying Events From a Topic

A subscriber can specify which events to receive, such as all events within the retention window or those that start after a particular event. The default is to receive only new events sent after subscribing. Events outside the 24-hour retention period are discarded.

The Replay Topic (replay-topic) provides these options:

  • All (ALL): Subscriber receives all events, including past events that are within the 24-hour retention period and new events sent after subscription.

  • Only New (ONLY_NEW): Subscriber receives new events that are broadcast after the client subscribes.

  • From Replay ID (FROM_REPLAY_ID): Subscriber receives all events after the specified event replayId.

Resume From the Last Replay ID: An option that allows for automatic replay of stored events, based on the Replay ID of the last event processed by the connector. This functionality can be useful in cases when the connector stopped listening for some reason, such as a server shutdown or dropped connection. If the stored Replay ID is outside the 24-hour retention period, your replay option determines what events to replay.

In this XML example, the replay-topic acts like an inbound endpoint for the Logger message:


          
       
1
2
3
4
5
6
<flow name="accountUpdatesReplay">
    <!-- INBOUND ENDPOINT -->
    <sfdc:replay-topic topic="AccountUpdates" replayId="1" replayOption="ALL" autoReplay="true"/>
    <!-- REST OF YOUR FLOW -->
    <logger level="INFO" message="Replayed events: #[payload]"/>
</flow>

If ALL or ONLY_NEW replay option is selected, then the replayId value is ignored.

Pushing Data to Salesforce

Use as an outbound connector in your flow to push data to Salesforce. To use the connector in this capacity, simply place the connector in your flow at any point after an inbound endpoint.

Receiving Inbound Data From Salesforce

You can use the Salesforce connector as an inbound connector without wrapping the connector in a poll scope to stream data from Salesforce into your application. To use the connector in this capacity, place a Salesforce connector at the start of your flow.

Studio automatically converts the connector to Salesforce (Streaming) mode. Technically, this is still the same connector, but it accesses the Salesforce Streaming API meaning that the only operation the converted connector can perform is Subscribe to topic (that is, subscribe to PushTopic).

subscribe streaming channel

Salesforce connector: Listens to notifications on a topic and feeds the data into the flow.

See also: Streaming API

Streaming channels provide notifications to subscribers that are not limited to record-based events. You can use the Salesforce Connector to work with Salesforce streaming channels.

Creating a Streaming Channel to Receive Data From Salesforce

You must have the proper Streaming API permissions enabled in your organization.

  1. Log into your Salesforce Developer Edition organization.

  2. Under All Tabs (+), select Streaming Channels.

  3. On the Streaming Channels tab, select New to create a new Streaming Channel.

  4. Enter /u/notifications/ExampleUserChannel in Streaming Channel Name, and an optional description.

You can either use the create operation or the exclusive publish-streaming-channel operation as follows:


          
       
1
<sfdc:publish-streaming-channel name="/u/Notifications" description="General notifications"/>

Subscribing to a Streaming Channel

After you create a streaming channel, you can start receiving events by subscribing to the channel. The subscribe-streaming-channel acts like an inbound endpoint and is used as follows:


          
       
1
2
3
4
5
6
<flow name="notificationsChannelSubscription">
        <!-- INBOUND ENDPOINT -->
        <sfdc:subscribe-streaming-channel streamingChannel="/u/TestStreaming"/>
        <!-- REST OF YOUR FLOW -->
        <logger level="INFO" message="Received an event: #[payload]"/>
</flow>

A Mule flow is divided in two. The first portion is usually an inbound endpoint (or an HTTP connector) and a message source. The Mule flow is an entity that receives and generates events that later are processed by the rest of the flow. The other portion is a collection of message processors that processes the messages (also known as events) that are received and generated by the inbound endpoint.

Every time a subscription to /u/TestStreaming receives an event, it executes the rest of the flow. In the case of this example it prints a message to the log at INFO level.

Streaming Channel Inbound Properties

This information gets passed along as inbound properties:

  • channel - Maps to the Channel JSON property

  • type - Maps to the Type JSON property in data

  • createdDate - Maps to the createdDate JSON property in data

Except for channel, each property inside an event is available as an INBOUND property.

Replaying Events from a Streaming Channel

A streaming channel can replay notifications, much like topic replay.

The replay-streaming-channel acts like an inbound endpoint and can be used like this:


          
       
1
2
3
4
5
6
<flow name="flowStreamingChannelReplay">
    <!-- INBOUND ENDPOINT -->
    <sfdc:replay-streaming-channel streamingChannel="/u/Notifications" replayId="1" replayOption="ALL"/>
    <!-- REST OF YOUR FLOW -->
    <logger level="INFO" message="Replayed events: #[payload]"/>
</flow>

If the ALL or ONLY_NEW replay options are selected, then the replayId value is ignored.

Pushing Events to a Streaming Channel

Salesforce lets you push custom events to a specific streaming channel through the REST API. You can use the Salesforce Workbench or this connector.

To use push-generic-event operation:


          
       
1
2
3
4
5
6
7
8
9
<flow name="flowPushGenericEvent">
    <!-- INBOUND ENDPOINT -->
    <sfdc:push-generic-event channelId="0M6j0000000KyjBCAS">
            <sfdc:events>
            <sfdc:event payload="Notification message text"/>
        </sfdc:events>
        </sfdc:push-generic-event>
    <logger level="INFO" message="Replayed events: #[payload]"/>
</flow>

The channel ID can be retrieved from the response map of the publish-streaming-channel operation.

Another way of retrieving the ID of the channel is from the Salesforce page, as follows:

  1. Log into your Developer Edition organization.

  2. Under All Tabs (+), select Streaming Channels.

If the channel ID field is not visible on the channel list, then:

  1. Click Create New View.

  2. Type a name for the view in the Name input field.

  3. In the Available Fields list, select Streaming Channel ID, and click Add.

  4. Add any other fields you want.

  5. Click Save.

Now you should see the channel ID for each streaming channel in the list.

The JSON received as response from the push event operation looks something like:


          
       
1
2
3
4
5
6
7
[
        {
        "userOnlineStatus": {
        },
        "fanoutCount": 0
        }
]

Loading Data in Batches

The Salesforce Bulk API loads batches of your organization’s data into Salesforce.

The Salesforce connector provides the Create and Create Bulk operations for working with the Bulk API.

For all bulk operations, Salesforce handles the creation process in the background, so the connector does not reply with a collection of SaveResults because it does not have them yet. Instead, the connector replies with a BatchInfo object, which contains the ID of the batch and the ID of the job it creates to upload those objects.

Tracking the Status of Bulk Data

You can monitor a Bulk API batch in Salesforce through the Job ID for the Bulk Data Load Jobs.

The job detail page in Salesforce includes a related list of all the batches for the job. The related list provides View Request and View Response links for each batch. If a batch is a CSV file, the links return the request or response in CSV format. If a batch is an XML file, the links return the request or response in XML format.

In Salesforce, you can track the status of bulk data load jobs and their associated batches. Click Your Name > Setup > Monitoring > Bulk Data Load Jobs. Click the Job ID to view the job detail page.

The job detail page includes a related list of all the batches for the job. The related list provides View Request and View Response links for each batch. If the batch is a CSV file, the links return the request or response in CSV format. If the batch is an XML file, the links return the request or response in XML format. These links are available for batches created in Salesforce API version 19.0 and later.

Understanding Usage Notes

Fields To Null

  • The configurations have a checkbox called Can Clear Fields by Updating Field Value to Null. If checked, all the fields in a request that have a Null value are added to the fieldsToNull field and sent to Salesforce.

  • You can decide which fields to set to Null without being forced to use the fieldsToNull field.

Upsert

  • Unless you configure the External ID Field Name for the sObject to which you are trying to Upsert, every use of the upsert will fail.

  • The Upsert operation does not work with the sObject priceBookentry2.

  • While you can’t change the contentType for bulk upsert, you can use Create Job to set the contentType to either CSV or zipped CSV (if you’re hitting the character limit). Follow up with Create Batch.

Query

  • Even though you can see the fields of an SObject and their corresponding types via DataSense, the Query operation returns all fields as String.

  • If you want to use the actual type of the field, you must convert that field to the desired type using a Transform (or Transform Message) component.

  • Although CreatedDate field appears as dateTime, the query returns a String representing the date.

  • To actually use the field as a dateTime, you can configure it using Transform Message, like in the example.

  • To store Date and DateTime fields, you can use DataWeave expressions to create Date and Calendar Java objects.

Inserting values into a Salesforce drop-down

  • Be aware that inserting dependent values into an existing drop-down list field in Salesforce does not always work. Test to confirm functionality.

Evaluating Values in a Salesforce drop-down

  • If you are evaluating against a value in an existing drop-down list field in Salesforce, be sure to use the exact value in the dropdown. For example, if you use the value "US" to evaluate against the contents of a drop-down list that contains the value "USA", the evaluation works, but you end up with two values in the dropdown: one for US and one for USA.

Currency

  • Currency values cannot exceed 18 characters in length.

  • When working with multiple currencies, be aware of which currency your sObject uses so that you avoid inaccurate entries. The default currency matches the location at the organization level.

Limits on API Calls

  • You need to know the rate limiting policy that applies to your account so that you do not exceed the number of allotted API calls per day.

Opportunity sObject

When extracting data from an Opportunity, be aware that a "quarter" is not relative to a calendar year. A "quarter" in this context is relative to the financial year of the organization.

Configuring with XML

If you are creating Salesforce connector XML by hand, add the namespace for the connector. By contrast, Anypoint Studio creates the namespace for a connector automatically when you create a project for a Mule app.


         
      
1
2
3
4
xsi:schemaLocation="
...
http://www.mulesoft.org/schema/mule/sfdc
http://www.mulesoft.org/schema/mule/sfdc/current/mule-salesforce.xsd"

Example:


         
      
1
2
3
4
5
6
7
8
9
10
11
<mule xmlns="http://www.mulesoft.org/schema/mule/core"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:sfdc="http://www.mulesoft.org/schema/mule/salesforce"
      xsi:schemaLocation="
               http://www.mulesoft.org/schema/mule/core
               http://www.mulesoft.org/schema/mule/core/current/mule.xsd
               http://www.mulesoft.org/schema/mule/sfdc
               http://www.mulesoft.org/schema/mule/sfdc/current/mule-salesforce.xsd">

      <!-- Insert your configuration elements and your flow here -->
</mule>

Configuring Maven Dependencies

When creating an app manually from the XML, you need to set up the pom.xml for your project:


          
       
1
2
3
4
5
6
7
8
9
10
11
<repositories>
   <repository>
        <id>mule-ee-releases</id>
        <name>MuleEE Releases Repository</name>
        <url>https://repository-master.mulesoft.org/nexus/content/repositories/releases-ee/</url>
    <repository>
        <id>mule-ee-snapshots</id>
        <name>MuleEE Snapshots Repository</name>
        <url>https://repository-master.mulesoft.org/nexus/content/repositories/ci-snapshots/</url>
    </repository>
</repositories>

This snippet specifies a project dependency for a specific release version:


          
       
1
2
3
4
5
6
<dependency>
    <groupId>org.mule.connectors</groupId>
    <artifactId>mule-sfdc-connector</artifactId>
    <version>RELEASE</version>
    <classifier>mule-plugin</classifier>
</dependency>

This snippet adds specifies a project dependency for the latest version:


          
       
1
2
3
4
5
<dependency>
    <groupId>org.mule.modules</groupId>
    <artifactId>mule-sfdc-connector</artifactId>
    <version>LATEST</version>
</dependency>

Example: Accept and Transform Data

sfdc_outbound

  • HTTP connector: Accepts data from HTTP requests.

  • Transform Message: Transforms data structure and format to produce the output Salesforce connector expects.

  • Salesforce connector: (Outbound) Connects with Salesforce and performs an operation to push data to Salesforce.

Inbound Scenario

query_inbound

  1. Scheduler connector: Triggers flow according to configuration.

  2. Salesforce connector: Connects with Salesforce, and returns an InputStream with the query results.

  3. Transform Message: Transforms data structure and format to produce output the File endpoint expects.

  4. File connector: Records data in a file, such as a CSV and saves it to a user-defined directory or location.

Example: XML

Paste this XML code into Anypoint Studio to experiment with the two flows described in the previous section.


          
       
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
<?xml version="1.0" encoding="UTF-8"?>

<mule xmlns:file="http://www.mulesoft.org/schema/mule/file" xmlns:salesforce="http://www.mulesoft.org/schema/mule/salesforce"
        xmlns:ee="http://www.mulesoft.org/schema/mule/ee/core"
        xmlns:http="http://www.mulesoft.org/schema/mule/http"
        xmlns="http://www.mulesoft.org/schema/mule/core"
        xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/http
http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.mulesoft.org/schema/mule/ee/core
http://www.mulesoft.org/schema/mule/ee/core/current/mule-ee.xsd
http://www.mulesoft.org/schema/mule/salesforce
http://www.mulesoft.org/schema/mule/salesforce/current/mule-salesforce.xsd
http://www.mulesoft.org/schema/mule/file
http://www.mulesoft.org/schema/mule/file/current/mule-file.xsd">
        <configuration-properties file="mule-app.properties"/>
        <http:listener-config name="HTTP_Listener_config" doc:name="HTTP Listener config" >
        <http:listener-connection host="localhost" port="8081" />
        </http:listener-config>
        <salesforce:sfdc-config name="Salesforce_Sfdc_config" doc:name="Salesforce Sfdc config">
          <salesforce:basic-connection
          username="${salesforce.username}"
          password="${salesforce.password}"
          securityToken="${salesforce.securityToken}" />
        </salesforce:sfdc-config>
        <flow name="crud_app_template">
                <http:listener config-ref="HTTP_Listener_config" path="/" doc:name="Listener" />
                <parse-template location="form.html" doc:name="Parse Template"  />
        </flow>
        <flow name="create_accountFlow" >
                <http:listener config-ref="HTTP_Listener_config" path="/createAccount" doc:name="Listener"  />
                <ee:transform doc:name="Transform Message" >
                        <ee:message >
                                <ee:set-payload ><![CDATA[%dw 2.0
output application/java
---
[{

        Name: payload.Name,
        AccountNumber: payload.AccountNumber,
        BillingCity: payload.BillingCity
}]]]></ee:set-payload>
                        </ee:message>
                </ee:transform>
                <salesforce:create doc:name="Create" type="Account" config-ref="Salesforce_Sfdc_config"/>
                <ee:transform doc:name="Transform Message" >
                        <ee:message >
                                <ee:set-payload ><![CDATA[%dw 2.0
output application/json
---
payload map {
        id:$.id,
        errors:$.errors,
        success:$.success

}]]></ee:set-payload>
                        </ee:message>
                </ee:transform>
        </flow>
        <flow name="delete_accountFlow" >
                <http:listener config-ref="HTTP_Listener_config" path="/delete" doc:name="Listener"  />
                <ee:transform doc:name="Transform Message" >
                        <ee:message >
                                <ee:set-payload ><![CDATA[%dw 2.0
output application/java
---
[payload.Id]]]></ee:set-payload>
                        </ee:message>
                </ee:transform>
                <salesforce:delete config-ref="Salesforce_Sfdc_config" doc:name="Delete" />
                <ee:transform doc:name="Transform Message" >
                        <ee:message >
                                <ee:set-payload ><![CDATA[%dw 2.0
output application/json
---
payload map {
        id:$.id,
        errors:$.errors,
        success:$.success
}]]></ee:set-payload>
                        </ee:message>
                </ee:transform>
        </flow>
        <flow name="query_accountFlow" >
                <http:listener config-ref="HTTP_Listener_config" path="/query" doc:name="Listener"  />
                <salesforce:query config-ref="Salesforce_Sfdc_config" doc:name="Query" >
                        <salesforce:salesforce-query>SELECT AccountNumber,BillingAddress,Id,Name FROM Account WHERE Name = ':name'</salesforce:salesforce-query>
                        <salesforce:parameters ><![CDATA[#[output application/java
---
{
        name : payload.name
}]]]></salesforce:parameters>
                </salesforce:query>
                <ee:transform doc:name="Transform Message"  >
                        <ee:message >
                                <ee:set-payload ><![CDATA[%dw 2.0
output application/json
---
payload map {
                AccountNumber:$.AccountNumber,
                BillingAddress:$.BillingAddress,
                Id:$.Id,
                Name:$.Name
}]]></ee:set-payload>
                        </ee:message>
                </ee:transform>
        </flow>
        <flow name="update_accountFlow" >
                <http:listener config-ref="HTTP_Listener_config" path="/update" doc:name="Listener"  />
                <ee:transform doc:name="Transform Message"  >
                        <ee:message >
                                <ee:set-payload ><![CDATA[%dw 2.0
output application/java
---
[{

        Name: payload.Name,
        AccountNumber: payload.AccountNumber,
        Id:payload.Id
}]]]></ee:set-payload>
                        </ee:message>
                </ee:transform>
                <salesforce:update config-ref="Salesforce_Sfdc_config" type="Account" doc:name="Update"  />
                <ee:transform doc:name="Transform Message" >
                        <ee:message >
                                <ee:set-payload ><![CDATA[%dw 2.0
output application/json
---
payload map {
        id:$.id,
        errors:$.errors,
        success:$.success
}]]></ee:set-payload>
                        </ee:message>
                </ee:transform>
        </flow>
        <flow name="upsert_accountFlow" >
                <http:listener config-ref="HTTP_Listener_config" path="/upsert" doc:name="Listener" />
                <ee:transform doc:name="Transform Message" >
                        <ee:message >
                                <ee:set-payload ><![CDATA[%dw 2.0
output application/java
---
[{

        Name: payload.Name,
        AccountNumber: payload.AccountNumber,
        Id:payload.Id
}]]]></ee:set-payload>
                        </ee:message>
                </ee:transform>
                <salesforce:upsert config-ref="Salesforce_Sfdc_config"
                externalIdFieldName="Id" type="Account" doc:name="Upsert" />
                <ee:transform doc:name="Transform Message" >
                        <ee:message >
                                <ee:set-payload ><![CDATA[%dw 2.0
output application/json
---
payload map {
        id:$.id,
        errors:$.errors,
        success:$.success,
        created:$.created

        }]]></ee:set-payload>
                        </ee:message>
                </ee:transform>
        </flow>
        <flow name="find_duplicates_for_account_flow" >
                <http:listener config-ref="HTTP_Listener_config" path="/findDuplicates" doc:name="Listener" />
                <ee:transform doc:name="Transform Message" >
                        <ee:message >
                                <ee:set-payload ><![CDATA[%dw 2.0
output application/java
---
[
        payload
]]]></ee:set-payload>
                        </ee:message>
                </ee:transform>
                <salesforce:find-duplicates config-ref="Salesforce_Sfdc_config" type="Account"
                doc:name="Find duplicates" />
                <ee:transform doc:name="Transform Message" >
                        <ee:message >
                                <ee:set-payload ><![CDATA[%dw 2.0
output application/json
---
{
        success: payload.success,
        duplicateResults: {
                (payload.duplicateResults map {
                        matchRecords: $.matchResults
                }
                )
        },
        duplicateRuleEntityType: payload.duplicateRuleEntityType,
        duplicateRule: payload.duplicateRule,
        allowSave: payload.allowSave,
        errorMessage: payload.errorMessage
}]]></ee:set-payload>
                        </ee:message>
                </ee:transform>
        </flow>
        <flow name="crud-appFlow" >
                <http:listener doc:name="Listener" config-ref="HTTP_Listener_config" path="/"/>
                <salesforce:convert-lead doc:name="Convert lead" config-ref="Salesforce_Sfdc_config"/>
        </flow>
</mule>

Example: Creating or Updating Salesforce Objects With Parent Child Relationships

SalesForce objects can have relationships between them that can be standard or custom created types.

The relationships between the objects are usually one­-to­-many parent­ child relationships, but can be any link between two objects residing in SalesForce.

Creating or altering these objects with relationships is challenging. This section shows how to perform an upsert for an object using the SalesForce connector.

Create a structure in Salesforce for this relationship.

This example assumes two custom types: MyCustomObject and MyOtherCustomObject

MyCustomObject must hold a relationship to a MyOtherCustomObject. When upserting MyCustomObjects, the POJO sent as input to the SalesForce connector looks like this:


         
      
1
2
3
4
5
6
7
8
9
{
        ...
        // MyCustomObject's fields ...
        OtherObject__r:
        {
                CustomField__c : 'ABC123',
                type: 'MyOtherCustomObject__c'
        }
}

OtherObject is the name of MyCustomObject field whose value must be a reference to a MyOtherCustomObject object. OtherObject__r indicates the name of the field that is set and that its a relationship to another object.

The value of this field must be an object with two fields.

A field named type with the referenced object type name as value. In this case a custom MyOtherCustomObject type.

A field with value and name appropriate to identify the right instance of MyOtherCustomObject to reference. In this case is the one with a value of ABC123 for the field named CustomField.

The following XML example shows how to update these objects:


         
      
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<?xml version="1.0" encoding="UTF-8"?>

<mule xmlns:metadata="http://www.mulesoft.org/schema/mule/metadata"
    xmlns:tracking="http://www.mulesoft.org/schema/mule/ee/tracking"
    xmlns:dw="http://www.mulesoft.org/schema/mule/ee/dw"
    xmlns:sfdc="http://www.mulesoft.org/schema/mule/sfdc"
    xmlns="http://www.mulesoft.org/schema/mule/core"
    xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
        xmlns:spring="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/sfdc
http://www.mulesoft.org/schema/mule/sfdc/current/mule-sfdc.xsd
http://www.mulesoft.org/schema/mule/ee/dw
http://www.mulesoft.org/schema/mule/ee/dw/current/dw.xsd
http://www.mulesoft.org/schema/mule/core
http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/ee/tracking
http://www.mulesoft.org/schema/mule/ee/tracking/current/mule-tracking-ee.xsd">
    <sfdc:config name="Salesforce__Basic_Authentication"
        username="username"
        password="password"
        securityToken="token"
        url="https://test.salesforce.com/services/Soap/u/34.0"
        doc:name="Salesforce: Basic Authentication"/>
    <flow name="DirectUpsert" initialState="stopped">
        <poll doc:name="Poll">
            <fixed-frequency-scheduler frequency="10000" startDelay="5000"/>
            <set-payload
                value="#[ [ ['Name' :'test'+server.dateTime, 'field_1__c' : 'test', 'OtherObject__r' : ['CustomField__c' : 'customFieldValue', 'type': 'MyOtherCustomObject__c'] ] ] ]"
                doc:name="Set Payload"/>
        </poll>

<sfdc:upsert config-ref="Salesforce__Basic_Authentication" externalIdFieldName="Id"
    type="MyCustomObject__c" doc:name="Salesforce">
<sfdc:objects ref="#[payload]"/>
</sfdc:upsert>
        <logger message="Upsert completed!" level="INFO" doc:name="Logger"/>
    </flow>
    <flow name="TransformBefore" initialState="stopped">
        <poll doc:name="Poll">
            <fixed-frequency-scheduler frequency="10000" startDelay="5000"/>
            <set-payload
                value="#[ {'name' :&quot;Paul&quot;, 'customData' : 'JULY 11TH', 'parentRef': 'Carlos' } ]"
                doc:name="Set Payload"/>
        </poll>
        <dw:transform-message metadata:id="7f3eb56a-b4ee-49db-8722-8b303c1c8e7a"
            doc:name="Transform Message">
            <dw:input-payload doc:sample="Input.dwl"/>
            <dw:set-payload><![CDATA[%dw 1.0
%output application/java
---
[{
        Name: payload.name,
        field_1__c: payload.customData,
        OtherObject__r: {'CustomField__c' : payload.parentRef, 'type': 'MyOtherCustomObject__c'}
}]]]></dw:set-payload>
        </dw:transform-message>
        <sfdc:upsert config-ref="Salesforce__Basic_Authentication"
            externalIdFieldName="Id" type="MyCustomObject__c" doc:name="Salesforce">
            <sfdc:objects ref="#[payload]"/>
        </sfdc:upsert>
        <logger message="#[payload[0].created ? &quot;Created&quot; : &quot;Updated&quot;]"
         level="INFO" doc:name="Logger"/>
    </flow>
</mule>

See Also

We use cookies to make interactions with our websites and services easy and meaningful, to better understand how they are used and to tailor advertising. You can read more and make your cookie choices here. By continuing to use this site you are giving us your consent to do this.

+