Archive for ‘salesforce’

October 17, 2011

salesforce contact integration on google app engine

contact integration with salesforce is easy. here is how we did it recently on a Google App Engine project.

this works for enterprise salesforce accounts only (and ofcourse developer accounts)

step 1: get an authorization code from salesforce

AUTHORIZE_URI = ‘https://login.salesforce.com

def get(self, **kwargs):
code = request.args.get(“code”)
args = {
‘client_id’: SALESFORCE_CONSUMER_KEY,
‘redirect_uri’: REDIRECT_URI,
‘state’:workspace # salesforce allows user # defined to be stored in the # state variable
}

if code is not None:

# call back from salesforce …

args[“client_secret”] = SALESFORCE_CONSUMER_SECRET args[“code”] = request.args.get(“code”)
args[‘grant_type’] = “authorization_code”

url = AUTHORIZE_URI + “/services/oauth2/token?” + urllib.urlencode(args)
response = urlfetch.fetch(url, method=urlfetch.POST, validate_certificate=False) content = json.loads(response.content)

access_token = content[‘access_token’]
instance_url = content[‘instance_url’]
refresh_token = content[‘refresh_token’]

else:

# call salesforce

args[‘response_type’] = ‘code’
url = ‘%s%s’%(AUTHORIZE_URI, “/services/oauth2/authorize?%s”%urllib.urlencode(args)) return redirect(url)

step 2: use the token to call into salesforce

def salesforce_query(email, contact_fields, access_token, instance_url):

fields = ‘, ‘.join([f for f in contact_fields])

args = {
“q” :”SELECT %s from Contact where Email = ‘%s'” % (fields, email) }

headers = {
“Authorization”: “OAuth %s” % access_token
}

url = ‘%s%s%s’ % (instance_url, “/services/data/v20.0/query?”, urllib.urlencode(args))

response = urlfetch.fetch(url, headers=headers, method=urlfetch.GET, validate_certificate=False) return simplejson.loads(response.content)