Created
June 24, 2020 18:51
-
-
Save mornir/32d128dbea476a8d05768b08c94b3369 to your computer and use it in GitHub Desktop.
Submit email to Mailchimp via Netlify Form. Delete data from Netlify after submission to Mailchimp.
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
const axios = require('axios') | |
const crypto = require('crypto') | |
const region = process.env.MAILCHIMP_API_KEY.split('-')[1] | |
const apiRoot = `https://${region}.api.mailchimp.com/3.0/lists/${process.env.MAILCHIMP_LIST_ID}/members/` | |
function deleteSubmission(id) { | |
const url = `https://api.netlify.com/api/v1/submissions/${id}?access_token=${process.env.NETLIFY_ACCESS_TOKEN}` | |
return axios.delete(url) | |
} | |
exports.handler = async event => { | |
const { id: mail_id, email } = JSON.parse(event.body).payload | |
if (!email) { | |
return { | |
statusCode: 400, | |
body: 'no email was provided', | |
} | |
} | |
let emailhash = crypto | |
.createHash('md5') | |
.update(email) | |
.digest('hex') | |
await axios({ | |
method: 'put', | |
url: apiRoot + emailhash, | |
data: { | |
email_address: email, | |
status: 'subscribed', | |
}, | |
auth: { | |
username: 'anythingreally', | |
password: process.env.MAILCHIMP_API_KEY, | |
}, | |
}).catch(err => { | |
console.log('error adding email to mailchimp', err.response.data.detail) | |
return { statusCode: 500, body: JSON.stringify(err.response.data) } | |
}) | |
await deleteSubmission(mail_id).catch(err => { | |
console.log('error deleting email', email) | |
return { statusCode: 500, body: JSON.stringify(err) } | |
}) | |
return { | |
statusCode: 200, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment