Tomas Kanok
Tomas Kanok

Reputation: 135

Connection to MailChimp v3.0 API

I have a problem connecting to the new MailChimp 3.0 API (2.0 works fine).

I would like to send some subscriber. What am I doing wrong? I am probably trying to send the apikey in the wrong way (HTTP Basic authentication). The documentation is here but I am not able to make it work: http://developer.mailchimp.com/documentation/mailchimp/guides/get-started-with-mailchimp-api-3/.

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(@"https://us12.api.mailchimp.com/3.0/lists/<listnumber>/members/");

string json = @"
    {
        ""email_address"": ""[email protected]"",
        ""status"": ""subscribed"",
        ""merge_fields"": {
                    ""FNAME"": ""Urist"",
            ""LNAME"": ""McVankab""
        }
    }
";

byte[] data = Encoding.UTF8.GetBytes(json);

request.Method = "POST";
request.Headers.Add("user", "<mykeynumber>");
request.ContentType = "application/json";
request.ContentLength = data.Length;

using (System.IO.Stream stream = request.GetRequestStream())
{
    stream.Write(data, 0, data.Length);
}

Upvotes: 4

Views: 1839

Answers (2)

Nathan Prather
Nathan Prather

Reputation: 2106

Anyone else coming in here, I've been playing around and I think it's best at this point to call it using the ASP.NET Web API library. I got this to work following this example: https://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client

and merging it together with the answer from this question: Calling MailChimp API v3.0 with .Net

The example uses a simple Windows console app, but can be ported to web:

// New code:
    static HttpClient client = new HttpClient();

    static void Main()
    {
        RunAsync().Wait();
    }

    static async Task RunAsync()
    {
        // New code:
        client.BaseAddress = new Uri( "https://us5.api.mailchimp.com/3.0/" );

        client.DefaultRequestHeaders.Accept.Clear();

        client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue( "application/json" ) );

        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( "Basic", "<YOUR_API_KEY_HERE>" );

        try {

            HttpResponseMessage response = await client.GetAsync( "" );

            if ( response.IsSuccessStatusCode ) {

                var results = await response.Content.ReadAsStringAsync();

                Console.WriteLine( $"results  (HTTP Status = {results})" );
            }
            else {

                Console.WriteLine( $"ERROR (HTTP Status = {response.StatusCode}" );
            }


        }
        catch ( Exception e ) {
            Console.WriteLine( e.Message );
        }

        Console.ReadLine();
    }

Upvotes: 0

TooMuchPete
TooMuchPete

Reputation: 4643

The primary issue appears to be authentication. Here is a good SO answer that demonstrates HTTP Basic Auth with HTTPWebRequest.

Upvotes: 1

Related Questions