Integration between Mailchimp and React Native app

Asked

Viewed 115 times

4

I’m a beginner in React Native. I’m basically trying to accomplish the integration between my application in React Native and Mailchimp, what I want to do is: Once the user provides us with his email, and sends the form, then an email is sent to him 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 to 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: ''

    }
);

}

Thanks in advance!

2 answers

2

It follows excerpt from 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

  • 1

    Very good, I like this option, I will try to implement this way, if all goes well, I come back here and mark as answered, and put my code!!

  • 1

    Show @Jeffersonbruchado, I await your return!

2


Everything quiet around here? Amid some research and thoughts, I had a possible idea for the resolution of this problem, follows below what I did to realize the integration between Mailchimp and Firebase for an React Native Application:

First of all, I did some research, and I realized that the best way to do that would be from the server side, since I was already using Firebase’s Realtime Database, and so I decided to use Cloud Functions to solve this problem, I realized the creation of a Cloud Function, that keeps checking the state of the Database, and when it is received some data, it is then fired a POST for the Mailchimp API, follows 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 Firebase’s Cloud Functions, once any insertion of Realtime Database is performed, this trigger triggers this function.

Thank you for your quick responses!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.