This repository has been archived by the owner on Oct 9, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
199 lines (179 loc) · 6.08 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
const { readFileSync } = require('fs');
const { resolve } = require('path');
const sendGridMail = require('@sendgrid/mail');
const sendGridClient = require('@sendgrid/client');
/**
* Return a template ID for the corresponding webhook event. These templates should exist, as they would've
* been created where they don't exist when the integration was created.
*
* @param {string} event
* @param {object} integration
* @returns {string}
*/
function getTemplateId(event, integration) {
const templateId = integration.config.templates[event] || '';
if (!templateId) {
throw new Error(`Template ID is not available for event: ${event}`);
}
return templateId;
}
/**
* Creates a template, and a template version in SendGrid, then returns the ID of the template version.
*
* @param {string} event
* @param {string} name
* @param {string} subject
* @returns {Promise<Object>}
*/
async function createTemplate(event, name, subject) {
// Load the template HTML and sample JSON data
const templateHtml = readFileSync(`${resolve(__dirname)}/templates/${event}/template.html`).toString();
const testData = readFileSync(`${resolve(__dirname)}/templates/${event}/testData.json`).toString();
// Queue each set of API calls, they can run concurrently.
const [templateResponse] = await sendGridClient.request({
body: { name, generation: 'dynamic' },
method: 'POST',
url: '/v3/templates',
});
// Get template ID, then create
const { id } = templateResponse.body;
// Create a version for the template, which includes the HTML and JSON data
await sendGridClient.request({
body: {
name,
subject,
html_content: templateHtml,
test_data: testData,
editor: 'code',
},
method: 'POST',
url: `/v3/templates/${id}/versions`,
});
return {
event,
// This is the ID we actually need
id,
};
}
module.exports = async function handler(request, context) {
// Fetch merchant and integration info
const merchant = await context.merchant();
const merchantId = merchant.id;
const integration = await context.integration();
// Assemble payload for SendGrid transactional templates
const data = {
...request.body,
merchant,
};
// Set up SendGrid mail client
const sendGridApiKey = integration.config.api_key || null;
if (!sendGridApiKey) {
throw new Error('SendGrid API key not available. Please check your configuration.');
}
sendGridMail.setApiKey(sendGridApiKey);
let result = {};
// Work out what to do
switch (data.event) {
// Runs once when an integration is first installed. Use this to control initial setup steps such as disabling
// default emails in the Chec API, etc.
case 'integrations.ready':
// Disable default emails in Chec
context.api.put(`/v1/merchants/${merchantId}/notifications`, {
customer: {
login_token: false,
orders: false,
shipments: false,
},
});
// Create transactional templates in SendGrid
sendGridClient.setApiKey(sendGridApiKey);
// Loop each event type
const promises = [];
const templateConfig = [
{
event: 'customers.login.token',
name: 'Customers: login token',
subject: 'Log in to your account',
},
{
event: 'orders.create',
eventAliases: ['orders.receipt.resend'],
name: 'Orders: receipt',
subject: 'Your order: {{ payload.customer_reference }}',
},
{
event: 'orders.physical.shipment',
name: 'Orders: item shipped',
subject: 'Your order has shipped!',
},
];
templateConfig.forEach(({ event, name, subject }) => {
promises.push(createTemplate(event, name, subject));
});
// Wait for all of the templates to be built, then collect their IDs
const templateIds = await Promise.all(promises);
// Converts from [{event: 'foo', id: 'a-b-c'},...] to {foo: 'a-b-c', ...}
const templates = templateIds.reduce((acc, value) => (acc[value.event] = value.id, acc), {});
// Add any template event aliases
templateConfig.forEach(({ event, eventAliases = [] }) => {
eventAliases.forEach((alias) => {
templates[alias] = templates[event];
});
});
context.store.set('templates', templates);
result = {
installed: true,
templates,
};
break;
// Send "new order" email to customer
case 'orders.create':
case 'orders.receipt.resend':
await sendGridMail.send({
to: data.payload.customer.email,
from: {
email: data.merchant.support_email, // must be verified in SendGrid before it can be used
name: data.merchant.name,
},
subject: `Your order: ${data.payload.customer_reference}`,
dynamic_template_data: data,
template_id: getTemplateId(data.event, integration),
});
result = { sent: true };
break;
// Send "item shipped" email to customer
case 'orders.physical.shipment':
await sendGridMail.send({
to: data.payload.customer.email,
from: {
email: data.merchant.support_email, // must be verified in SendGrid before it can be used
name: data.merchant.name,
},
subject: 'Your order has a new shipment!',
dynamic_template_data: data,
template_id: getTemplateId(data.event, integration),
});
result = { sent: true };
break;
// Send "customer login token" email to customer
case 'customers.login.token':
await sendGridMail.send({
to: data.payload.email,
from: {
email: data.merchant.support_email, // must be verified in SendGrid before it can be used
name: data.merchant.name,
},
subject: 'Log in to your account',
dynamic_template_data: data,
template_id: getTemplateId(data.event, integration),
})
result = { sent: true };
break;
default:
throw new Error('Invalid `event` type provided.');
}
return {
statusCode: 200,
body: JSON.stringify(result),
};
}