Skip to content

Commit 9e48bc7

Browse files
committed
feat: parse ecom webhook and sendfull order to configured uri
1 parent 4beaade commit 9e48bc7

File tree

1 file changed

+58
-9
lines changed

1 file changed

+58
-9
lines changed

functions/routes/ecom/webhook.js

Lines changed: 58 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
const axios = require('axios')
2+
13
// read configured E-Com Plus app data
24
const getAppData = require('./../../lib/store-api/get-app-data')
35

@@ -31,21 +33,68 @@ exports.post = ({ appSdk }, req, res) => {
3133
}
3234

3335
/* DO YOUR CUSTOM STUFF HERE */
34-
35-
// all done
36-
res.send(ECHO_SUCCESS)
36+
const { resource } = trigger
37+
if (resource === 'orders' && trigger.action !== 'delete') {
38+
const resourceId = trigger.resource_id || trigger.inserted_id
39+
const url = appData.webhook_uri
40+
if (resourceId && url) {
41+
console.log(`Trigger for Store #${storeId} ${resourceId} => ${url}`)
42+
return appSdk.apiRequest(storeId, `${resource}/${resourceId}.json`)
43+
.then(async ({ response }) => {
44+
const order = response.data
45+
if (
46+
appData.skip_pending === true &&
47+
(!order.financial_status || order.financial_status.current === 'pending')
48+
) {
49+
return res.sendStatus(204)
50+
}
51+
console.log(`> Sending ${resource} notification`)
52+
const token = appData.webhook_token
53+
let headers
54+
if (token) {
55+
headers = {
56+
'Authorization': `Bearer ${token}`
57+
}
58+
}
59+
return axios({
60+
method: 'post',
61+
url,
62+
headers,
63+
data: {
64+
storeId,
65+
trigger,
66+
order,
67+
}
68+
})
69+
})
70+
.then(({ status }) => console.log(`> ${status}`))
71+
.catch(error => {
72+
if (error.response && error.config) {
73+
const err = new Error(`#${storeId} ${resourceId} POST to ${url} failed`)
74+
const { status, data } = error.response
75+
err.response = {
76+
status,
77+
data: JSON.stringify(data)
78+
}
79+
err.data = JSON.stringify(error.config.data)
80+
return console.error(err)
81+
}
82+
console.error(error)
83+
})
84+
.finally(() => {
85+
if (!res.headersSent) {
86+
return res.sendStatus(200)
87+
}
88+
})
89+
}
90+
}
91+
res.sendStatus(204)
3792
})
3893

3994
.catch(err => {
4095
if (err.name === SKIP_TRIGGER_NAME) {
4196
// trigger ignored by app configuration
4297
res.send(ECHO_SKIP)
43-
} else if (err.appWithoutAuth === true) {
44-
const msg = `Webhook for ${storeId} unhandled with no authentication found`
45-
const error = new Error(msg)
46-
error.trigger = JSON.stringify(trigger)
47-
console.error(error)
48-
res.status(412).send(msg)
4998
} else {
5099
// console.error(err)
51100
// request to Store API with error response

0 commit comments

Comments
 (0)