Created
August 5, 2019 21:21
-
-
Save joshuap/dbb0ad23648c09ce3383801675da034e to your computer and use it in GitHub Desktop.
Netlify function to tag subscribers in ConvertKit
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
// Netlify function to tag subscribers in ConvertKit | |
// https://www.netlify.com/products/functions/ | |
// POST to /.netlify/functions/tag?id={subscriberId} with JSON array of tag ids: `[{tagId}, {tagId}, ...]` | |
const request = require("request-promise"); | |
const apiKey = process.env.CONVERTKIT_API_KEY; | |
const apiSecret = process.env.CONVERTKIT_API_SECRET; | |
exports.handler = function(event, context, callback) { | |
let headers = {}; | |
if (process.env.NODE_ENV === "dev") { | |
headers["Access-Control-Allow-Origin"] = "*" | |
} | |
if (event.httpMethod !== "POST") { | |
return callback(null, { | |
statusCode: 200, // Return 200 for CORS/OPTIONS | |
headers: headers, | |
body: "please send a post request", | |
}); | |
} | |
const tagIds = JSON.parse(event.body); | |
const params = event.queryStringParameters || {}; | |
const subscriberId = params.id; | |
const subscriberUrl = `https://api.convertkit.com/v3/subscribers/${subscriberId}?api_secret=${apiSecret}`; | |
// Get the subscriber record | |
request.get({ | |
uri: subscriberUrl, | |
json: true, | |
simple: false, | |
resolveWithFullResponse: true, | |
}).then((res) => { | |
if (res.statusCode !== 200) { | |
return callback(null, { | |
statusCode: 422, | |
headers: headers, | |
body: `error: invalid get response: ${res.statusCode}`, | |
}); | |
} | |
// Subscribe them to the tag | |
const email = res.body.subscriber.email_address | |
Promise.all( | |
tagIds.map(function(tagId) { | |
return request.post({ | |
url: `https://api.convertkit.com/v3/tags/${tagId}/subscribe?api_key=${apiKey}&email=${encodeURIComponent(email)}` | |
}); | |
}) | |
).then(() => { | |
callback(null, { | |
statusCode: 200, | |
headers: headers, | |
body: "ok", | |
}); | |
}).catch(callback); | |
}).catch(callback); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment