Integration between MailChimp and React Native app

5

I am a beginner in React Native. I'm basically trying to perform the integration between my application in React Native and MailChimp, what I want to do is: From the moment the user provides us with their email, and send the form, then an email is triggered for it through MailChimp, I use Firebase to create my own email base, but I would like to automate the sending task via mailchimp. The method used to save emails in Firebase is as follows:

saveEmail() {
var id = firebase.database().ref().child('xxx').push().key;
const valueEmail = this.state.input;
const valueName = this.state.name;

firebase.database().ref('/xxx/' + id).set({
    email: valueEmail,
    name: valueName
});

//here where the post for the mailchimp API will be carried out

this.setState(
    {
        isModalVisible: !this.state.isModalVisible,
        valid: false,
        name: '',
        input: ''

    }
);

}

Thank you in advance!

    
asked by anonymous 05.09.2018 / 14:41

2 answers

3

Everything quiet around here? In the middle of some researches and thoughts, I had a possible idea to solve this problem, here is what I did to integrate MailChimp and Firebase into a React Native Application:

First of all, I did some research, and realized that the best way to do this would be for the server side, since I was already using the Firebase Realtime Database, so I decided to use the Cloud Functions to solve this problem. creating a Cloud Function, which is checking the state of the Database, and when a data is received, a POST is triggered for the MailChimp API, below the function created for this:

const functions = require('firebase-functions');

\Code suppressed here

exports.onDataAdded = functions.database.ref('/xxx/{id}').onCreate((snap, context) => {
    const data = snap.val();
    var fetch = require('isomorphic-fetch');
    var btoa = require('btoa');

    console.log(data.email);
    // POST /lists/{list_id}/members
    // Add a new list member

    var MAILCHIMP_API_KEY = 'Key Here';
    var listId = 'Id Here';
    // NOTE: mailchimp's API uri differs depending on your location. us6 is the east coast. 
    var url = 'https://<dc>.api.mailchimp.com/3.0/lists/' + listId + '/members';
    var method = 'POST';
    var headers = {
        'authorization': "Basic " + btoa('randomstring:' + MAILCHIMP_API_KEY),
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    };
    var body = JSON.stringify(
        {
            email_address: data.email,
            status: 'subscribed',
            'language': data.language,
            merge_fields: { FNAME: data.name }
        }
    );

    return fetch(url, {
        method,
        headers,
        body
    }).then(resp => resp.json())
        .then(resp => {
            return console.log(resp)
        })
        .catch(error => {
            throw new Error(error.statusText)
        });
});

With this function created in the Firebase Cloud Functions, as soon as some Realtime Database insert is performed, this trigger triggers this function.

Thanks for the quick answers !!

    
08.09.2018 / 02:37
2

Follow the code that performs this integration from node.js and axios

const axios = require('axios')

const mailchimpOptions = {
  apiKey: 'xxxxxxxxxxxxxxx',
  listId: 'xxxxxxxxxxxxxxxxx',
}

const axiosInstance = axios.create({
  auth: {
    username: 'anystring',
    password: mailchimpOptions.apiKey,
  },
})

function subscribe(req, res) {
  axiosInstance.post('https://us15.api.mailchimp.com/3.0/lists/${mailchimpOptions.listId}/members', {
    email_address: req.body.email_address,
    status: 'subscribed',
  }).then((response) => {
    if (response.data.status === 'subscribed') {
      res.send({
        success: true,
        message: 'Obrigado! Estamos direcionando seu contato para nossos consultores.',
      })
    } else {
      res.send({
        success: false,
        message: 'Parece que você já está cadastrado. Outros assuntos mande um e-mail para xxxxxxxx',
      })
    }
  }).catch((err) => {
    if (err.response.data.title === 'Member exists') {
      res.send(400, {
        success: false,
        message: 'Obrigado pelo interesse! Seu contato já está cadastrado.',
      })
    } else {
      res.send({
        success: false,
        message: 'Parece que você já está cadastrado. Outros assuntos mande um e-mail para xxxxxxxx',
      })
    }
  })
}

module.exports = subscribe

    
05.09.2018 / 17:02