Created
March 9, 2018 21:39
-
-
Save segovia94/25882b934108b66b86af4304be60fdc4 to your computer and use it in GitHub Desktop.
Subscribe a person to a Mailchimp list using an Azure serverless Function App
This file contains hidden or 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
/** | |
* Expected query parameters via GET or POST | |
* | |
* email: a valid email address | |
* firstName: the first name | |
* lastName: the persons last name | |
* | |
* Don't forget to replace the API key and List ID. | |
*/ | |
// Add the https://docs.microsoft.com/en-us/azure/azure-functions/functions-reference-node | |
const MailchimpApi = require('mailchimp-api-v3') | |
// Add your mailchimp API Key | |
const mailchimp = new MailchimpApi('API-KEY-GOES-HERE') | |
// Set the ID for the list people will subscribe to. | |
const listId = '1234567' | |
module.exports = function (context, req) { | |
context.log('JavaScript HTTP trigger function processed a request.') | |
let errorMessage = false | |
// Set fields based on GET query or POST body. | |
const fields = (req.query || req.body) | |
// Set error message if fields are missing | |
if (!fields.email) { | |
errorMessage = "Oops! Looks like you forgot to add a valid email address." | |
} | |
else if (!fields.firstName || !fields.lastName) { | |
errorMessage = "Please provide a First and Last Name." | |
} | |
// Exit if there is an error message. | |
if (errorMessage) { | |
context.res = { | |
status: 400, | |
body: { | |
msg: errorMessage | |
} | |
} | |
context.done() | |
return | |
} | |
// Create the data we plan to send to Mailchimp. | |
const postDate = { | |
"email_address": fields.email, | |
"status": "subscribed", | |
"merge_fields": { | |
"FNAME": fields.firstName, | |
"LNAME": fields.lastName | |
} | |
} | |
// Send request to Mailchimp. | |
context.log('start request') | |
mailchimp.post('/lists/' + listId + '/members', postDate) | |
.then(function(results) { | |
context.res = { | |
body: { | |
response: 'success', | |
msg: "Excellent! Your email address has successfully been added to our Newsletter." | |
} | |
} | |
context.done() | |
}) | |
.catch(function (err) { | |
// Log the error. | |
context.log(err) | |
context.res = { | |
status: err.status, | |
body: { | |
msg: err.detail | |
} | |
} | |
context.done() | |
}) | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment