Created
August 30, 2019 15:43
-
-
Save skatkov/5eed0aba8ccc0d477017ead665f3c2c6 to your computer and use it in GitHub Desktop.
netlify function: mailchimp subscribe
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
/* eslint-disable */ | |
const axios = require('axios'); | |
require('dotenv').config(); | |
exports.handler = function(event, context, callback) { | |
const password = process.env.MAILCHIMP_API_KEY; | |
console.log(password); | |
if (!password) { | |
console.error('No MailChimp API Key include in environment variables'); | |
process.exit(1); | |
} | |
const parsedBody = JSON.parse(event.body); | |
const email = parsedBody.email; | |
const re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; | |
if (!re.test(email)) { | |
return callback(null, { | |
statusCode: 400, | |
body: JSON.stringify({ msg: 'Invalid Email' }), | |
}); | |
} | |
const body = { | |
email_address: email, | |
status: 'subscribed', | |
}; | |
const username = 'pairity'; | |
axios({ | |
method: 'post', | |
url: 'https://us16.api.mailchimp.com/3.0/lists/04626a0e95/members/', | |
data: body, | |
auth: { | |
username, | |
password, | |
}, | |
}) | |
.then(response => | |
callback(null, { | |
statusCode: 200, | |
body: JSON.stringify({ msg: 'Thanks for subscribing!' }), | |
}), | |
) | |
.catch(({ response }) => { | |
let title = ''; | |
if (response && response.data && response.data.title) { | |
title = response.data.title; | |
} | |
callback(null, { | |
statusCode: 500, | |
body: JSON.stringify({ | |
msg: `Failed to subscribe. ${title}`, | |
}), | |
}); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment