generated from ecomplus/application-starter
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwebhook.js
265 lines (254 loc) · 11.5 KB
/
webhook.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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
// read configured E-Com Plus app data
const getAppData = require('./../../lib/store-api/get-app-data')
const RdAxios = require('./../../lib/rd-station/create-access')
const SKIP_TRIGGER_NAME = 'SkipTrigger'
const ECHO_SUCCESS = 'SUCCESS'
const ECHO_SKIP = 'SKIP'
const ECHO_API_ERROR = 'STORE_API_ERR'
exports.post = ({ appSdk }, req, res) => {
// receiving notification from Store API
const { storeId } = req
const validateStatus = function (status) {
return status >= 200 && status <= 301
}
const sendItem = (axios, validateStatus, data) => new Promise(resolve => {
return axios.post('/platform/events', data, {
maxRedirects: 0,
validateStatus
}).then(e => {
console.log('Item sended')
resolve(e)
})
})
/**
* Treat E-Com Plus trigger body here
* Ref.: https://developers.e-com.plus/docs/api/#/store/triggers/
*/
const trigger = req.body
console.log('Trigger from: ', storeId)
// get app configured options
getAppData({ appSdk, storeId })
.then(appData => {
if (
Array.isArray(appData.ignore_triggers) &&
appData.ignore_triggers.indexOf(trigger.resource) > -1
) {
// ignore current trigger
const err = new Error()
err.name = SKIP_TRIGGER_NAME
throw err
}
const { client_id, client_secret, code } = appData
if (!client_id && !client_secret) {
return res.status(409).send({
error: 'NO_RD_KEYS',
message: 'Client id ou secret não configurado'
})
}
const rdAxios = new RdAxios(client_id, client_secret, code, storeId)
/* DO YOUR CUSTOM STUFF HERE */
const { resource } = trigger
if ((resource === 'orders' || resource === 'carts' || resource === 'customers') && trigger.action !== 'delete') {
const resourceId = trigger.resource_id || trigger.inserted_id
if (resourceId) {
console.log(`Trigger for Store #${storeId} ${resource} ${resourceId}`)
appSdk.apiRequest(storeId, `${resource}/${resourceId}.json`)
.then(async ({ response }) => {
let customer
const body = response.data
if (resource === 'carts') {
const cart = body
if (cart.available && !cart.completed) {
const { customers } = cart
if (customers && customers[0]) {
const { response } = await appSdk.apiRequest(storeId, `customers/${customers[0]}.json`)
customer = response.data
}
} else {
return res.sendStatus(204)
}
} else if (resource === 'orders') {
const { buyers } = body
if (buyers && buyers.length && buyers[0]) {
const { response } = await appSdk.apiRequest(storeId, `customers/${buyers[0]._id}.json`)
customer = response.data
}
}
console.log(`> Sending ${resource} notification`)
let data, items
if (resource === 'orders') {
const financial = body && body.financial_status.current
const transaction = body.transactions[0]
const getMethod = transaction => {
const paymentMethod = transaction.payment_method && transaction.payment_method.code
if (paymentMethod === 'credit_card') {
return 'Credit Card'
} else {
return 'Others'
}
}
const paymentMethod = getMethod(transaction)
const total = body.amount && body.amount.total
items = body.items
data = {
"event_type": "ORDER_PLACED",
"event_family":"CDP",
"payload": {
"name": customer.display_name,
"email": customer.main_email,
"cf_order_id": body.status_link || body._id,
"cf_order_total_items": items && items.length || 0,
"cf_order_status": financial,
"cf_order_payment_method": paymentMethod,
"cf_order_payment_amount": total,
"legal_bases": [
{
"category": "communications",
"type":"consent",
"status": body.accepts_marketing !== false ? 'granted' : 'declined'
}
]
}
}
} else if (resource === 'carts') {
items = body.items
data = {
"event_type": "CART_ABANDONED",
"event_family":"CDP",
"payload": {
"name": customer.display_name,
"email": customer.main_email,
"cf_cart_id": body.permalink || body._id,
"cf_cart_total_items": items && items.length || 0,
"cf_cart_status": "in_progress",
"legal_bases": [
{
"category": "communications",
"type": "consent",
"status": body.accepts_marketing !== false ? 'granted' : 'declined'
}
]
}
}
} else if (resource === 'customers') {
const cellphone = body.phones && body.phones.length && body.phones[0] && body.phones[0].number
const phoneWithLocale = cellphone && cellphone.length ? `+55${cellphone}` : undefined
const birthDate = body.birth_date && body.birth_date.day && body.birth_date.month && body.birth_date.year ? `${body.birth_date.year}/${body.birth_date.month.padStart(2, '0')}/${body.birth_date.day.padStart(2, '0')}` : undefined
const address = body.addresses && body.addresses.length && body.addresses[0]
const city = address ? address.city : undefined
const state = address ? address.province_code : undefined
data = {
name: body.display_name || body.name && body.name.given_name,
email: body.main_email,
mobile_phone: phoneWithLocale,
birthdate: birthDate,
city,
state,
legal_bases: [
{
category: "communications",
type:"consent",
status: body.accepts_marketing !== false ? 'granted' : 'declined'
}
]
}
}
rdAxios.preparing
.then(() => {
const { axios } = rdAxios
// https://axios-http.com/ptbr/docs/req_config
let url = resource !== 'customers' ? '/platform/events' : '/platform/contacts'
return axios.post(url, data, {
maxRedirects: 0,
validateStatus
})
})
.then(({ status }) => {
console.log(`> ${status} - Created ${resource} - ${resourceId} - ${storeId}`)
if (resource === 'orders' || resource === 'carts') {
rdAxios.preparing
.then(async () => {
const { axios } = rdAxios
if (body && body.financial_status && body.financial_status.current === 'paid') {
data = {
"event_type": "SALE",
"event_family": "CDP",
"payload": {
"email": customer.main_email,
"funnel_name": "default",
"value": body.amount && body.amount.total
}
}
return axios.post('/platform/events?event_type=sale', data, {
maxRedirects: 0,
validateStatus
})
} else {
const resourceSub = resource.replace('s', '')
const addProp = [`cf_${resourceSub}_product_id`, `cf_${resourceSub}_product_sku`]
const removeProp = [`cf_${resourceSub}_total_items`, `cf_${resourceSub}_status`, `cf_${resourceSub}_payment_method`, `cf_${resourceSub}_payment_amount`]
const promises = []
const isOrder = resource === 'orders'
if (items && items.length && data) {
removeProp.forEach(prop => delete data['payload'][prop])
items.forEach(item => {
data['payload'][addProp[0]] = item.product_id
data['payload'][addProp[1]] = item.sku
data['event_type'] = isOrder ? 'ORDER_PLACED_ITEM' : 'CART_ABANDONED_ITEM'
promises.push(sendItem(axios, validateStatus, data))
});
return await Promise.all(promises).then((response) => console.log(`>> Created items ${resource} - ${storeId}`)).catch(err => console.log('erro do promise all', err))
}
}
})
}
})
.catch(error => {
if (error.response && error.config) {
const err = new Error(`#${storeId} ${resourceId} POST failed`)
const { status, data } = error.response
err.response = {
status,
data: JSON.stringify(data)
}
err.data = JSON.stringify(error.config.data)
return console.error(err)
}
console.error(error)
})
.finally(() => {
if (!res.headersSent) {
return res.sendStatus(200)
}
})
})
}
}
if (resource !== 'carts') {
res.sendStatus(201)
}
})
.catch(err => {
console.log('erro para buscar o app')
if (err.name === SKIP_TRIGGER_NAME) {
// trigger ignored by app configuration
res.send(ECHO_SKIP)
} else if (err.appWithoutAuth === true) {
const msg = `Webhook for ${storeId} unhandled with no authentication found`
const error = new Error(msg)
error.trigger = JSON.stringify(trigger)
console.error(error)
res.status(412).send(msg)
} else {
// console.error(err)
// request to Store API with error response
// return error status code
res.status(500)
const { message } = err
res.send({
error: ECHO_API_ERROR,
message
})
}
})
}