Created
November 10, 2018 05:14
-
-
Save amarg26/7449d1a19ccb49e39ec2f6045c03b308 to your computer and use it in GitHub Desktop.
node Index.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require('isomorphic-fetch'); | |
require('dotenv').config(); | |
const fs = require('fs'); | |
const express = require('express'); | |
const session = require('express-session'); | |
const RedisStore = require('connect-redis')(session); | |
const path = require('path'); | |
const logger = require('morgan'); | |
const webpack = require('webpack'); | |
const webpackMiddleware = require('webpack-dev-middleware'); | |
const webpackHotMiddleware = require('webpack-hot-middleware'); | |
const config = require('../config/webpack.config.js'); | |
const ShopifyAPIClient = require('shopify-api-node'); | |
const ShopifyExpress = require('@vmundhra/shopify-express'); | |
//const { MemoryStrategy } = require('@vmundhra/shopify-express/strategies'); | |
var redis = require('redis'); | |
const { RedisStrategy } = require('@vmundhra/shopify-express/strategies'); | |
const bodyParser = require('body-parser'); | |
const { SHOPIFY_APP_KEY, SHOPIFY_APP_HOST, SHOPIFY_APP_SECRET, NODE_ENV } = process.env; | |
const shopifyConfig = { | |
host: SHOPIFY_APP_HOST, | |
apiKey: SHOPIFY_APP_KEY, | |
secret: SHOPIFY_APP_SECRET, | |
scope: [ 'write_orders, write_products, write_customers,write_price_rules' ], | |
// shopStore: new MemoryStrategy(), | |
shopStore: new RedisStrategy(), | |
afterAuth(request, response) { | |
const { session: { accessToken, shop } } = request; | |
// install webhooks or hook into your own app here | |
registerWebhook(shop, accessToken, { | |
topic: 'orders/create', | |
address: `${SHOPIFY_APP_HOST}/order-create`, | |
format: 'json' | |
}); | |
return response.redirect('/'); | |
} | |
}; | |
const registerWebhook = function(shopDomain, accessToken, webhook) { | |
const shopify = new ShopifyAPIClient({ | |
shopName: shopDomain, | |
accessToken: accessToken | |
}); | |
shopify.webhook | |
.create(webhook) | |
.then((response) => console.log(`webhook '${webhook.topic}' created`), (err) => console.log(`Error creating webhook '${webhook.topic}'. ${JSON.stringify(err.response.body)}`)); | |
}; | |
const app = express(); | |
const isDevelopment = NODE_ENV !== 'production'; | |
app.set('views', path.join(__dirname, 'views')); | |
app.set('view engine', 'ejs'); | |
//app.use(session({ secret: SHOPIFY_APP_SECRET, cookie: { maxAge: 60000 , secure: true}})); | |
app.use(function(req, res, next) { | |
console.log('Time:', Date.now()); | |
next(); | |
}); | |
app.use(logger('dev')); | |
// session is necessary for api proxy and auth verification | |
app.use( | |
session({ | |
store: isDevelopment ? undefined : new RedisStore(), | |
secret: SHOPIFY_APP_SECRET, | |
resave: true, | |
saveUninitialized: false | |
}) | |
); | |
// Run webpack hot reloading in dev | |
if (isDevelopment) { | |
const compiler = webpack(config); | |
const middleware = webpackMiddleware(compiler, { | |
hot: true, | |
inline: true, | |
publicPath: config.output.publicPath, | |
contentBase: 'src', | |
stats: { | |
colors: true, | |
hash: false, | |
timings: true, | |
chunks: false, | |
chunkModules: false, | |
modules: false | |
} | |
}); | |
app.use(middleware); | |
app.use(webpackHotMiddleware(compiler)); | |
} else { | |
const staticPath = path.resolve(__dirname, '../assets'); | |
app.use('/assets', express.static(staticPath)); | |
} | |
// Install | |
app.get('/install', (req, res) => res.render('install')); | |
// Create shopify middlewares and router | |
const shopify = ShopifyExpress(shopifyConfig); | |
// Mount Shopify Routes | |
const { routes, middleware } = shopify; | |
const { withShop, withWebhook, withAppProxy } = middleware; | |
// mounts '/auth' and '/api' off of '/shopify' | |
app.use('/shopify', routes); | |
// Client | |
// shields from being accessed without session | |
app.get( | |
'/', | |
withShop({ | |
authBaseUrl: '/shopify' | |
}), | |
function(request, response) { | |
const { session: { shop, accessToken } } = request; | |
response.render('app', { | |
title: 'Shopify Node App', | |
apiKey: shopifyConfig.apiKey, | |
shop: shop | |
}); | |
} | |
); | |
app.post( | |
'/order-create', | |
withWebhook((error, request) => { | |
if (error) { | |
console.error(error); | |
return; | |
} | |
console.log('We got a webhook!'); | |
console.log('Details: ', request.webhook); | |
console.log('Body:', request.body); | |
}) | |
); | |
// support parsing of application/json type post data | |
app.use(bodyParser.json()); | |
//support parsing of application/x-www-form-urlencoded post data | |
app.use(bodyParser.urlencoded({ | |
extended: true | |
})); | |
app.post( | |
'/newsletter-signup', | |
bodyParser.json(), | |
withAppProxy((error, request, response) => { | |
//just return here since withAppProxy already sends error response | |
if (error) { | |
console.error(error); | |
return; | |
} | |
const { proxy: { shop, accessToken }, body: { email, phone } } = request; | |
const shopifyAPIClient = new ShopifyAPIClient({ | |
shopName: shop, | |
accessToken | |
}); | |
shopifyAPIClient.customer | |
.create({ | |
email, | |
phone, | |
accepts_marketing: true, | |
tags: 'newsletter' | |
}) | |
.then( | |
(data) => { | |
console.log(`customer created = `, data); | |
response.json({ | |
status: 'success', | |
customer: { | |
id: data.id | |
} | |
}); | |
}, | |
(err) => { | |
console.log(`Error in create customer'. = `, err); | |
console.log(`Error creating customer'. ${JSON.stringify(err.response.body)}`); | |
response.status(err.statusCode).send(err.response.body); | |
} | |
); | |
}) | |
); | |
app.post('/referral', bodyParser.json(), withAppProxy((error,request,response)=>{ | |
const codeWord = "Friend"; | |
const result = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] //choose from those values | |
.map(a => [Math.random(), a]) //assign each value a random number - this will create an array of arrays like [[0.123422, 1], [0.848354, 2], ...] | |
.sort((a, b) => a[0] - b[0]) //sort by the random number order | |
.map(a => a[1]) //pluck the values | |
.join(""); | |
const couponcode=`${codeWord}-${result}`; | |
if (error) { | |
console.error(error); | |
return; | |
} | |
const { | |
proxy: { | |
shop, | |
accessToken | |
}, | |
body: { | |
email, | |
phone | |
} | |
} = request; | |
const shopify = new ShopifyAPIClient({ | |
shopName: shop, | |
accessToken | |
}); | |
shopify.priceRule.create({ | |
email, | |
phone, | |
title: "REFERRALFRIEND", | |
allocation_method: "each", | |
once_per_customer: true, | |
target_type: "line_item", | |
target_selection: "all", | |
value_type: "percentage", | |
value: -15.0, | |
customer_selection: "all", | |
starts_at: "2018-10-10T1:00:10Z" | |
}) | |
.then((data) => { | |
shopify.discountCode.create(data.id, | |
{ code: couponcode }) | |
.then((data) => { | |
console.log(`coupon code created = `, data); | |
response.json({ | |
status: 'success', | |
discount_code: { | |
code: couponcode, | |
} | |
}); | |
}) | |
.catch((err) => { | |
console.log(`Error in create coupon code'. = `, err); | |
console.log(`Error creating coupon code'. ${JSON.stringify(err.response.body)}`); | |
response.status(err.statusCode).send(err.response.body); | |
}); | |
}) | |
.catch((err) => { | |
console.log(`Error in create price rule'. = `, err); | |
console.log(`Error creating price rule'. ${JSON.stringify(err.response.body)}`); | |
response.status(err.statusCode).send(err.response.body); | |
}); | |
})); | |
// Error Handlers | |
app.use(function(req, res, next) { | |
const err = new Error('Not Found'); | |
err.status = 404; | |
next(err); | |
}); | |
app.use(function(error, request, response, next) { | |
response.locals.message = error.message; | |
response.locals.error = request.app.get('env') === 'development' ? error : {}; | |
response.status(error.status || 500); | |
response.render('error'); | |
}); | |
module.exports = app; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment