|
| 1 | +const axios = require('axios') |
| 2 | + |
1 | 3 | // read configured E-Com Plus app data
|
2 | 4 | const getAppData = require('./../../lib/store-api/get-app-data')
|
3 | 5 |
|
@@ -31,21 +33,68 @@ exports.post = ({ appSdk }, req, res) => {
|
31 | 33 | }
|
32 | 34 |
|
33 | 35 | /* 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) |
37 | 92 | })
|
38 | 93 |
|
39 | 94 | .catch(err => {
|
40 | 95 | if (err.name === SKIP_TRIGGER_NAME) {
|
41 | 96 | // trigger ignored by app configuration
|
42 | 97 | 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) |
49 | 98 | } else {
|
50 | 99 | // console.error(err)
|
51 | 100 | // request to Store API with error response
|
|
0 commit comments