Last active
September 5, 2019 10:22
-
-
Save michelepatrassi/1a5a148a0b5a44597d4fd45c976b22fc to your computer and use it in GitHub Desktop.
Cloud Function cron, add 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 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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment