Facebook
From Imrul Kayes Sifat, 1 Week ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 88
  1. app.get("/shopify", (req, res) => {
  2.     const shopName = req.query.shop;
  3.     if (shopName) {
  4.  
  5.         const shopState = nonce();
  6.  
  7.         const redirectURL = forwardingAddress + "/shopify/callback";
  8.  
  9.         // install url for app install
  10.         const installUrl =
  11.             "https://" +
  12.             shopName +
  13.             "/admin/oauth/authorize?client_id=" +
  14.             apiKey +
  15.             "&scope;=" +
  16.             scopes +
  17.             "&state;=" +
  18.             shopState +
  19.             "&redirect;_uri=" +
  20.             redirectURL;
  21.         res.cookie("state", shopState);
  22.         // redirect the user to the installUrl
  23.         res.redirect(installUrl);
  24.     } else {
  25.         return res.status(400).send('Missing "Shop Name" parameter!!');
  26.     }
  27. })
  28. function verifyHmac(queryParams: any) {
  29.     const { hmac, ...params } = queryParams;
  30.     const sortedParams = Object.keys(params)
  31.         .sort()
  32.         .map((key) => `${key}=${params[key]}`)
  33.         .join('&');
  34.  
  35.     const calculatedHmac = crypto
  36.         .createHmac('sha256', process.env.SHOPIFY_API_SECRET)
  37.         .update(sortedParams)
  38.         .digest('hex');
  39.  
  40.     return hmac === calculatedHmac;
  41. }
  42.  
  43. app.get("/shopify/callback", (req, res) => {
  44.     const { shop, hmac, code, shopState } = req.query;
  45.     const stateCookie = cookie.parse(req.headers.cookie).shopState;
  46.     const validation = verifyHmac(req.query)
  47.  
  48.     if (!validation) {
  49.         return res.status(400).send("HMAC validation failed");
  50.     }
  51.  
  52.     const accessTokenRequestUrl =
  53.         "https://" + shop + "/admin/oauth/access_token";
  54.     const accessTokenPayload = {
  55.         client_id: process.env.SHOPIFY_API_KEY,
  56.         client_secret: process.env.SHOPIFY_API_SECRET,
  57.         code,
  58.     };
  59.     request
  60.         .post(accessTokenRequestUrl, { json: accessTokenPayload })
  61.  
  62.         .then((accessTokenResponse: any) => {
  63.             console.log(accessTokenResponse)
  64.         })
  65.  
  66.         .catch((error: any) => {
  67.             res.status(error.statusCode).send(error.error.error_description);
  68.         });
  69. })