· 5 years ago · Dec 11, 2019, 05:10 PM
1app.post('/api/webhook', async (req, res) => {
2 console.log(':tada: We got an order!');
3 // We'll compare the hmac to our own hash
4 const hmac = req.get('X-Shopify-Hmac-Sha256');
5 // Use raw-body to get the body (buffer)
6 // let body;
7 // let newOrder;
8 const body = await getRawBody(req)
9 const newOrder = JSON.parse(body.toString())
10 //console.log(newOrder)
11 try {
12 body = await getRawBody(req);
13 newOrder = JSON.parse(body.toString());
14 console.log(newOrder)
15 } catch (e) {
16 console.log('Something went wrong:')
17 console.log(e)
18 throw e;
19 }
20 // Create a hash using the body and our key
21 const hash = crypto
22 .createHmac('sha256', secretKey)
23 .update(body, 'utf8', 'hex')
24 .digest('base64');
25 // Compare our hash to Shopify's hash
26 if (hash === hmac) {
27 // It's a match! All good
28 console.log(':tada: Phew, it came from Shopify!');
29 res.sendStatus(200);
30 } else {
31 // No match! This request didn't originate from Shopify
32 console.log(':ghost: Danger! Not from Shopify!');
33 res.sendStatus(403);
34 }
35 const config = {
36 headers: {
37 'Content-Type': 'application/x-www-form-urlencoded',
38 'Accept' : 'application/json',
39 'GSUID' : '158'
40 }
41 };
42 const requestBody = {
43 f: 'json',
44 u: 'boxofheat',
45 p: 'boX_oF_heaT.2019'
46 };
47 //Login and retrieve session_digest
48 const login = 'https://clienti.grupposinergia.net/webservice/login';
49 axios.post(login, qs.stringify(requestBody), config)
50 .then(response => {
51 //Store session_digest
52 var session = [];
53 session = response.data.session_digest;
54 //Insert orders
55 const data = {
56 no: newOrder,
57 sd: session,
58 f: "json"
59 }
60 const url = 'https://clienti.grupposinergia.net/webservice/logistics/insert_orders';
61 const params = httpBuildQuery(data);
62 axios.post(url, params, config)
63 .then(response => {
64 console.log(response);
65 })
66 .catch((err) => {
67 console.log("API Error:" + err);
68 })
69 })
70 .finally( () => {
71 console.log('end');
72 })
73})