taoCMS是基于php+sqlite/mysql的国内最小(100Kb左右)的功能完善的CMS管理系统

使用restful api操作salesforce的数据

2014-01-15

In the past I've complained about the Salesforce SOAP API for reading/writing your CRM databases. Last year Salesforce added a new API, one founded on RESTful principals, for developers to work with. I wish it was implemented as an OData service, but I guess the Salesforce guys are stuck behind the times.

At any rate, I had a need to read/write to a Salesforce instance and couldn't bear to use their SOAP API again so I decided to give the REST API a go. Their developer site doesn't do that much in the way of help for .NET developers (there is some, but not much)... everything is really skewed towards PHP or their own APEX language. After some searching I found Dan Boris' series of Salesforce related posts. These are good and he covers a lot of good things such as:

Dan's posts talk about using the method of authentication where you create an app that contains an embedded browser control and you get the user using t your app to login to Salesforce. Then your app grabs the OAuth token and include that with all future requests. Before you do this you need to configure a new remote access app for your Salesforce account. This is done by logging in and going to SETUP > DEVELOP > REMOTE ACCESS. Click NEW and create a new remote access app. One of the fields it will give you is a callback URL that is required. This is used by Salesforce to redirect the user back to a specific URL after a successful login. In a web app this makes sense but not if you want to use this within a console app or a service. What I do is put just a dummy URN in there that I'll look for later like resttest:callback.

Now, Dan's stuff works great in many cases, but not if you want to create an app that runs like a service and automatically logs in and does some stuff with the API without user interaction. The way you authenticate with Salesforce is using OAuth 2.0. OAuth 2.0 supports multiple authentication flows and Salesforce supports many of them as outlined in their SDK: Authenticating Remote Access Application OAuth & discussed on their DeveloperForce site: Digging Deeper into OAuth 2.0 on Force.com. In my scenario I want to focus on creating an app that runs as a service to use the REST API without any user action required for logging in. This is the least secure because it means I have to store a username & password somewhere, but that's just the ante for playing the game. So, in this case I want to use the OAuth 2.0 Username & Password Flow.

So, to authenticate you do something like this using the OAuth 2.0 Username & Password flow:

   1: private void AuthenticateToSalesforce(){
   2:   string uri = "https://login.salesforce.com/services/oauth2/token";
   3:  
   4:   var webClient = new WebClient() {
   5:     BaseAddress = uri
   6:   };
   7:  
   8:   var collection = new NameValueCollection();
   9:   collection.Add("grant_type", "password");
  10:   collection.Add("client_id", CONSUMER_KEY);
  11:   collection.Add("client_secret", CONSUMER_SECRET);
  12:   collection.Add("username", SALESFORCE_USERNAME);
  13:   collection.Add("password", SALESFORCE_PASSWORD_AND_SECRETKEY);
  14:  
  15:   byte[] responseBytes = webClient.UploadValues("", "POST", collection);
  16:   string response = Encoding.UTF8.GetString(responseBytes);
  17:   string decodedResponse = HttpUtility.UrlDecode(response);
  18:   JavaScriptSerializer js = new JavaScriptSerializer();
  19:   var token = js.Deserialize<TokenResponse>(decodedResponse);
  20: }
  21:  
  22: public class TokenResponse {
  23:   public string id { get; set; }
  24:   public string issued_at { get; set; }
  25:   public string refresh_token { get; set; }
  26:   public string instance_url { get; set; }
  27:   public string signature { get; set; }
  28:   public string access_token { get; set; }
  29: }

As you can see I'm creating a Web request and passing in a handful of things in the header. Specifically I'm passing in the grant_type of "password" to signal I want to use the OAuth 2.0 Username & Password flow. I'm also passing in the consumer key & secret you get from creating the remote access app in your Salesforce account and finally the username & password to authenticate with. This will return a JSON array (you can also get a XML response if you like) which I deserialize into a custom object that will pull everything I need. Specifically I need the instance_url (which is the URL of my Salesforce account) and the access_token which is what you need to include in all future requests.

Once you have the token, you can use the REST API to read & write data like Dan shows in his posts I linked to above, or like this:

   1: public void QuerySalesforce(){
   2:   // build LEAD query
   3:   XDocument xDoc = XDocument.Load(@"SalesForceSchema.xml");
   4:   var fields = from x in xDoc.Root.Element("Lead").Elements("Field") 
   5:                select x.Attribute("SfName").Value;
   6:   string query = String.Format("SELECT {0} FROM Lead 
   7:                                 WHERE Email = 'something@email.com'"
   8:                                , string.Join(",", fields));
   9:  
  10:   string sfQuery = String.Format("{0}/services/data/v23.0/query?q={1}",
  11:                    token.instance_url,
  12:                    query);
  13:   HttpWebRequest request = HttpWebRequest.Create(sfQuery) as HttpWebRequest;
  14:   request.Headers.Add("Authorization", "OAuth " + token.access_token);
  15:   request.ContentType = "application/json";
  16:   request.Method = "GET";
  17:  
  18:   WebResponse webResponse = request.GetResponse();
  19:   var sr = new System.IO.StreamReader(webResponse.GetResponseStream());
  20:   string json = sr.ReadToEnd();
  21:   var leads = js.Deserialize<sfdcLeadCollection<sfdcLeadForCollection>>
  22:                                     (HttpUtility.UrlDecode(json));
  23: }
  24:  
  25: public class sfdcLeadCollection<T> {
  26:   public bool Done { get; set; }
  27:   public int TotalSize { get; set; }
  28:   public string nextRecordsUrl { get; set; }
  29:   public List<T> Records { get; set; }
  30: }
  31:  
  32: public class sfdcAttributes {
  33:   public string Type { get; set; }
  34:   public string Url { get; set; }
  35: }
  36:  
  37: public class sfdcLeadForCollection : sObjectLead {
  38:   public sfdcAttributes Attributes { get; set; }
  39: }
  40:  
  41: public class sObjectLead {
  42:   public string Id { get; set; }
  43:   public string Email { get; set; }
  44:   public string FirstName { get; set; }
  45:   public string LastName { get; set; }
  46:   public string Company { get; set; }
  47:   public string Phone { get; set; }
  48:   public string MobilePhone { get; set; }
  49:   public string Fax { get; set; }
  50:   public string Website { get; set; }
  51:   public string Street { get; set; }
  52:   public string City { get; set; }
  53:   public string State { get; set; }
  54:   public string Country { get; set; }
  55:   public string PostalCode { get; set; }
  56: }

Read more at http://www.andrewconnell.com/blog/Authenticating-and-Working-with-the-Salesforce-REST-API-and-OAuth#hixSiH8ZKOoBZZdk.99

类别:技术文章 | 阅读:166972 | 评论:0 | 标签:salesforce restful api

想收藏或者和大家分享这篇好文章→

“使用restful api操作salesforce的数据”共有0条留言

发表评论

姓名:

邮箱:

网址:

验证码:

公告

taoCMS发布taoCMS2.5Beta5(最后更新14年05月25日),请大家速速升级,欢迎大家试用和提出您宝贵的意见建议。

捐助与联系

☟请使用新浪微博联系我☟

☟在github上follow我☟

标签云