This repository was archived by the owner on Sep 4, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwebtask-mailchimp.js
115 lines (96 loc) · 3.06 KB
/
webtask-mailchimp.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
const express = require('express')
const Webtask = require('webtask-tools')
const cors = require('cors')
const crypto = require('crypto')
const bodyParser = require('body-parser')
const request = require('request')
const server = express()
server.listen(4430)
server.use(bodyParser.json())
//
// Allow requests from these domains only
//
const corsOptions = {
origin: ['https://oceanprotocol.com', /\.oceanprotocol\.com$/],
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}
server.use(cors(corsOptions))
const baseUrl = 'https://us16.api.mailchimp.com/3.0'
const listId = '3c6eed8b71'
const md5 = data =>
crypto
.createHash('md5')
.update(data)
.digest('hex')
server.post('/newsletter/:email', (req, res) => {
const { email } = req.params
const { MAILCHIMP_API_KEY } = req.webtaskContext.secrets
const emailDecoded = decodeURIComponent(email)
const subscriberHash = md5(emailDecoded)
const baseOptions = {
url: `${baseUrl}/lists/${listId}/members/${subscriberHash}`,
auth: {
user: 'oceanprotocol',
pass: MAILCHIMP_API_KEY
}
}
const optionsCreate = {
...baseOptions,
json: {
email_address: emailDecoded,
status: 'pending', // double opt-in
merge_fields: {
// our GDPR fallback
GDPR: 'yes'
}
}
}
const optionsMarketing = marketingPermissionId => ({
...baseOptions,
json: {
marketing_permissions: [
{
marketing_permission_id: marketingPermissionId,
text: 'Email',
enabled: true
}
]
}
})
const addMarketingPermissions = (data, cb) => {
const marketingPermissionId =
data.marketing_permissions[0].marketing_permission_id
request.patch(
optionsMarketing(marketingPermissionId),
(error, response, body) => {
if (error) res.send(error)
return cb(body)
}
)
}
// Check if user exists first
request.get(baseOptions, (error, response, body) => {
if (error) res.send(error)
const data = JSON.parse(body)
// Member exists and is subscribed
if (data.status === 'subscribed') {
// Patch in native GDPR permissions
addMarketingPermissions(data, () => {
res.send('{ "status": "exists" }')
})
} else {
// Create user
request.put(optionsCreate, (error2, response, body2) => {
if (error2) res.send(error2)
if (Number.isInteger(body2.status)) {
res.send(body2)
}
// Patch in native GDPR permissions
addMarketingPermissions(body2, () => {
res.send('{ "status": "created" }')
})
})
}
})
})
module.exports = Webtask.fromExpress(server)