Firebase Cloud Functions + MailChimp: Add A New Subscriber

Firebase

I am assuming that you already have a Mailchimp account and created a project on the Firebase Console.

Let’s set up the node.js environment to write cloud functions.

npm install -g firebase-tools

Then,

firebase login

If you have an error about node_modules at this stage, you might need to re-install node and npm.

After that, create a directory and CD to it and run:

firebase init functions

Once all the dependencies are done, the folder structure should look like this:

Next, install the Mailchimp package.

CD to functions folder and run.

npm install --save mailchimp-api-v3

Then, import it to index.js.

var Mailchimp = require('mailchimp-api-v3')

After that, instantiate MailChimp object with your API Key.

var mailchimp = new Mailchimp(yourkey);

To get the API key, log in to MailChimp→ Profile Name at the top right → Account → Extras → API Key.

Now, declare addSubscriber() HTTP function in the index.js file.

exports.addSubscriber = functions.https.onRequest((req, res) => {

  mailchimp.post('/lists/id/members', {
      merge_fields: {
        "FNAME": req.body.fname,
        "LNAME": req.body.lname
      },
      email_address: req.body.email,
      status: 'subscribed',
      tags: ["incomplete_purchase"]
    })
    .then(function (results) {
      res.json(results);
    })
    .catch(function (err) {
      res.json(err);
    })

})

Make sure to replace id with your Audience ID /lists/65tr2f288r/members. To get that, choose the Audience → View Contacts → Settings → Audience Name and Defaults → Audience ID.

As you can see, I am adding a new subscriber with a few request body parameters FNAME, LNAME, email_address, status and tags.

You can find all the available parameters on the MailChimp API Documentation.

To get this function working properly, you need to enable the paid plan on Firebase in order to communicate with Third-party APIs such as MailChimp.

Let’s deploy it.

CD to thefunctions folder and run.

firebase deploy

Once it’s deployed, it will provide a URL link to run the functions. You can simply go to any HTTP client to test it out.

Voila…it works! If you go back to your Mailchimp account, you can see a new subscriber added there.

If it does not work for some reason, just write to me in the comments section below and I will stand by to help.

Sharing is caring!

You may also like this:

  • Vue.js + Firebase: Track Multiple Users’ Location Real-Time
  • Learn Firebase Cloud Storage Quickly [Guide]
  • Deploying Vue.js App To Firebase Hosting in a minute
  • Vue.js + Firebase: Role-Based Authentication & Authorization
  • JavaScript + Firebase: Get Logged In User Data [RTDB]