-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
105 lines (92 loc) · 2.85 KB
/
index.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
const dotenv = require("dotenv").config();
const express = require("express");
const app = express();
const crypto = require("crypto");
const nonce = require("nonce");
const querystring = require("querystring");
const request = require("request-promise");
const cookie = require("cookie");
const apiKey = process.env.SHOPIFY_API_KEY;
const apiSecret = process.env.SHOPIFY_API_SECRET;
const scopes = "write_products";
const forwardingAddress = "http://7cda1155abc7.ngrok.io";
app.get("/shopify", (req, res) => {
const shop = req.query.shop;
if (shop) {
const state = nonce();
const redirectUri = forwardingAddress + "/shopify/callback";
const installUrl =
"https://" +
shop +
"/admin/oauth/authorize?client_id=" +
apiKey +
"&scope=" +
scopes +
"&state=" +
state +
"&redirect_uri=" +
redirectUri;
res.cookie("state", state);
res.redirect(installUrl);
} else {
return res
.status(400)
.send(
"missing shop parameter. Please add ?shop=your-development-shop.shopify.com to your request"
);
}
});
app.get("/shopify/callback", (req, res) => {
const { shop, hmac, code, state } = req.query;
const stateCookie = cookie.parse(req.headers.cookie).state;
console.log(state);
console.log(stateCookie);
if (state != stateCookie) {
return res.status(403).send("Request origin cannot be verified");
}
if (shop && hmac && code) {
const map = Object.assign({}, req.query);
delete map["hmac"];
const message = querystring.stringify(map);
const generatedHash = crypto
.createHmac("sha256", apiSecret)
.update(message)
.digest("hex");
if (generatedHash !== hmac) {
return res.status(400).send("HMAC validation failed");
}
const accessTokenRequestUrl =
"https://" + shop + "/admin/oauth/access_token";
const accessTokenPayload = {
client_id: apiKey,
client_secret: apiSecret,
code,
};
request
.post(accessTokenRequestUrl, { json: accessTokenPayload })
.then((accessTokenResponse) => {
const accessToken = accessTokenResponse.access_token;
res.status(200).send("Got an access token, let's do something with it");
})
.catch((error) =>
res.status(error.statusCode).send(error.error.error_description)
);
const apiRequestUrl = "https://" + shop + "/admin/shop.json";
const shopRequestHeader = {
"X-Shopify-Access-Token": accessToken,
};
request
.get(apiRequestUrl, { headers: shopRequestHeader })
.them((apiResponse) => {
res.end(shopResponse);
})
.catch((error) => {
res.status(error.statusCode).send(error.error.error_description);
});
} else {
req.status(400).send("Required parameters missing");
}
});
app.listen(3000, () => {
console.log("Listening to port 3000");
});