2014-10-29 4 views
6

Qualcuno ha un esempio di chiamata a un'API Marketo Rest da .net/C#.Esempio di codice per chiamare Marketo Rest Api in .net/C#

Sono particolarmente interessato al pezzo di autenticazione oauth. http://developers.marketo.com/documentation/rest/authentication/

ho intenzione di chiamare questo endpoint http://developers.marketo.com/documentation/rest/get-multiple-leads-by-list-id/

non riesco a trovare alcun esempio là fuori sul interweb.

+0

Non ci sono veramente esempi o documentazione sulla chiamata alle API di Market REST usando .net/C#. Non sono sicuro del motivo per cui a qualcuno non è piaciuta la domanda. – Cameron

+0

Perché è stato downvoted? Questa è una domanda valida. –

risposta

6

Sono stato in grado di codificare una soluzione per chiamare un'API Marketo Rest e fare l'OAuth. Di seguito è riportato un how-to Il codice seguente mostra le nozioni di base, ma necessita di pulizia, registrazione e gestione degli errori per garantire la produzione.

È necessario ottenere gli URL di Rest api per l'istanza di Marketo. Per fare ciò, accedere a marketo e navigare su Admin \ Integration \ Web Services e utilizzare gli URL nella Sezione API Rest.

È necessario ottenere l'ID utente e il segreto da marketo - accedere a Admin \ Integration \ Launch Pont. Visualizza i dettagli del tuo servizio di Rest per ottenere identità e segreti. Se non si dispone di un servizio, quindi seguire queste istruzioni http://developers.marketo.com/documentation/rest/custom-service/.

Infine, è necessario il proprio ID elenco per l'elenco di lead che si desidera ottenere. Puoi ottenerlo navigando al tuo elenco e copiando la parte numerica dell'ID dall'URL. Esempio: https://XXXXX.marketo.com/#ST1194B2 -> Lista ID = 1194

 private void GetListLeads() 
    { 
     string token = GetToken().Result; 

     string listID = "XXXX"; // Get from Marketo UI 
     LeadListResponse leadListResponse = GetListItems(token, listID).Result; 
     //TODO: do something with your list of leads 

    } 
    private async Task<string> GetToken() 
    { 
     string clientID = "XXXXXX"; // Get from Marketo UI 
     string clientSecret = "XXXXXX"; // Get from Marketo UI 

     string url = String.Format("https://XXXXXX.mktorest.com/identity/oauth/token?grant_type=client_credentials&client_id={0}&client_secret={1}",clientID, clientSecret); // Get from Marketo UI 
     var fullUri = new Uri(url, UriKind.Absolute); 

     TokenResponse tokenResponse = new TokenResponse(); 
     using (var client = new HttpClient()) 
     { 
      HttpResponseMessage response = await client.GetAsync(fullUri); 

      if (response.IsSuccessStatusCode) 
      { 
       tokenResponse = await response.Content.ReadAsAsync<TokenResponse>(); 
      } 
      else 
      { 
       if (response.StatusCode == HttpStatusCode.Forbidden) 
        throw new AuthenticationException("Invalid username/password combination."); 
       else 
        throw new ApplicationException("Not able to get token"); 
      } 
     } 

     return tokenResponse.access_token; 
    } 

    private async Task<LeadListResponse> GetListItems(string token, string listID) 
    { 

     string url = String.Format("https://XXXXXX.mktorest.com/rest/v1/list/{0}/leads.json?access_token={1}", listID, token);// Get from Marketo UI 
     var fullUri = new Uri(url, UriKind.Absolute); 

     LeadListResponse leadListResponse = new LeadListResponse(); 
     using (var client = new HttpClient()) 
     { 
      HttpResponseMessage response = await client.GetAsync(fullUri); 

      if (response.IsSuccessStatusCode) 
      { 
       leadListResponse = await response.Content.ReadAsAsync<LeadListResponse>(); 
      } 
      else 
      { 
       if (response.StatusCode == HttpStatusCode.Forbidden) 
        throw new AuthenticationException("Invalid username/password combination."); 
       else 
        throw new ApplicationException("Not able to get token"); 
      } 
     } 

     return leadListResponse; 
    } 


    private class TokenResponse 
    { 
     public string access_token { get; set; } 
     public int expires_in { get; set; } 
    } 

    private class LeadListResponse 
    { 
     public string requestId { get; set; } 
     public bool success { get; set; } 
     public string nextPageToken { get; set; } 
     public Lead[] result { get; set; } 
    } 

    private class Lead 
    { 
     public int id { get; set; } 
     public DateTime updatedAt { get; set; } 
     public string lastName { get; set; } 
     public string email { get; set; } 
     public DateTime datecreatedAt { get; set; } 
     public string firstName { get; set; } 
    } 
1

vecchia questione, solo nella speranza di aiutare il prossimo ragazzo che finisce qui da una ricerca su Google :-)

Questa pagina è stata probabilmente non c'è al momento di questo post, ma ora c'è una buona pagina con esempi in diverse lingue. La pagina è in http://developers.marketo.com/documentation/rest/get-multiple-leads-by-list-id

Nel caso in cui il collegamento si esaurisce, ecco il codice di esempio che essi forniscono per C#

using Newtonsoft.Json; 
using System; 
using System.Collections.Generic; 
using System.IO; 
using System.Linq; 
using System.Net; 
using System.Text; 
using System.Threading.Tasks; 

namespace Samples 
{ 
    class LeadsByList 
    { 
     private String host = "CHANGE ME"; //host of your marketo instance, https://AAA-BBB-CCC.mktorest.com 
     private String clientId = "CHANGE ME"; //clientId from admin > Launchpoint 
     private String clientSecret = "CHANGE ME"; //clientSecret from admin > Launchpoint 
     public int listId; 
     public int batchSize;//max 300, default 300 
     public String[] fields;//array of field names to retrieve 
     public String nextPageToken;//paging token 
     /* 
     public static void Main(String[] args) 
     { 
      MultipleLeads leads = new MultipleLeads(); 
      leads.listId = 1001 
      String result = leads.getData(); 
      Console.WriteLine(result); 
      while (true) 
      { 

      } 
     } 
     */ 
     public String getData() 
     { 
      StringBuilder url = new StringBuilder(host + "/rest/v1/list/" + listId + "/leads.json?access_token=" + getToken()); 
      if (fields != null) 
      { 
       url.Append("&fields=" + csvString(fields)); 
      } 
      if (batchSize > 0 && batchSize < 300) 
      { 
       url.Append("&batchSize=" + batchSize); 
      } 
      if (nextPageToken != null) 
      { 
       url.Append("&nextPageToken=" + nextPageToken); 
      } 
      HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url.ToString()); 
      request.ContentType = "application/json"; 
      request.Accept = "application/json"; 
      HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
      Stream resStream = response.GetResponseStream(); 
      StreamReader reader = new StreamReader(resStream); 
      return reader.ReadToEnd(); 
     } 

     private String getToken() 
     { 
      String url = host + "/identity/oauth/token?grant_type=client_credentials&client_id=" + clientId + "&client_secret=" + clientSecret; 
      HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 
      request.ContentType = "application/json"; 
      HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
      Stream resStream = response.GetResponseStream(); 
      StreamReader reader = new StreamReader(resStream); 
      String json = reader.ReadToEnd(); 
      //Dictionary<String, Object> dict = JavaScriptSerializer.DeserializeObject(reader.ReadToEnd); 
      Dictionary<String, String> dict = JsonConvert.DeserializeObject<Dictionary<String, String>>(json); 
      return dict["access_token"]; 
     } 
     private String csvString(String[] args) 
     { 
      StringBuilder sb = new StringBuilder(); 
      int i = 1; 
      foreach (String s in args) 
      { 
       if (i < args.Length) 
       { 
        sb.Append(s + ","); 
       } 
       else 
       { 
        sb.Append(s); 
       } 
       i++; 
      } 
      return sb.ToString(); 

     } 
    } 
} 

Al momento di questa risposta - questa pagina ha tutte le chiamate API documentato http://developers.marketo.com/documentation/rest/