Last active
September 5, 2019 10:30
-
-
Save michelepatrassi/3c2f77bf481760c3c5e1116a00f0c173 to your computer and use it in GitHub Desktop.
Cloud Function cron, add and update mailchimp contact
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as functions from 'firebase-functions'; | |
import * as admin from 'firebase-admin'; | |
import MailchimpApi = require('mailchimp-api-v3'); | |
import md5 = require('crypto-js/md5'); | |
const CRON_SCHEDULE = '* * * * *'; | |
const API_KEY = 'YOUR_API_KEY'; | |
const AUDIENCE_ID = 'YOUR_AUDIENCE_ID'; | |
export const cronMailchimp = functions.region('europe-west1').pubsub | |
.schedule(CRON_SCHEDULE).onRun(async context => { | |
const mailchimpApi = new MailchimpApi(API_KEY); | |
const userRefs = await admin.firestore().collection('users').listDocuments(); | |
for (const userRef of userRefs) { | |
const userDoc = await userRef.get(); | |
const user = userDoc.data(); | |
console.log(`mailchimp.ts - handling user ${userRef.id} with email ${user.email}`); | |
try { | |
await patchContact(mailchimpApi, AUDIENCE_ID, user); | |
console.log(`mailchimp.ts - user updated!`, ); | |
} catch (e) { | |
console.log(`mailchimp.ts - catched updated error (probably contact does not exist)`, e); | |
try { | |
await createContact(mailchimpApi, AUDIENCE_ID, user); | |
console.log(`mailchimp.ts - user created!`, ); | |
} catch (e) { | |
console.error(`mailchimp.ts - failed to create contact!`, e); | |
} | |
} | |
} | |
}) | |
const createContact = async (mailchimpApi, audienceId, user) => { | |
const body = { | |
email_address: user.email, | |
status: "subscribed", | |
merge_fields: { | |
FNAME: user.name, | |
LNAME: user.surname | |
} | |
}; | |
return mailchimpApi.post(`/lists/${audienceId}/members/`, body); | |
} | |
const patchContact = async (mailchimpApi, audienceId, user) => { | |
const body = { | |
merge_fields: { | |
FNAME: user.name, | |
LNAME: user.surname | |
} | |
}; | |
const memberId = md5(user.email.toLowerCase()); | |
return mailchimpApi.patch(`/lists/${audienceId}/members/${memberId}`, body); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment