Salesforce® API

See how easily Chime can integrate with Salesforce®.

Join the Beta » Request a Demo »

Note: The Virtual Agent can be downloaded here » Virtual Agent SDK (zip) (VirtualAgentSDK\Samples\Salesforce)

Overview

The Salesforce Virtual Agent SDK sample includes two Virtual Agents that work together to query and update records in Salesforce. The Pre-Conversation Virtual Agent looks up the guest in the Contact table by their email address and adds their Salesforce information to the Chime session metadata. The expert in Chime can then view this metadata in their Context Window Extension or agent dashboard. The Post-Conversation Virtual Agent updates the description field of the Contact record to note what time the guest sought help from the queue. The Post-Conversation Virtual Agent also posts a Chatter Feed Item with the Chime session metadata, like chat messages.

Before we get started...Check your references!

The following examples use these references. These examples use Newtonsoft Json library to deserialize the responses from Salesforce®.


using Newtonsoft.Json;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

                            

1. Connect to Salesforce® (create an authentication header for subsequent HTTP requests)

This code snippet shows you how to use your Salesforce® credentials to retrieve an access token and construct an authentication header for making subsequent HTTP requests to the Salesforce® REST API.


public class SFResponse
{
    public string access_token = "";
    public string instance_url = "";
    public string token_type = "";
}
public static async void ConnectToSalesForce()
    {
        StringBuilder body = new StringBuilder();
        body.Append("?grant_type=password&");
        body.Append("client_id=" + client_id + "&");
        body.Append("client_secret=" + client_secret + "&");
        body.Append("username=" + username + "&");
        body.Append("password=" + password + security_token);

        using (var client = new HttpClient())
        {
            AuthURL = "https://login.salesforce.com/services/oauth2/token";
            var values = new Dictionary<string, string>();
            var content = new FormUrlEncodedContent(values);
            var response = client.PostAsync(AuthURL + body, content).Result;
            if (response.IsSuccessStatusCode)
            {
                var jsonString = await response.Content.ReadAsStringAsync();
                SFResponse dataObjects = JsonConvert.DeserializeObject<SFResponse>(jsonString);
                authHeaders = new AuthenticationHeaderValue(dataObjects.token_type, dataObjects.access_token);
                isConnectedToSF = true;
                return;
            }
            Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            isConnectedToSF = false;
        }
    }

                        

2. Query a Salesforce table (look for a record matching the guest's e-mail address)

This example shows you how to query the Salesforce Contact table for records that match the provided e-mail address, and receive the Department and Title fields from those record. We’re using the authentication header created in the first example.


public class QueryResponse
{
    public List<Contact> records;
}
public class Contact
{
    public string Department = "";
    public string Title = "";
}
public static async void QuerySalesforce(string email)
    {
        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Authorization = authHeaders;
            var query = "SELECT Department , Title FROM Contact WHERE Email = \'" + email + "\'";
            var requestURL = instance_url + "/services/data/v20.0/query?q=" + query.Replace(" ", "+");
            var response = client.GetAsync(requestURL).Result;
            if (response.IsSuccessStatusCode)
            {
                var jsonString = await response.Content.ReadAsStringAsync();
                QueryResponse data = JsonConvert.DeserializeObject<QueryResponse>(jsonString);
                Contact seeker = data.records.FirstOrDefault();
                if (seeker != null)
                {
                    recordID = seeker.Id;
                }
            }
        }
    }

                        

3. Update a Salesforce record

This example shows how you can update a record field in Salesforce, given that record’s ID. This sample will update the description field of a Contact record.


public static void UpdateSalesforce(string recordId, string description)
{
    using (var client = new HttpClient())
    {
        client.DefaultRequestHeaders.Authorization = authHeaders;
        var values = new Dictionary<string, string>();
        values.Add("Description", description);
        var stringPayload = JsonConvert.SerializeObject(values);
        var content = new StringContent(stringPayload, Encoding.UTF8, "application/json");
        var requestUrl = instance_url + "/services/data/v20.0/sobjects/Contact/" + recordId;
        var response = client.PatchAsync(requestUrl, content).Result;
        if (response.IsSuccessStatusCode)
        {
            Console.WriteLine("Success patching Contact object in salesforce");
            didUpdateSF = true;
        }
        else
        {
            Console.WriteLine(response.StatusCode + " " + response.ReasonPhrase);
        }
    }
}

                        

4. Post a Chatter feed item to a Contact record

This example will show you how, given a record ID, you can post a Chatter feed item directly to that Contact record’s page. The feed item will show up as being posted by the entity you have authenticated yourself as in Step 1.


public class FeedItem
{
    public Body body = new Body();
    public string feedElementType = "FeedItem";
    public string subjectId = Program.recordID;

    public FeedItem(string descr)
    {
        body.messageSegments.Add(new MessageSegment() { text = descr });
    }
    public class Body
    {
        public List<MessageSegment> messageSegments = new List<MessageSegment>();
    }
    public class MessageSegment
    {
        public string type = "Text";
        public string text;
    }
}

    public static void PostChatterFeed(string recordID, string description)
    {
        string chatterUrl = instance_url + "/services/data/v35.0/chatter/feed-elements?feedElementType=FeedItem&subjectId="+recordID+"&text=New+post";

        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Authorization = authHeaders;
            FeedItem values = new FeedItem(description);
            var stringPayload = JsonConvert.SerializeObject(values);
            var content = new StringContent(stringPayload, Encoding.UTF8, "application/json");
            var response = client.PostAsync(chatterUrl, content).Result;
            if (response.IsSuccessStatusCode)
            {
                Console.WriteLine("Success posting Chatter Feed object to salesforce");
                didUpdateSF = true;
            }
            else
            {
                Console.WriteLine(response.StatusCode + " " + response.ReasonPhrase);
            }
        }
    }

                        

Questions?

Have a question about Chime integration with Salesforce®? Ask one of our developers at InstantDev@instant-tech.com.