4

I am new to ReactJS and I am trying to build this app that need to use mailchimp so the user can subscribe for newsletter. I need to make a request using axios? can someone guide me through this? where do i put my api key? Did I do it correct in the bellow code? i put my mailchimps username in 'username' and my apikey in 'xxxxxxxxxxxxxxxxxxx-us16', however, i got the 401 error saying Unauthorized, BUT my console did say Fetch Complete: POST and caught no error.

import React, {Component} from 'react';
import './Subscribe.css';

class Subscribe extends Component {
  sub = () => {
    let authenticationString = btoa('username:xxxxxxxxxxxxxxxxxxx-us16');
    authenticationString = "Basic " + authenticationString;

    fetch('https://us16.api.mailchimp.com/3.0/lists/xxxxxxxxx/members', {
      mode: 'no-cors',
      method: 'POST',
      headers: {
        'Authorization': authenticationString,
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        email_address: "somedude@gmail.com",
        status: "subscribed",
      })
    }).then(function(e){
        console.log('complete')
    }).catch(function(e){
        console.log("fetch error");
    })
  };

  render () {
    return(
      <div>
        <button onClick={this.sub}> subscribe </button>
      </div>
    );
  };
};
dg2903
  • 613
  • 6
  • 12

3 Answers3

2

In the documentation, the curl example uses the --user flag. Using this to convert curl commands to an equivalent js code, you need the 'auth' property on the option object of the fetch to make it work.

fetch('https://us16.api.mailchimp.com/3.0/lists/xxxxxxxxx/members', {
  method: 'POST',
  headers: {
    'content-type': 'application/json'
  },
  body: JSON.stringify({
    email_address: "somedude@gmail.com",
    status: "subscribed",
  },
  auth: {
    'user': 'username',
    'pass': 'xxxxxxxxxxxxxxxxxxx-us16'
  })
})
Mμ.
  • 8,382
  • 3
  • 26
  • 36
  • @dg2903 I've updated my code and removed unnecessary bits. Can you try if that works? – Mμ. Jul 02 '17 at 02:16
  • still error 401. in the documenation they say: MailChimp does not support client-side implementation of our API using CORS requests due to the potential security risk of exposing account API keys. does that have anything to do with the error? I am writing this in pure reactjs – dg2903 Jul 02 '17 at 23:43
  • 1
    I see. That makes sense. Doing this in the client side will expose your API key. This should be done in your backend. – Mμ. Jul 03 '17 at 00:29
1

It took me a while to get the syntax right for this. This is an example of a working request using nodejs in a server-side-rendered reactjs app using axios.

It appears "get" requests won't work for this method because of the 401 error: MailChimp does not support client-side implementation of our API using CORS requests due to the potential security risk of exposing account API keys.

However, patch, put, and post seem to work fine.

Example (using async / await)

// Mailchimp List ID
let mcListId = "xxxxxxxx";

// My Mailchimp API Key
let API_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxxxx-us12";

// Mailchimp identifies users by the md5 has of the lowercase of their email address (for updates / put / patch)
let mailchimpEmailId = md5(values["unsubscribe-email-address"].toLowerCase());

var postData = {
    email_address: "somedude@gmail.com",
    status: "subscribed"
};

// Configure headers
let axiosConfig = {
    headers: {
        'authorization': "Basic " + Buffer.from('randomstring:' + API_KEY).toString('base64'),
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    }
};

try {
    let mcResponse = await axios.post('https://us12.api.mailchimp.com/3.0/lists/' + mcListId + '/members', postData, axiosConfig)
    console.log("Mailchimp List Response: ", mcResponse);

} catch(err) {
    console.log("Mailchimp Error: ", err);
    console.log("Mailchimp Error: ", err["response"]["data"]);
}
Matthew Rideout
  • 7,330
  • 2
  • 42
  • 61
-1

You can using the method described there: AJAX Mailchimp signup form integration

You will need to use JSONP otherwise you will get a CORS error.

If you use a modern environment (I mean not jQuery), you can achieve this method using a library like qs or queryString to transform your form data to an uri.

Your final url could look something like:

jsonp(`YOURMAILCHIMP.us10.list-manage.com/subscribe/post-json?u=YOURMAILCHIMPU&${queryString.stringify(formData)}`, { param: 'c' }, (err, data) => {
  console.log(err);
  console.log(data);
});

It's a bit hacky and I guess Mailchimp can remove this from one day to the other as it's not documented, so if you can avoid it, you'd better do.

adriendenat
  • 3,445
  • 1
  • 25
  • 25
  • I will try this when i get back from vacation. I believe I might have tried this method and it didnt work, Maybe I've done something wrong. The document did say that they no longer allow us to making any request call from using client-side implementation, it required a back-end. I will try this again when i get back. – dg2903 Sep 16 '17 at 00:43
  • I tried before I answered and it worked fine for me. Good luck. – adriendenat Sep 16 '17 at 18:05
  • @TimDau you need to use jsonp as described there. I'll update the answer. https://stackoverflow.com/questions/8425701/ajax-mailchimp-signup-form-integration#answer-50611587 – adriendenat May 01 '19 at 16:53