Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
254 lines (207 loc) · 8.24 KB
/
Copy pathserver.js
File metadata and controls
254 lines (207 loc) · 8.24 KB
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
/*************************************************************************
*
* Shopify App Development with Node, React, REST API & GraphQL
*
* Server File is where you will be creating all of your API functions.
* Though we'll most likely optimize this file and separate the functions
* into separate files / components.
*
* Note: Some parts of this file is copied from Shopify tutorial
* which you can browse in the link below:
* https://shopify.dev/tutorials/build-a-shopify-app-with-node-and-react/embed-your-app-in-shopify#set-up-a-node-server
*
*
* ***********************************************************************/
require('isomorphic-fetch');
const dotenv = require('dotenv');
const Koa = require('koa');
const next = require('next');
const { default: createShopifyAuth } = require('@shopify/koa-shopify-auth');
const { verifyRequest } = require('@shopify/koa-shopify-auth');
const session = require('koa-session');
const Router = require('@koa/router');
const axios = require('axios');
dotenv.config();
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
const { SHOPIFY_API_SECRET_KEY, SHOPIFY_API_KEY } = process.env;
app.prepare().then(() => {
const server = new Koa();
const router = new Router();
server.use(session({ secure: true, sameSite: 'none' }, server));
server.keys = [SHOPIFY_API_SECRET_KEY];
server.use(
createShopifyAuth({
apiKey: SHOPIFY_API_KEY,
secret: SHOPIFY_API_SECRET_KEY,
scopes: [
'read_products',
'write_products',
'read_script_tags',
'write_script_tags',
'read_orders',
'write_orders',
'read_draft_orders',
'write_draft_orders'
],
afterAuth(ctx) {
const { shop, accessToken } = ctx.session;
ctx.redirect('https://' + shop + '/admin/apps');
},
}),
);
server.use(verifyRequest());
//======================================================//
// GET PRODUCTS ROUTER
//======================================================//
router.get('/getProducts', verifyRequest(), async (ctx, res) => {
const { shop, accessToken } = ctx.session;
const url = `https://${shop}/admin/api/2020-10/products.json`;
const shopifyHeader = (token) => ({
'Content-Type': 'application/json',
'X-Shopify-Access-Token': token,
});
const getProducts = await axios.get(url, { headers: shopifyHeader(accessToken) });
ctx.body = getProducts.data;
ctx.res.statusCode = 200;
});
//======================================================//
// DELETE PRODUCTS ROUTER
//======================================================//
router.get('/deleteProduct', verifyRequest(), async (ctx, res) => {
const { shop, accessToken } = ctx.session;
const productID = ctx.query.id;
const url = `https://${shop}/admin/api/2020-10/products/${productID}.json`;
const shopifyHeader = (token) => ({
'Content-Type': 'application/json',
'X-Shopify-Access-Token': token,
});
const getProducts = await axios.delete(url, { headers: shopifyHeader(accessToken) })
.then(response => { console.log(response); })
.catch(error => console.log(error));
ctx.res.statusCode = 200;
});
//======================================================//
// CREATE SCRIPT TAGS
//======================================================//
router.get('/installScriptTags', verifyRequest(), async (ctx, res) => {
const { shop, accessToken } = ctx.session;
const url = `https://${shop}/admin/api/2020-10/script_tags.json`;
const src = 'https://example.com/example.js';
let scriptTagExist = false;
const shopifyHeader = (token) => ({
'Content-Type': 'application/json',
'X-Shopify-Access-Token': token,
});
const scriptTagBody = JSON.stringify({
script_tag: {
event: 'onload',
src,
},
});
const getScriptTags = await axios.get(url, { headers: shopifyHeader(accessToken) });
//console.log(getScriptTags.data);
getScriptTags.data.script_tags.map((script) => {
//console.log(script);
if(script.src == src) {
scriptTagExist = true;
}
});
if(!scriptTagExist) {
await axios.post(url, scriptTagBody, { headers: shopifyHeader(accessToken) })
.then(response => { console.log(response); })
.catch(error => console.log(error));
}
ctx.res.statusCode = 200;
});
//======================================================//
// DELETE SCRIPT TAG ROUTER
//======================================================//
router.get('/uninstallScriptTag', verifyRequest(), async (ctx, res) => {
const { shop, accessToken } = ctx.session;
const scriptTagID = ctx.query.id;
const url = `https://${shop}/admin/api/2020-10/script_tags/${scriptTagID}.json`;
const shopifyHeader = (token) => ({
'Content-Type': 'application/json',
'X-Shopify-Access-Token': token,
});
await axios.delete(url, { headers: shopifyHeader(accessToken) })
.then(response => { console.log(response); })
.catch(error => console.log(error));
ctx.res.statusCode = 200;
});
//======================================================//
// CREATE ORDER ROUTER
//======================================================//
router.get('/createDraftOrder', verifyRequest(), async (ctx, resp) => {
const { shop, accessToken } = ctx.session;
const title = ctx.query.title;
const quantity = ctx.query.quantity;
const price = ctx.query.price;
const url = `https://${shop}/admin/api/2020-10/graphql.json`;
const CREATE_DRAFT_ORDER_QUERY = JSON.stringify({
query: `mutation {
draftOrderCreate (
input: {
lineItems: {
title: "${title}"
quantity: ${quantity}
originalUnitPrice: "${price}"
}
}
) {
draftOrder {
id
}
userErrors {
message
}
}
}`
});
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Shopify-Access-Token': accessToken
},
body: CREATE_DRAFT_ORDER_QUERY
});
const responseJson = await response.json();
const COMPLETE_DRAFT_ORDER_QUERY = JSON.stringify({
query: `mutation {
draftOrderComplete (
id: "${responseJson.data.draftOrderCreate.draftOrder.id}"
) {
draftOrder {
id
}
}
}`
});
const completeDraftOrderResponse = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Shopify-Access-Token': accessToken
},
body: COMPLETE_DRAFT_ORDER_QUERY
});
const responseCompleteDraftOrderJson = await completeDraftOrderResponse.json();
console.log(responseCompleteDraftOrderJson);
ctx.res.statusCode = 200;
});
server.use(router.routes());
server.use(router.allowedMethods());
server.use(async (ctx) => {
await handle(ctx.req, ctx.res);
ctx.respond = false;
ctx.res.statusCode = 200;
return
});
server.listen(port, () => {
console.log(`> Ready on http://localhost:${port}`);
});
});