7

I am trying to implement Mail Chimp's new API with my ASP.NET C# website so when a user enters their email address into an input box it will be added to my mailchimp list automatically. I have tried various other methods however none of these have worked.

I have tried a Web Client which threw a 405 Cannot use that Method response and a HttpClient which threw an error on the starred GetStringAsync method call because its not a task.

My code so far is detailed below:

public bool BatchSubscribe(IEnumerable<MailChimpSubscriberModel> newSubscribers)
{   
    if (string.IsNullOrEmpty(_defaultListId)) throw new ArgumentNullException(Res.Resource.MailChimpIntegrationNoListId);

    if (string.IsNullOrEmpty(_apiKey)) throw new ArgumentNullException(Res.Resource.MailChimpIntegrationNoApiKey);

    foreach (MailChimpSubscriberModel subscriber in newSubscribers)
    {
        string url = "https://" + _dataPoint + ".api.mailchimp.com/3.0/lists/" + _defaultListId + "/";

        Subscriber member = new Subscriber();
        member.email = subscriber.Email;
        member.subscribed = "subscribed";

        string jsonString = new JavaScriptSerializer().Serialize(member);

        //using (WebClient client = new WebClient())
        //{
        //    client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
        //    client.Headers[HttpRequestHeader.Authorization] = new AuthenticationHeaderValue("Basic", _apiKey).ToString();
        //    string HtmlResult = client.(url, jsonString);

        //    return true;
        //}

        using (var http = new HttpClient())
        {
            http.DefaultRequestHeaders.Authorization =
                 new AuthenticationHeaderValue("Basic", _apiKey);
            string content = await http.**GetStringAsync**(@"https://us11.api.mailchimp.com/3.0/lists");
            Console.WriteLine(content);
        }
    }
    return false;
}
ekad
  • 14,436
  • 26
  • 44
  • 46
PYROv1
  • 143
  • 1
  • 10

5 Answers5

10

I'm a bit late to this question, but as it took me half a day to figure it out, here there is my answer, so it can help others. I'm using MailChimp 3.0:

private void subscribeAddress() 
{
  string apiKey = "APIKEY-usX"; //your API KEY created by you.
  string dataCenter = "usX";
  string listID = "listID"; //The ListID of the list you want to use.

  SubscribeClassCreatedByMe subscribeRequest = new SubscribeClassCreatedByMe 
  {
      email_address = "somebodys@email.com",
      status = "subscribed"
  };
  subscribeRequest.merge_fields = new MergeFieldClassCreatedByMe();
  subscribeRequest.merge_fields.FNAME = "YourName";
  subscribeRequest.merge_fields.LNAME = "YourSurname";

  using (HttpClient client = new HttpClient())
  {
      var uri = "https://" + dataCenter + ".api.mailchimp.com/";
      var endpoint = "3.0/lists/" + listID + "/members";

      client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", apiKey);
      client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
      client.BaseAddress = new Uri(uri);

      //NOTE: To avoid the method being 'async' we access to '.Result'
      HttpResponseMessage response = client.PostAsJsonAsync(endpoint, subscribeRequest).Result;//PostAsJsonAsync method serializes an object to 
                                                                                            //JSON and then sends the JSON payload in a POST request
    //StatusCode == 200
    // -> Status == "subscribed" -> Is on the list now
    // -> Status == "unsubscribed" -> this address used to be on the list, but is not anymore
    // -> Status == "pending" -> This address requested to be added with double-opt-in but hasn't confirmed yet
    // -> Status == "cleaned" -> This address bounced and has been removed from the list

    //StatusCode == 404
    if ((response.IsSuccessStatusCode))
    {
       //Your code here
    }
  }
}

Here there are the classes SubscribeClassCreatedByMe and MergeFieldClassCreatedByMe

namespace Subscriber
{
  public class SubscribeClassCreatedByMe 
  {
    public string email_address { get; set; }
    public string status { get; set; }
    public MergeFieldClassCreatedByMe merge_fields { get; set; }
  }
}
namespace Subscriber
{
  public class MergeFieldClassCreatedByMe
  {
    public string FNAME { get; set; }
    public string LNAME { get; set; }
  }
}

Well, I hope this help!!

Aida
  • 151
  • 1
  • 5
  • While using same parameters through Postman, I am getting Error `403 The API key provided is linked to a different datacenter` – Pranav Singh Sep 14 '16 at 10:35
  • 1
    I am getting error in response `StatusCode: 400, ReasonPhrase: 'Bad Request'` – Pranav Singh Sep 15 '16 at 08:26
  • In my case I received a Bad Request response due to using bogus credentials (e.g. email: example@example.com). When using more realistic credentials it worked. – Dan Apr 22 '18 at 10:19
0

401 isn't "cannot use that method" it's "Unauthorized". You've got an authentication error. From the looks of things, you're not quite doing basic auth the right way. Check out this example for the details you're missing.

PS: the response that comes back from APIv3 is usually pretty helpful, so you should always make sure to look at that whole response, not just the status code.

TooMuchPete
  • 4,583
  • 2
  • 17
  • 21
  • Hi @TooMuchPete thanks for your response. I am currently getting a 404 error code whenever I try and send the json data to mailchimp. This is the message being sent: {Method: GET, RequestUri: 'https://us11.api.mailchimp.com/3.0/lists/myListKey/{"email":"testemail@test.com","subscribed":"subscribed"}', Version: 1.1, Content: , Headers: { Authorization: Basic myAPIkey }} – PYROv1 Aug 18 '15 at 10:26
  • That doesn't look like something you ought to be sending to MailChimp. If you're trying to make a GET request, you shouldn't be sending any body at all. What are you getting back in the body of MailChimp's response? – TooMuchPete Aug 18 '15 at 18:51
0

It works if you change auth to these lines:

String username = "abc"; //anything
String password = apiKey; //your apikey
String encoded = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));

client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", encoded);
Richie Thomas
  • 3,073
  • 4
  • 32
  • 55
Amigo
  • 47
  • 8
0

Below code snippet is should work on .NET Core 2.1 using Mailchimp API V3.0:

    string url = @"https://" + mailchimpInstance + ".api.mailchimp.com/3.0/lists/" + ListId + "/members";

     var info = new Info() { email_address = "example@gmail.com", status = "subscribed" };
        var infoJson = JsonConvert.SerializeObject(info);

     using (var client = new HttpClient())
        {

            var uri = "https://" + mailchimpInstance + ".api.mailchimp.com/";
            var endpoint = "3.0/lists/" + ListId + "/members";

            try
            {

                client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic",ApiKey);
                client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                client.BaseAddress = new Uri(uri);
                var content = new StringContent(infoJson.ToString(), Encoding.UTF8, "application/json");
                 HttpResponseMessage response = await client.PostAsync(endpoint, content);

                var responseString = await response.Content.ReadAsStringAsync();
                Console.WriteLine("Response from server -> " + responseString);

                return Ok();
Fayeeg
  • 1
  • 1
  • What is content, what is Info(), where's your catch? How do you have your bool set up? Too much missing here to be useful. – Ryan Jan 19 '21 at 17:10
0

Add into References MailChimp.Net.dll than you can define an interface like

IMailChimpManager manager = new MailChimpManager(ConfigurationManager.AppSettings["MailChimpApiKey"].ToString());

than you can add or update your client in your MailChimp list

                Member m = await manager.Members.AddOrUpdateAsync(ConfigurationManager.AppSettings["MailChimpListId"].ToString(), new Member { EmailAddress = _email, EmailType = "html", Status = Status.Pending});
            m = await manager.Members.AddOrUpdateAsync(ConfigurationManager.AppSettings["MailChimpListId"].ToString(), new Member { EmailAddress = _email, EmailType = "html", Status = Status.Subscribed });

It is very simple.. I think...

Hasta Dhana
  • 4,699
  • 7
  • 17
  • 26
Zoltan
  • 137
  • 10