2016-03-05 74 views
1

我有以下調用來發布訂閱到Mailchimp列表,但它返回未授權。我有存儲在web.config中的API密鑰,列表和用戶名,我有三重檢查。向MailChimp API v3發送請求總是返回未授權

using (var wc = new System.Net.WebClient()) 
{ 
    string parameters = string.Concat("email_address=", email, "&status=", "subscribed"), 
      url = "https://us12.api.mailchimp.com/3.0/lists/" + ConfigurationManager.AppSettings["MailChimp.ListId"] + "/members"; 

    wc.Headers.Add("Content-Type", "application/json"); 

    wc.Credentials = new NetworkCredential("", ConfigurationManager.AppSettings["MailChimp.ApiKey"]); 

    string result = wc.UploadString(url, parameters); 
} 

回答

3

有幾個與你的代碼的問題:

  1. 你發送的電子郵件地址和狀態查詢字符串參數而不是JSON
  2. 以這種方式沒有按發送憑據與Web客戶端工作不正常。

嘗試以下操作:

var apiKey = "<api-key>"; 
var listId = "<your-list-id>"; 
var email = "<email-address-to-add>"; 

using (var wc = new System.Net.WebClient()) 
{ 
    // Data to be posted to add email address to list 
    var data = new { email_address = email, status = "subscribed" }; 

    // Serialize to JSON using Json.Net 
    var json = JsonConvert.SerializeObject(data); 

    // Base URL to MailChimp API 
    string apiUrl = "https://us12.api.mailchimp.com/3.0/"; 

    // Construct URL to API endpoint being used 
    var url = string.Concat(apiUrl, "lists/", listId, "/members"); 

    // Set content type 
    wc.Headers.Add("Content-Type", "application/json"); 

    // Generate authorization header 
    string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(":" + apiKey)); 

    // Set authorization header 
    wc.Headers[HttpRequestHeader.Authorization] = string.Format("Basic {0}", credentials); 

    // Post and get JSON response 
    string result = wc.UploadString(url, json); 
} 
+0

這完美地工作。感謝堆門 – Andrew