Skip to content

Instantly share code, notes, and snippets.

@matthiasnys
Last active December 28, 2021 14:02
Show Gist options
  • Save matthiasnys/0746b2519f9c91dd36dc69c3a6fd4e65 to your computer and use it in GitHub Desktop.
Save matthiasnys/0746b2519f9c91dd36dc69c3a6fd4e65 to your computer and use it in GitHub Desktop.
Lambda code for the webhook
// Define some constants:
const SENDGRID_API_KEY = '' // API key for sendgrid
const SENDGRID_TEMPLATE_ID = '' // Create a template in Sendgrid, add the id here
const MOLLIE_TOKEN = 'live_...' // Mollie api token.
module.exports.webhook = async (event) => {
// 1: Parse the event
let realBody = JSON.parse(event.body)
let amount = null
let email = null
let name = null
let firstName = null
let submissionId = realBody.data.submissionId
for (let i = 0; i < realBody.data.fields.length; i++) {
let item = realBody.data.fields[i];
if (item.label === 'Totaal' && item.type === 'CALCULATED_FIELDS') {
amount = item.value
}
if (item.label === 'Email' && item.type === 'INPUT_EMAIL') {
email = item.value
}
if (item.label === 'Naam' && item.type === 'INPUT_TEXT') {
name = item.value
}
if (item.label === 'Details' && item.type === 'INPUT_TEXT') {
firstName = item.value
}
}
// Check required properties
if (!amount || !email || !name || !firstName || !submissionId || !respondentId ) {
return {
statusCode: 400,
body: JSON.stringify(
{
message: "Missing properties. Please fix me!",
input: { amount, email, name, firstName, submissionId, respondentId },
},
null,
2
),
};
}
// 2: Create an order and send to Mollie
var order = { amount, email, name, firstName, submissionId, respondentId }
const response = await sendToMollie(order)
// Check if we have a valid payment link from Mollie
if (!response._links.paymentLink.href) {
return {
statusCode: 400,
body: JSON.stringify(
{
message: "Something went wrong creating the payment request (mollie)",
input: { response },
},
null,
2
),
};
}
// Add the paymentLink to the order
order.paymentLink = response._links.paymentLink.href
// 3: Send an e-mail using the sendgrid api
let sendGridResponse = await sendPaymentEmail(order)
return {
statusCode: 200,
body: JSON.stringify(
{
message: "Go Serverless v2.0! Your function executed successfully!",
input: response,
},
null,
2
),
};
};
async function sendToMollie(order) {
var myHeaders = new fetch.Headers();
myHeaders.append("Authorization", `Bearer ${MOLLIE_TOKEN}`);
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
var urlencoded = new URLSearchParams();
urlencoded.append("amount[currency]", "EUR");
urlencoded.append("amount[value]", `${order.amount}.00`);
urlencoded.append("description", `Order #${order.submissionId} - ${order.name}`);
urlencoded.append("redirectUrl", "https://b-nys.com");
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: urlencoded,
redirect: 'follow'
};
const response = await fetch("https://api.mollie.com/v2/payment-links", requestOptions)
if (response.status === 201) {
return response.json() // Parse it
} else {
let responseText = await response.text()
throw Error(`StatusCode: ${response.status} - ${responseText} for SendToMollie`)
}
}
async function sendPaymentEmail(order) {
try {
var myHeaders = new fetch.Headers();
myHeaders.append("Authorization", 'Bearer ' + SENDGRID_API_KEY);
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
"from": {
"email": "info@burgerlijk.com",
"name": "Burgerlijk"
},
"personalizations": [
{
"to": [
{
"email": order.email
}
],
"dynamic_template_data": order
}
],
"template_id": SENDGRID_TEMPLATE_ID
});
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
const response = await fetch("https://api.sendgrid.com/v3/mail/send", requestOptions)
return response
} catch (error) {
console.log('Failed Sendgrid -> ' + error.message)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment