salesforce
Modules
Module salesforce
API
Declarations
ballerinax/salesforce Ballerina library
Overview
The Salesforce connector allows users to perform CRUD operations for SObjects, query using SOQL, search using SOSL, and describe SObjects and organizational data through the Salesforce REST API. Apart from these functionalities, Ballerina Salesforce Connector includes a listener to capture events.
This module supports Salesforce v48.0 REST API.
Prerequisites
Before using this connector in your Ballerina application, complete the following:
- Create Salesforce account
- Obtain tokens
- Client tokens - Follow the steps listed under OAuth 2.0 Web Server Flow for Web App Integration.
- Listener tokens - Follow the steps listed under Reset Your Security Token generate secret key and follow the steps listed under Subscription Channels to subscribe channels.
Quickstart
To use the Salesforce connector in your Ballerina application, update the .bal file as follows:
Client
Step 1: Import connector
Import the ballerinax/salesforce
module into the Ballerina project.
import ballerinax/salesforce;
Step 2: Create a new connector instance
Create a salesforce:ConnectionConfig
with the OAuth2 tokens obtained, and initialize the connector with it.
salesforce:ConnectionConfig sfConfig = { baseUrl: <"EP_URL">, clientConfig: { clientId: <"CLIENT_ID">, clientSecret: <"CLIENT_SECRET">, refreshToken: <"REFRESH_TOKEN">, refreshUrl: <"REFRESH_URL"> } }; salesforce:Client baseClient = new(sfConfig);
Step 3: Invoke connector operation
- Now you can use the operations available within the connector. Note that they are in the form of remote operations.
Following is an example on how to create a record using the connector.
json accountRecord = { Name: "John Keells Holdings", BillingCity: "Colombo 3" }; public function main() returns error? { string recordId = check baseClient->createRecord("Account", accountRecord); }
- Use
bal run
command to compile and run the Ballerina program.
Listener
Step 1: Import connector
Import the ballerinax/salesforce
module into the Ballerina project.
import ballerinax/salesforce;
Step 2: Create a new connector listener instance
Create a salesforce:ListenerConfiguration
with the basic credentials obtained, and initialize the connector with it.
The password should be the concatenation of the user's Salesforce password and secret key.
salesforce:ListenerConfiguration listenerConfig = { username: config:getAsString("SF_USERNAME"), password: config:getAsString("SF_PASSWORD") }; listener salesforce:Listener eventListener = new (listenerConfig);
Step 3: Invoke listener service
- Now you can use the channel available in the Salesforce and capture the events occurred.
Following is an example on how to capture all events using the connector.
@salesforce:ServiceConfig { channelName:"/data/ChangeEvents" } service /quoteUpdate on eventListener { remote function onUpdate (salesforce:EventData quoteUpdate) { json quote = quoteUpdate.changedData.get("Status"); } }
- Use
bal run
command to compile and run the Ballerina program.
Functions
prepareUrl
Returns the prepared URL.
Parameters
- paths string[] - An array of paths prefixes
Return Type
- string - The prepared URL
Clients
salesforce: Client
Ballerina Salesforce connector provides the capability to access Salesforce REST API. This connector lets you to perform operations for SObjects, query using SOQL, search using SOSL, and describe SObjects and organizational data.
Constructor
Initializes the connector. During initialization you can pass either http:BearerTokenConfig if you have a bearer token or http:OAuth2RefreshTokenGrantConfig if you have Oauth tokens. Create a Salesforce account and obtain tokens following this guide.
init (ConnectionConfig salesforceConfig)
- salesforceConfig ConnectionConfig - Salesforce Connector configuration
describeAvailableObjects
function describeAvailableObjects() returns OrgMetadata|Error
Lists the available objects and their metadata for your organization and available to the logged-in user.
Return Type
- OrgMetadata|Error -
OrgMetadata
record if successful or elsesfdc:Error
getSObjectBasicInfo
function getSObjectBasicInfo(string sobjectName) returns SObjectBasicInfo|Error
Describes the individual metadata for the specified object.
Parameters
- sobjectName string - SObject name
Return Type
- SObjectBasicInfo|Error -
SObjectBasicInfo
record if successful or elsesfdc:Error
describeSObject
function describeSObject(string sObjectName) returns SObjectMetaData|Error
Completely describes the individual metadata at all levels for the specified object. Can be used to retrieve the fields, URLs, and child relationships.
Parameters
- sObjectName string - SObject name value
Return Type
- SObjectMetaData|Error -
SObjectMetaData
record if successful or elsesfdc:Error
sObjectPlatformAction
function sObjectPlatformAction() returns SObjectBasicInfo|Error
Query for actions displayed in the UI, given a user, a context, device format, and a record ID.
Return Type
- SObjectBasicInfo|Error -
SObjectBasicInfo
record if successful or elsesfdc:Error
getRecordById
Gets an object record by ID.
Return Type
- json|Error - JSON result if successful or else
sfdc:Error
getRecordByExtId
function getRecordByExtId(string sobject, string extIdField, string extId, string... fields) returns json|Error
Gets an object record by external ID.
Parameters
- sobject string - SObject name
- extIdField string - External ID field name
- extId string - External ID value
- fields string... - Fields to retrieve
Return Type
- json|Error - JSON result if successful or else
sfdc:Error
getAccountById
Accesses Account SObject records based on the Account object ID.
Return Type
- json|Error - JSON response if successful or else an sfdc:Error
createAccount
Creates new Account object record.
Parameters
- accountRecord json - Account JSON record to be inserted
deleteAccount
Deletes existing Account's records.
Parameters
- accountId string - Account ID
Return Type
- Error? -
true
if successfulfalse
otherwise, or an sfdc:Error in case of an error
updateAccount
Updates existing Account object record.
Return Type
- Error? -
true
if successful,false
otherwise or an sfdc:Error in case of an error
getLeadById
Accesses Lead SObject records based on the Lead object ID.
Return Type
- json|Error - JSON response if successful or else an sfdc:Error
createLead
Creates new Lead object record.
Parameters
- leadRecord json - Lead JSON record to be inserted
deleteLead
Deletes existing Lead's records.
Parameters
- leadId string - Lead ID
Return Type
- Error? -
true
if successful,false
otherwise or an sfdc:Error incase of an error
updateLead
Updates existing Lead object record.
Return Type
- Error? -
true
if successful,false
otherwise or an sfdc:Error in case of an error
getContactById
Accesses Contacts SObject records based on the Contact object ID.
Return Type
- json|Error - JSON result if successful or else an sfdc:Error
createContact
Creates new Contact object record.
Parameters
- contactRecord json - JSON contact record
deleteContact
Deletes existing Contact's records.
Parameters
- contactId string - Contact ID
Return Type
- Error? -
true
if successful,false
otherwise or an sfdc:Error in case of an error
updateContact
Updates existing Contact object record.
Return Type
- Error? -
true
if successful,false
otherwise or an sfdc:Error in case of an error
getOpportunityById
Accesses Opportunities SObject records based on the Opportunity object ID.
Return Type
- json|Error - JSON response if successful or else an sfdc:Error
createOpportunity
Creates new Opportunity object record.
Parameters
- opportunityRecord json - JSON opportunity record
deleteOpportunity
Deletes existing Opportunity's records.
Parameters
- opportunityId string - Opportunity ID
Return Type
- Error? -
true
if successful,false
otherwise or an sfdc:Error in case of an error
updateOpportunity
Updates existing Opportunity object record.
Return Type
- Error? -
true
if successful,false
otherwise or an sfdc:Error in case of an error
getProductById
Accesses Products SObject records based on the Product object ID.
Return Type
- json|Error - JSON result if successful or else an sfdc:Error
createProduct
Creates new Product object record.
Parameters
- productRecord json - JSON product record
deleteProduct
Deletes existing product's records.
Parameters
- productId string - Product ID
Return Type
- Error? -
true
if successful,false
otherwise or an sfdc:Error in case of an error
updateProduct
Updates existing Product object record.
Return Type
- Error? -
true
if successful,false
otherwise or an sfdc:Error in case of an error
getQueryResult
function getQueryResult(string receivedQuery) returns SoqlResult|Error
Executes the specified SOQL query.
Parameters
- receivedQuery string - Sent SOQL query
Return Type
- SoqlResult|Error -
SoqlResult
record if successful. Else, the occurredError
.
getNextQueryResult
function getNextQueryResult(string nextRecordsUrl) returns SoqlResult|Error
If the query results are too large, retrieve the next batch of results using the nextRecordUrl.
Parameters
- nextRecordsUrl string - URL to get the next query results
Return Type
- SoqlResult|Error -
SoqlResult
record if successful. Else, the occurredError
.
searchSOSLString
function searchSOSLString(string searchString) returns SoslResult|Error
Executes the specified SOSL search.
Parameters
- searchString string - Sent SOSL search query
Return Type
- SoslResult|Error -
SoslResult
record if successful. Else, the occurredError
.
getAvailableApiVersions
Lists summary details about each REST API version available.
getResourcesByApiVersion
Lists the resources available for the specified API version.
Parameters
- apiVersion string - API version (v37)
getOrganizationLimits
Lists the Limits information for your organization.
Return Type
getRecord
Accesses records based on the specified object ID, can be used with external objects.
Parameters
- path string - Resource path
Return Type
- json|Error - JSON result if successful else or else
sfdc:Error
createRecord
Creates records based on relevant object type sent with json record.
deleteRecord
Delete existing records based on relevant object ID.
Return Type
- Error? - true if successful else false or else
sfdc:Error
updateRecord
Updates records based on relevant object ID.
Parameters
- sObjectName string - SObject name value
- id string - SObject ID
- recordPayload json - JSON record to be updated
Return Type
- Error? - true if successful else false or else
sfdc:Error
Constants
salesforce: API_VERSION
Constant field API_VERSION
. Holds the value for the Salesforce API version.
salesforce: EMPTY_STRING
Constant field EMPTY_STRING
. Holds the value of "".
salesforce: ERR_EXTRACTING_ERROR_MSG
salesforce: HTTP_ERROR_MSG
salesforce: INVALID_CLIENT_CONFIG
salesforce: REPLAY_FROM_EARLIEST
Replay ID -2
to get all new events sent after subscription and all past events within the retention window.
salesforce: REPLAY_FROM_TIP
Replay ID -1
to get all new events sent after subscription.
Listeners
salesforce: Listener
Ballerina Salesforce Listener connector provides the capability to receive notifications from Salesforce.
Constructor
Initializes the connector. During initialization you have to pass Salesforce username and concatenation of password and security token.
init (ListenerConfiguration config)
- config ListenerConfiguration -
attach
detach
function detach(service object {} s) returns error?
Parameters
- s service object {} -
'start
function 'start() returns error?
gracefulStop
function gracefulStop() returns error?
immediateStop
function immediateStop() returns error?
Annotations
salesforce: ServiceConfig
Records
salesforce: Attribute
Defines the Attribute type. Contains the attribute information of the resultant record.
Fields
- 'type string -
- url string - URL of the resultant record
salesforce: ChangeEventMetadata
Header fields that contain information about the event.
Fields
- commitTimestamp int? - The date and time when the change occurred, represented as the number of milliseconds since January 1, 1970 00:00:00 GMT
- transactionKey string? - Uniquely identifies the transaction that the change is part of
- changeOrigin string? - Origin of the change. Use this field to find out what caused the change.
- changeType string? - The operation that caused the change
- entityName string? - The name of the standard or custom object for this record change
- sequenceNumber int? - Identifies the sequence of the change within a transaction
- commitUser string? - The ID of the user that ran the change operation
- commitNumber int? - The system change number (SCN) of a committed transaction
- recordId string? - The record ID for the changed record
salesforce: ConnectionConfig
Salesforce client configuration.
Fields
- baseUrl string - The Salesforce endpoint URL
- clientConfig OAuth2RefreshTokenGrantConfig|BearerTokenConfig - OAuth2 direct token configuration
- secureSocketConfig ClientSecureSocket? - HTTPS secure socket configuration
- httpVersion string(default "1.1") - The HTTP version understood by the client
- http1Settings ClientHttp1Settings(default {}) - Configurations related to HTTP/1.x protocol
- http2Settings ClientHttp2Settings(default {}) - Configurations related to HTTP/2 protocol
- timeout decimal(default 60) - The maximum time to wait (in seconds) for a response before closing the connection
- forwarded string(default "disable") - The choice of setting
forwarded
/x-forwarded
header
- followRedirects FollowRedirects?(default ()) - Configurations associated with Redirection
- poolConfig PoolConfiguration?(default ()) - Configurations associated with request pooling
- cache CacheConfig(default {}) - HTTP caching related configurations
- compression Compression(default http:COMPRESSION_AUTO) - Specifies the way of handling compression (
accept-encoding
) header
- circuitBreaker CircuitBreakerConfig?(default ()) - Configurations associated with the behaviour of the Circuit Breaker
- retryConfig RetryConfig?(default ()) - Configurations associated with retrying
- cookieConfig CookieConfig?(default ()) - Configurations associated with cookies
- responseLimits ResponseLimitConfigs(default {}) - Configurations associated with inbound response size limits
salesforce: ErrorDetails
Additional details extracted from the Http error.
Fields
- statusCode int? - Http status code of the error
- body anydata? - Response body with extra information
salesforce: EventData
A record type which contains data returned from a Change Data Event.
Fields
- changedData map<json> - A JSON map which contains the changed data
- metadata ChangeEventMetadata? - Header fields that contain information about the event
salesforce: Limit
Defines the Limit type to list limits information for your org.
Fields
- Max int - The limit total for the org
- Remaining int - The total number of calls or events left for the org
- json... - Rest field
salesforce: ListenerConfiguration
Salesforce listener configuration.
Fields
- username string - Salesforce login username
- password string - Salesforce login password appended with the security token (<password><security token>)
salesforce: OrgMetadata
Metadata for your organization and available to the logged-in user.
Fields
- encoding string - Encoding
- maxBatchSize int - Maximum batch size
- sobjects SObjectMetaData[] - Available SObjects
- json... - Rest field
salesforce: SFDCChannelConfigData
The channel configuration data.
Fields
- channelName string - The channel name to which a client can subscribe to receive event notifications
- replayFrom ReplayFrom(default REPLAY_FROM_TIP) - The replay ID to change the point in time when events are read
-1
- Get all new events sent after subscription. This option is the default-2
- Get all new events sent after subscription and all past events within the retention windowSpecific number
- Get all events that occurred after the event with the specified replay ID
salesforce: SObjectBasicInfo
Basic info of a SObject.
Fields
- objectDescribe SObjectMetaData - Metadata related to the SObject
- json... - Rest field
salesforce: SObjectMetaData
Metadata for an SObject, including information about each field, URLs, and child relationships.
Fields
- name string - SObject name
- createable boolean - Is createable
- deletable boolean - Is deletable
- updateable boolean - Is updateable
- queryable boolean - Is queryable
- label string - SObject label
- json... - Rest field
salesforce: SoqlRecord
Defines the SOQL query result record type.
Fields
- attributes Attribute - Attribute record
- json... - Rest field
salesforce: SoqlResult
Define the SOQL result type.
Fields
- done boolean - Query is completed or not
- totalSize int - The total number result records
- records SoqlRecord[] - Result records
- json... - Rest field
salesforce: SoslRecord
Defines SOSL query result.
Fields
- attributes Attribute - Attribute record
- Id string - ID of the matching object
- json... - Rest field
salesforce: SoslResult
Defines SOSL query result.
Fields
- searchRecords SoslRecord[] - Matching records for the given search string
- json... - Rest field
salesforce: Version
Defines the Salesforce version type.
Fields
- label string - Label of the Salesforce version
- url string - URL of the Salesforce version
- 'version string -
Errors
salesforce: Error
Salesforce connector error.
Union types
salesforce: ReplayFrom
ReplayFrom
The replay ID to change the point in time when events are read
Import
import ballerinax/salesforce;
Metadata
Released date: over 2 years ago
Version: 4.2.0
License: Apache-2.0
Compatibility
Platform: java11
Ballerina version: 2201.0.1
Pull count
Total: 95249
Current verison: 7150
Weekly downloads
Keywords
Sales & CRM/Customer Relationship Management
Cost/Freemium
Contributors