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 !!