app.get("/shopify", (req, res) => {
const shopName = req.query.shop;
if (shopName) {
const shopState = nonce();
const redirectURL = forwardingAddress + "/shopify/callback";
// install url for app install
const installUrl =
"https://" +
shopName +
"/admin/oauth/authorize?client_id=" +
apiKey +
"&scope;=" +
scopes +
"&state;=" +
shopState +
"&redirect;_uri=" +
redirectURL;
res.cookie("state", shopState);
// redirect the user to the installUrl
res.redirect(installUrl);
} else {
return res.status(400).send('Missing "Shop Name" parameter!!');
}
})
function verifyHmac(queryParams: any) {
const { hmac, ...params } = queryParams;
const sortedParams = Object.keys(params)
.sort()
.map((key) => `${key}=${params[key]}`)
.join('&');
const calculatedHmac = crypto
.createHmac('sha256', process.env.SHOPIFY_API_SECRET)
.update(sortedParams)
.digest('hex');
return hmac === calculatedHmac;
}
app.get("/shopify/callback", (req, res) => {
const { shop, hmac, code, shopState } = req.query;
const stateCookie = cookie.parse(req.headers.cookie).shopState;
const validation = verifyHmac(req.query)
if (!validation) {
return res.status(400).send("HMAC validation failed");
}
const accessTokenRequestUrl =
"https://" + shop + "/admin/oauth/access_token";
const accessTokenPayload = {
client_id: process.env.SHOPIFY_API_KEY,
client_secret: process.env.SHOPIFY_API_SECRET,
code,
};
request
.post(accessTokenRequestUrl, { json: accessTokenPayload })
.then((accessTokenResponse: any) => {
console.log(accessTokenResponse)
})
.catch((error: any) => {
res.status(error.statusCode).send(error.error.error_description);
});
})
{"html5":"htmlmixed","css":"css","javascript":"javascript","php":"php","python":"python","ruby":"ruby","lua":"text\/x-lua","bash":"text\/x-sh","go":"go","c":"text\/x-csrc","cpp":"text\/x-c++src","diff":"diff","latex":"stex","sql":"sql","xml":"xml","apl":"apl","asterisk":"asterisk","c_loadrunner":"text\/x-csrc","c_mac":"text\/x-csrc","coffeescript":"text\/x-coffeescript","csharp":"text\/x-csharp","d":"d","ecmascript":"javascript","erlang":"erlang","groovy":"text\/x-groovy","haskell":"text\/x-haskell","haxe":"text\/x-haxe","html4strict":"htmlmixed","java":"text\/x-java","java5":"text\/x-java","jquery":"javascript","mirc":"mirc","mysql":"sql","ocaml":"text\/x-ocaml","pascal":"text\/x-pascal","perl":"perl","perl6":"perl","plsql":"sql","properties":"text\/x-properties","q":"text\/x-q","scala":"scala","scheme":"text\/x-scheme","tcl":"text\/x-tcl","vb":"text\/x-vb","verilog":"text\/x-verilog","yaml":"text\/x-yaml","z80":"text\/x-z80"}