Adding subscribers to a list in Mail Chimp 3.0 in KENTICO

Khoa Nguyen asked on August 6, 2018 06:33

It work with curl

curl --request POST \
--url 'https://us19.api.mailchimp.com/3.0/lists/439db5911d/members/' \
--user 'anystring:6d43f4b7e3b8271c2508ac6d3a0fc2ce-us19' \
--header 'content-type: application/json' \
--data '{"apikey":"6d43f4b7e3b8271c2508ac6d3a0fc2ce-us19","email_address":"myemail@gmail.com","status":"subscribed"}' \
--include

I want to create a widget to add subscribe to mailchimp

    JavaScriptSerializer serializer = new JavaScriptSerializer();
    var info = new Info() { email_address = "myemail@gmail.com", status = "subscribed", apikey= "6d43f4b7e3b8271c2508ac6d3a0fc2ce-us19" };
    var infoJson = serializer.Serialize(info);

    string url = @"https://us19.api.mailchimp.com/3.0/lists/439db5911d/members";
    HttpClient client = new HttpClient();
    client.DefaultRequestHeaders.Clear();

    client.BaseAddress = new Uri(url);
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    var user = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes("anystring:6d43f4b7e3b8271c2508ac6d3a0fc2ce-us19"));
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", user);

    HttpResponseMessage response = client.PostAsJsonAsync(url, infoJson).Result;

    text.Text = response.ToString();

public class Info { public string email_address { get; set; } public string status { get; set; } public string apikey { get; set; } }

It return status 400, anyone can help me?

Here is response

StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: { X-Request-Id: a2269c5d-0ef0-4a81-865c-7f1fb21c3e40 Link: ; rel="describedBy" Connection: close Date: Mon, 06 Aug 2018 04:29:06 GMT Set-Cookie: _AVESTA_ENVIRONMENT=prod; path=/ Set-Cookie: _mcid=1.8049c88b78f20da02cd07d042d343aef; expires=Tue, 06-Aug-2019 04:29:06 GMT; Max-Age=31536000; path=/; domain=.mailchimp.com Server: openresty Content-Length: 370 Content-Type: application/problem+json; charset=utf-8 }

Correct Answer

Arun Kumar answered on August 6, 2018 13:39

Use below code to get the actual error message from the API

  try
        {
            string url = @"https://us19.api.mailchimp.com/3.0/lists/439db5911d/members";
            var user = Convert.ToBase64String(Encoding.UTF8.GetBytes("anystring:6d43f4b7e3b8271c2508ac6d3a0fc2ce-us19"));
            WebRequest request = HttpWebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/json";
            using (var streamWriter = new StreamWriter(request.GetRequestStream()))
            {
                string json = "{\"email_address\":\"myemail@gmail.com\"," +
                              "\"status\":\"subscribed\"}";

                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();
            }
            request.Headers.Add("apikey", "cc66928d7dc9016072a80ef2bb3fc08c-us19");
            request.Headers["Authorization"] = "Basic " + user;
            var wresponse = (HttpWebResponse)request.GetResponse();

            var responseString = new StreamReader(wresponse.GetResponseStream()).ReadToEnd();


        }
        catch (WebException webEx)
        {
            if (null != webEx.Response)
            {
                using (var stream = webEx.Response.GetResponseStream())
                {
                    using (var reader = new StreamReader(stream))
                    {
                        var errorMsg = reader.ReadToEnd();
                    }
                }
            }
        }

In catch errorMsg you will get the error details from mailchimp error format which you can parse to read the error message.

0 votesVote for this answer Unmark Correct answer

Recent Answers


Arun Kumar answered on August 6, 2018 10:30 (last edited on August 6, 2018 10:32)

Hi Khoa,

Please try below code, it should work fine.

 JavaScriptSerializer serializer = new JavaScriptSerializer();
            var info = new Info() { email_address = "myemail@gmail.com", status = "subscribed", apikey = "6d43f4b7e3b8271c2508ac6d3a0fc2ce-us19" };
            var infoJson = serializer.Serialize(info);

            string url = @"https://us19.api.mailchimp.com/3.0/lists/439db5911d/members";
            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Clear();

            client.BaseAddress = new Uri(url);
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var user = Convert.ToBase64String(Encoding.UTF8.GetBytes("anystring:6d43f4b7e3b8271c2508ac6d3a0fc2ce-us19"));
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", user);
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post,url);
            request.Content = new StringContent(infoJson,
                                                Encoding.UTF8,
                                                "application/json");

            var res = client.SendAsync(request).Result;

There was an issue in setting up the content type in default request header. You should set the encoding with content type in request message or use WebRequest instead of HttpClient which is more easier to use.

0 votesVote for this answer Mark as a Correct answer

Khoa Nguyen answered on August 6, 2018 13:01 (last edited on August 6, 2018 13:05)

Hi Samira Grazitti,

I had tried your code and see something change.

For new member add to list, it work good.( Status code 200)

But for email already exist, it show 400 but no message like 'User already exist'

Here is code return when user exist:

StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: { X-Request-Id: 82c401c6-cbcd-48f3-ac2c-88715b369a3a Link: ; rel="describedBy" Connection: close Date: Mon, 06 Aug 2018 10:58:56 GMT Set-Cookie: _AVESTA_ENVIRONMENT=prod; path=/ Set-Cookie: _mcid=1.c34b5b11887685c962e4fd5c589659d6; expires=Tue, 06-Aug-2019 10:58:56 GMT; Max-Age=31536000; path=/; domain=.mailchimp.com Server: openresty Content-Length: 273 Content-Type: application/problem+json; charset=utf-8 }
0 votesVote for this answer Mark as a Correct answer

Anton Grekhovodov answered on August 6, 2018 14:22

Hi,
Try to use MailChimp.Net library, it's pretty easy. The library has all needed methods to manage subscribers/lists/etc. And before adding subscriber, you can call Members.Exist/ExistAsync method to check if a record exists. Another advantage of the library, you don't need to worry about building requests with correct headers.

0 votesVote for this answer Mark as a Correct answer

Khoa Nguyen answered on August 6, 2018 18:12

Thank you Samira Grazitti, it work perfectly !!

0 votesVote for this answer Mark as a Correct answer

Khoa Nguyen answered on August 6, 2018 18:15

Hi Anton Grekhovodov,

MailChimp library look goods, but you can show me how to control status code if can add subscriber or not.

I had make a successfully add member to list, but it return nothing.

0 votesVote for this answer Mark as a Correct answer

Anton Grekhovodov answered on August 7, 2018 06:52

Hi,
The method from the library doesn't returns a status code, it returns object of Member type. Example, how to use the library:

var mailChimpManager = new MailChimpManager(apiKey);
var subscriberExists = await mailChimpManager.Members.ExistsAsync(listId, email);
if (subscriberExists)
{
   //return if necessary;
}

//create a new subscriber
var newMember = new Member() {EmailAddress = email, Status = Status.Subscribed};
// to add custom fields use
// newMember.MergeFields.Add(Key, Value);

//method returns Member object
var newMemberResult = await mailChimpManager.Members.AddOrUpdateAsync(listId, newMember);
if (newMemberResult != null && !string.IsNullOrEmpty(newMember.Id))
{
    //subscriber has been added
}
0 votesVote for this answer Mark as a Correct answer

   Please, sign in to be able to submit a new answer.