This repository has been archived by the owner on Dec 31, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
396 lines (364 loc) · 10.1 KB
/
index.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
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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
var express = require('express')
var queryString = require('querystring')
var request = require('request')
var bodyParser = require('body-parser')
var logger = require('./configs/logger')
var paypal = require('paypal-rest-sdk')
var url = require('url')
var mongoose = require('mongoose')
var newIPN = require('./models/ipn')
const path = require('path')
// MongoDB Setup
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true })
var connection = mongoose.connection
connection.on('error', console.error.bind(console, 'DB Connection Error:'))
connection.once('open', function () {})
// Express Setup
var serverHost = process.env.SERVER_HOST
var app = express()
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
// Define Client Path
app.use(express.static(path.join(__dirname, 'client/build')))
////
// Payment Endpoints
////
// Create Payment
app.post('/api/create-payment', function (req, res) {
var apiKey = req.body.apiCredentials.key
var apiSecret = req.body.apiCredentials.secret
var payment = req.body.payment
var redirectURL = req.body.redirectUrl
createPayment(
apiKey,
apiSecret,
redirectURL,
payment,
function (paymentResults) {
res.json(paymentResults)
logger.info(
'Payment data sent back to user: ' + JSON.stringify(paymentResults)
)
}
)
})
// Create Billing Agreement
app.post('/api/create-billingplan', function (req, res) {
var apiKey = req.body.apiCredentials.key
var apiSecret = req.body.apiCredentials.secret
var billingPlanAttributes = req.body.billingPlanAttributes
createBillingPlan(
apiKey,
apiSecret,
billingPlanAttributes,
function (billingPlanResults) {
// Redirect to our approval handler to execute payment
res.json(billingPlanResults)
}
)
})
// Create Billing Agreement
app.post('/api/create-agreement', function (req, res) {
var apiKey = req.body.apiCredentials.key
var apiSecret = req.body.apiCredentials.secret
var billingAgreementAttributes = req.body.billingAgreementAttributes
createBillingAgreement(
apiKey,
apiSecret,
billingAgreementAttributes,
function (billingAgreementResults) {
// Redirect to our approval handler to execute payment
res.json(billingAgreementResults)
}
)
})
// Execute Payment
app.post('/api/execute-payment', function (req, res) {
var payerId = req.body.PayerID
var paymentId = req.body.paymentId
var apiKey = req.body.apiCredentials.key
var apiSecret = req.body.apiCredentials.secret
executePayment(
apiKey,
apiSecret,
payerId,
paymentId,
function (paymentResults) {
res.json(paymentResults)
logger.info(
'User has approved the payment: ' + JSON.stringify(paymentResults)
)
}
)
})
// Execute Billing Agreement
app.post('/api/execute-agreement', function (req, res) {
var paymentToken = req.body.token
var apiKey = req.body.apiCredentials.key
var apiSecret = req.body.apiCredentials.secret
executeAgreement(apiKey, apiSecret, paymentToken, function (agreement) {
logger.info('User has approved the agreement: ' + JSON.stringify(agreement))
res.json(agreement)
})
})
////
// Payment Handlers
////
function createPayment(apiKey, apiSecret, redirectURL, paymentJSON, callback) {
if (apiKey && apiSecret) {
// Configure PayPal SDK
paypal.configure({
mode: 'sandbox',
client_id: apiKey,
client_secret: apiSecret,
headers: {
custom: 'header',
},
})
paypal.payment.create(paymentJSON, function (error, payment) {
if (error) {
callback(error)
} else {
logger.info('Payment Created: ' + JSON.stringify(payment))
callback(payment)
}
})
}
}
function createBillingPlan(apiKey, apiSecret, billingPlanAttributes, callback) {
if (apiKey && apiSecret) {
// Configure PayPal SDK
paypal.configure({
mode: 'sandbox',
client_id: apiKey,
client_secret: apiSecret,
headers: {
custom: 'header',
},
})
var billingPlanUpdateAttributes = [
{
op: 'replace',
path: '/',
value: {
state: 'ACTIVE',
},
},
]
paypal.billingPlan.create(
billingPlanAttributes,
function (error, billingPlan) {
if (error) {
logger.error('Error Creating Billing Plan: ' + error)
callback(error)
} else {
logger.info('Billing plan created: ' + JSON.stringify(billingPlan))
// Activate the plan by changing status to Active
paypal.billingPlan.update(
billingPlan.id,
billingPlanUpdateAttributes,
function (error, response) {
if (error) {
logger.error('Error activating billing plan: ' + error)
} else {
logger.info(
'Billing plan state changed to ' + billingPlan.state
)
callback(billingPlan)
}
}
)
}
}
)
}
}
function createBillingAgreement(
apiKey,
apiSecret,
billingAgreementAttributes,
callback
) {
if (apiKey && apiSecret) {
// Configure PayPal SDK
paypal.configure({
mode: 'sandbox',
client_id: apiKey,
client_secret: apiSecret,
headers: {
custom: 'header',
},
})
// Use activated billing plan to create agreement
paypal.billingAgreement.create(
billingAgreementAttributes,
function (error, billingAgreement) {
if (error) {
logger.error('Error with billing plan: ' + error)
callback(error)
} else {
logger.info(
'Billing agreement created from billing plan: ' +
JSON.stringify(billingAgreement)
)
callback(billingAgreement)
}
}
)
}
}
function executePayment(apiKey, apiSecret, payerId, paymentId, callback) {
// Configure PayPal SDK
paypal.configure({
mode: 'sandbox',
client_id: apiKey,
client_secret: apiSecret,
headers: {
custom: 'header',
},
})
var execute_payment_json = { payer_id: payerId }
paypal.payment.execute(
paymentId,
execute_payment_json,
function (error, payment) {
if (error) {
logger.error('Error executing payment: ' + error.response)
callback(error)
} else {
logger.info('Payment executed: ' + JSON.stringify(payment))
callback(payment)
}
}
)
}
function executeAgreement(apiKey, apiSecret, paymentToken, callback) {
// Configure PayPal SDK
paypal.configure({
mode: 'sandbox',
client_id: apiKey,
client_secret: apiSecret,
headers: {
custom: 'header',
},
})
paypal.billingAgreement.execute(
paymentToken,
{},
function (error, billingAgreement) {
if (error) {
logger.error('Execute Agreement Error: ' + error)
callback(error)
} else {
logger.info(
'Billing agreement has been executed: ' +
JSON.stringify(billingAgreement)
)
callback(billingAgreement)
}
}
)
}
////
// IPN Handler and Database Management
////
app.post('/', function (req, res) {
logger.info('New IPN Message: ' + JSON.stringify(req.body)) // Before anything else, log the IPN
// Read the IPN message sent from PayPal and prepend 'cmd=_notify-validate'
req.body = req.body || {}
res.status(200).send('OK')
res.end()
postreq = JSON.toString(req.body)
var postreq = 'cmd=_notify-validate'
for (var key in req.body) {
var value = queryString.escape(req.body[key])
postreq = postreq + '&' + key + '=' + value
}
logger.debug('IPN Postback: ' + postreq)
var options = {
url: 'https://www.sandbox.paypal.com/cgi-bin/webscr',
method: 'POST',
headers: {
Connection: 'close',
},
body: postreq,
strictSSL: true,
rejectUnauthorized: false,
requestCert: true,
agent: false,
}
request(options, function callback(error, response, body) {
logger.debug(response.statusCode + ': ' + body)
if (!error && response.statusCode === 200) {
// inspect IPN validation result and act accordingly
if (body.substring(0, 8) === 'VERIFIED') {
// VERIFIED
var item_name = req.body['item_name']
var item_number = req.body['item_number']
var payment_status = req.body['payment_status']
var payment_amount = req.body['mc_gross']
var payment_currency = req.body['mc_currency']
var txn_id = req.body['txn_id']
var receiver_email = req.body['receiver_email']
var payer_email = req.body['payer_email']
// Loop through the array and print the NVPs:
logger.debug('IPN Data: ')
for (var key in req.body) {
var value = req.body[key]
logger.debug(key + '=' + value)
}
} else if (body.substring(0, 7) === 'INVALID') {
// INVALID
logger.error('IPN Invalid: ' + body)
}
// Save the IPN and associated data to MongoDB
newIPN.create(
{
ipnMessageRaw: JSON.stringify(req.body),
ipnMessage: req.body,
ipnPostback: postreq,
status: body,
timestamp: Date.now(),
},
function (err, res) {
if (err) logger.error('DB Create Error' + err)
}
)
}
})
})
// Get IPN Data from MongoDB
app.get('/api/ipnData', function (req, res) {
connection.db.collection('ipn', function (err, collection) {
collection
.find({})
.sort({ timestamp: -1 })
.limit(50)
.toArray(function (err, data) {
res.json(data)
})
})
})
// Get a count of IPNs from MongoDB
app.get('/api/ipnCount', function (req, res) {
connection.db.collection('ipn', function (err, collection) {
collection.find({}).count(function (err, data) {
res.json(data)
})
})
})
////
// Serve Client Application
///
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'client/build/index.html'))
})
////
// App Launcher
////
var port = process.env.PORT || 8080
var host = process.env.HOST || '0.0.0.0'
app.listen(port, host, function () {
var msg = 'Server listening at http://localhost:' + port
console.log(msg)
})