-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
224 lines (183 loc) · 6.69 KB
/
app.js
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
require('dotenv').config();
var https = require('https');
var express = require('express');
var session = require('express-session');
var request = require('request');
var app = express();
var config = require('./config.json');
var path = require('path');
var crypto = require('crypto');
var QuickBooks = require('node-quickbooks');
var queryString = require('query-string');
var fs = require('fs');
var json2csv = require('json2csv');
var Tokens = require('csrf');
var csrf = new Tokens();
// Configure View and Handlebars
app.use(express.static(path.join(__dirname, '')))
app.set('views', path.join(__dirname, 'views'))
var exphbs = require('express-handlebars');
var hbs = exphbs.create({defaultLayout: false});
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');
app.use(session({secret: 'secret', resave: 'false', saveUninitialized: 'false'}))
/*
Create body parsers for application/json and application/x-www-form-urlencoded
*/
var bodyParser = require('body-parser')
app.use(bodyParser.json())
var urlencodedParser = bodyParser.urlencoded({ extended: false })
/*
App Variables
*/
var token_json,realmId,payload;
var fields = ['realmId', 'name', 'id', 'operation', 'lastUpdated'];
var newLine= "\r\n";
app.use(express.static('views'));
app.get('/', function(req, res) {
//write the headers and newline
fields= (fields + newLine);
fs.writeFile('file.csv', fields, function (err, stat) {
if (err) throw err;
console.log('file saved');
});
// Render home page with params
res.render('index', {
redirect_uri: config.redirectUri,
token_json: token_json,
webhook_uri: config.webhookUri,
webhook_payload: payload
});
});
app.get('/authUri', function(req,res) {
/*
Generate csrf Anti Forgery
*/
req.session.secret = csrf.secretSync();
var state = csrf.create(req.session.secret);
/*
Generate the AuthUrl
*/
var redirecturl = config.authorization_endpoint +
'?client_id=' + config.clientId +
'&redirect_uri=' + encodeURIComponent(config.redirectUri) + //Make sure this path matches entry in application dashboard
'&scope='+ config.scopes.connect_to_quickbooks[0] +
'&response_type=code' +
'&state=' + state;
res.send(redirecturl);
});
app.get('/callback', function(req, res) {
var parsedUri = queryString.parse(req.originalUrl);
realmId = parsedUri.realmId;
var auth = (new Buffer(config.clientId + ':' + config.clientSecret).toString('base64'));
var postBody = {
url: config.token_endpoint,
headers: {
Accept: 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
Authorization: 'Basic ' + auth,
},
form: {
grant_type: 'authorization_code',
code: req.query.code,
redirect_uri: config.redirectUri
}
};
request.post(postBody, function (err, res, data) {
var accessToken = JSON.parse(res.body);
token_json = JSON.stringify(accessToken, null,2);
});
res.send('');
});
app.post('/payload',function (req,res) {
console.log("The Webhook notification payload is :" + JSON.stringify(req.body));
res.sendStatus(200);
})
app.post('/webhook', function(req, res) {
var webhookPayload = JSON.stringify(req.body);
console.log('The paylopad is :' + JSON.stringify(req.body));
var signature = req.get('intuit-signature');
var fields = ['realmId', 'name', 'id', 'operation', 'lastUpdated'];
var newLine= "\r\n";
// if signature is empty return 401
if (!signature) {
return res.status(401).send('FORBIDDEN');
}
// if payload is empty, don't do anything
if (!webhookPayload) {
return res.status(200).send('success');
}
/**
* Validates the payload with the intuit-signature hash
*/
var hash = crypto.createHmac('sha256', config.webhooksVerifier).update(webhookPayload).digest('base64');
if (signature === hash) {
console.log("The Webhook notification payload is :" + webhookPayload);
/**
* Write the notification to CSV file
*/
var appendThis = [];
for(var i=0; i < req.body.eventNotifications.length; i++) {
var entities = req.body.eventNotifications[i].dataChangeEvent.entities;
var realmID = req.body.eventNotifications[i].realmId;
for(var j=0; j < entities.length; j++) {
var notification = {
'realmId': realmID,
'name': entities[i].name,
'id': entities[i].id,
'operation': entities[i].operation,
'lastUpdated': entities[i].lastUpdated
}
appendThis.push(notification);
}
}
var toCsv = {
data: appendThis,
fields: fields
};
fs.stat('file.csv', function (err, stat) {
if (err == null) {
//write the actual data and end with newline
var csv = json2csv(toCsv) + newLine;
fs.appendFile('file.csv', csv, function (err) {
if (err) throw err;
console.log('The "data to append" was appended to file!');
});
}
else {
//write the headers and newline
console.log('New file, just writing headers');
fields= (fields + newLine);
fs.writeFile('file.csv', fields, function (err, stat) {
if (err) throw err;
console.log('file saved');
});
}
});
return res.status(200).send('SUCCESS');
}
return res.status(401).send('FORBIDDEN');
});
app.post('/createCustomer', urlencodedParser, function(req, res) {
var token = JSON.parse(token_json);
// save the access token somewhere on behalf of the logged in user
var qbo = new QuickBooks(config.clientId,
config.clientSecret,
token.access_token, /* oAuth access token */
false, /* no token secret for oAuth 2.0 */
realmId,
true, /* use a sandbox account */
true, /* turn debugging on */
4, /* minor version */
'2.0', /* oauth version */
token.refresh_token /* refresh token */);
qbo.createCustomer({DisplayName: req.body.displayName}, function(err, customer) {
if (err) console.log(err)
else console.log("The response is :" + JSON.stringify(customer,null,2));
res.send(customer );
});
});
// Start server on HTTP (will use ngrok for HTTPS forwarding)
app.listen(8000, function () {
console.log('Example app listening on port 8000!')
})