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!!
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!!
– Jefferson Bruchado
Show @Jeffersonbruchado, I await your return!
– Vinicius Zomer