Firebase Cloud Functions + MailChimp: Add A New Subscriber

Cloud Functions Firebase

Assuming that you already have a mailchimp account and created a project on the Firebase Console

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

npm install -g firebase-tools

Then,

firebase login

if you have get 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 looks like this.

Next, Install 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, login 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, 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 would need to enable paid plan on Firebase in order to communicate with Third party APIs such as MailChimp.

Let’s Deploy it.

CD to functions 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 cleint to test it out. 

wola…it works! If you go back to your mailchimp account, you can see a new subscribed added there.

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

 

Comments Count: 0 0