creating apps with node js

New Member
1 0 0

I'm a total newby to shopify and i'm recently started working with node.js. i want to create a node app that can find users from my shopify shop. I started with the tutorial on the shopify website that prints out my shop information in the callback url. so i get a token and with that token i can do something but i don't see the way of how to take the token out and work with it in other routes. I saw also the shopify-node-api but I can't get it working, i think because of the settings. I want to build a private app so i assume that the token that i receive is valid forever? I placed that token in my env file so that i can import it in the shopify-node-api settings but nothing happens, i only get a 502 bad gateway

 

const dotenv = require('dotenv').config();
const express = require('express');
const app = express();
const crypto = require('crypto');
const cookie = require('cookie');
const nonce = require('nonce')();
const querystring = require('querystring');
const request = require('request-promise');
const shopifyAPI = require('shopify-node-api');


const apiKey = process.env.SHOPIFY_API_KEY;
const apiSecret = process.env.SHOPIFY_API_SECRET;
const apiToken = process.env.SHOPIFY_ACCESS_TOKEN;
const scopes = 'read_products';
const forwardingAddress = "https://8ea26f78.ngrok.io"; // Replace this with your HTTPS Forwarding address

app.get('/', (req, res) => {
    res.send('Hello World! ik ben hier');
});

app.get('/test', (req, res) => {
    var Shopify = new shopifyAPI({
        shop: 'bitworkz-test.myshopify.com', // MYSHOP.myshopify.com
        shopify_api_key: apiKey, // Your API key
        shopify_shared_secret: apiSecret, // Your Shared Secret
        access_token: apiToken, //permanent token
    });
});

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.myshopify.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;

    if (state !== stateCookie) {
        return res.status(403).send('Request origin cannot be verified');
    }

    if (shop && hmac && code) {
        // DONE: Validate request is from Shopify
        const map = Object.assign({}, req.query);
        delete map['signature'];
        delete map['hmac'];
        const message = querystring.stringify(map);
        const providedHmac = Buffer.from(hmac, 'utf-8');
        const generatedHash = Buffer.from(
            crypto
                .createHmac('sha256', apiSecret)
                .update(message)
                .digest('hex'),
            'utf-8'
        );
        let hashEquals = false;

        try {
            hashEquals = crypto.timingSafeEqual(generatedHash, providedHmac)
        } catch (e) {
            hashEquals = false;
        };

        if (!hashEquals) {
            return res.status(400).send('HMAC validation failed');
        }

        // DONE: Exchange temporary code for a permanent access token
        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;
                console.log(accessToken);
                // DONE: Use access token to make API call to 'shop' endpoint
                const shopRequestUrl = 'https://' + shop + '/admin/api/2019-07/shop.json';
                const shopRequestHeaders = {
                    'X-Shopify-Access-Token': accessToken,
                };

                request.get(shopRequestUrl, { headers: shopRequestHeaders })
                    .then((shopResponse) => {
                        res.status(200).end(shopResponse);
                    })
                    .catch((error) => {
                        res.status(error.statusCode).send(error.error.error_description);
                    });
            })
            .catch((error) => {
                res.status(error.statusCode).send(error.error.error_description);
            });

    } else {
        res.status(400).send('Required parameters missing');
    }
});

app.listen(3000, () => {
    console.log('Example app listening on port 3000!');
});
0 Likes
Highlighted
New Member
2 0 0

Hi,

I am a newbie to shopify myself. Have you installed ngrok locally and update this line with your local instance of ngrok?

 

const forwardingAddress = "https://8ea26f78.ngrok.io";

 

0 Likes