In the article before, I described how to set up Heroku for integration. In this post, I will start with the basic — obtaining the access token.

Just a bit of the background. I recently run into a problem where customers are emailing enquiries to whichever company email address they found in their inboxes. Meaning a technical support agent might be getting an enquiry about a product feature, and the agent will have manually assign the case back to the correct queue.

It felt like a very common problem, however, I couldn’t find any solutions online whatsoever. Therefore, I (again) decided to design a solution for it myself. Due to the system limitations of apex programming, I don’t think it’s even possible to build a classifier inside the Salesforce platform. I had to build it externally and push the result back to Salesforce.

So the complete flow is:

  1. Salesforce creats cases from emails
  2. Salesforce sends case descriptions along with the Case IDs to
  3. The classified cases based on historical data and send results back to Salesforce

Here, we are actually only going to talk about the last step — send data back to Salesforce.

The external application is written in Python, a very powerful programming language. The reason why I chose python is not only because it’s fast to build a web application on Django, but also because python comes with heaps of free libraries we can use e.g. sklearn.

There are many ways to achieve this, I am going to introduce the soap api, just because it only requires your Salesforce user login email and password.

Here is the method in Python:

def login(instance, userName, password):
    url = "https://" + instance + ".salesforce.com/services/Soap/u/37.0"
    payload = u"""<?xml version="1.0" encoding="utf-8" ?>
    <env:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
    <env:Body>
    <n1:login xmlns:n1="urn:partner.soap.sforce.com">
    <n1:username>""" + userName + """</n1:username>
    <n1:password>""" + password + """</n1:password>
    </n1:login>
    </env:Body>
    </env:Envelope>"""
    headers = {
        'content-type': "text/xml; charset=UTF-8",
        'soapaction': "login"
    }
    response = requests.request("POST", url, data=payload, headers=headers)
    loginXmlRoot = ET.fromstring(response.text)
    sessionId = loginXmlRoot[0][0][0][4].text
    return sessionId

When you call this method, it calls Salesforce API and obtains the session id (the token), which can be later used to ‘do some damages’.

In the next blog, I will post how to use this token to create objects in Salesforce via api.