node-paytmpg 3.0.5 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,6 +5,11 @@ var Transaction;
5
5
  var IDLEN = 10;
6
6
  var nodeBase64 = require('nodejs-base64-converter');
7
7
  var RazorPay = require('razorpay');
8
+ var OpenMoney = require('./adapters/open_money')
9
+ const PaytmChecksum = require('./checksum/PaytmChecksum.js');
10
+ const { stat } = require('fs');
11
+ const { config } = require('process');
12
+
8
13
 
9
14
  function sanitizeRequest(body) {
10
15
 
@@ -18,17 +23,28 @@ module.exports = function (app, callbacks) {
18
23
  var config = (app.get('np_config'))
19
24
  var useController = require('./np_user.controller.js')(app, callbacks);
20
25
 
26
+ var razorPayInstance;
27
+ var openMoneyInstance = new OpenMoney(config);
28
+
21
29
  if (config.razor_url)
22
- var razorPayInstance = new RazorPay({ key_id: config.KEY, key_secret: config.SECRET })
30
+ razorPayInstance = new RazorPay({ key_id: config.KEY, key_secret: config.SECRET })
31
+ if (config.open_money_url) {
32
+ openMoneyInstance = new OpenMoney(config);
33
+ }
23
34
 
35
+ let usingMultiDbOrm = false;
24
36
  if (config.db_url) {
25
37
  Transaction = require('../models/np_transaction.model.js');
38
+ usingMultiDbOrm = false;
39
+
26
40
  } else if (app.multidborm) {
27
41
  Transaction = require('../models/np_multidbplugin.js')('nptransactions', app.multidborm);
28
42
  Transaction.db = app.multidborm;
29
43
  Transaction.modelname = 'nptransactions'
30
44
  Transaction.idFieldName = 'orderId'
31
45
  app.NPTransaction = Transaction;
46
+ usingMultiDbOrm = true;
47
+
32
48
  }
33
49
 
34
50
  var module = {};
@@ -101,7 +117,7 @@ module.exports = function (app, callbacks) {
101
117
  params['ORDER_ID'] = req.body.ORDER_ID;
102
118
  params['CUST_ID'] = req.body.CUST_ID;
103
119
  params['TXN_AMOUNT'] = req.body.TXN_AMOUNT;
104
- params['CALLBACK_URL'] = req.body.CALLBACK_URL;
120
+ params['CALLBACK_URL'] = req.body.CALLBACK_URL + "?order_id=" + req.body.ORDER_ID;
105
121
  params['EMAIL'] = req.body.EMAIL;
106
122
  params['MOBILE_NO'] = req.body.MOBILE_NO;
107
123
  params['PRODUCT_NAME'] = req.body.PRODUCT_NAME;
@@ -109,28 +125,246 @@ module.exports = function (app, callbacks) {
109
125
 
110
126
  if (config.paytm_url) {
111
127
 
128
+ let initTxnbody = {
129
+ "requestType": "Payment",
130
+ "mid": params['MID'],
131
+ "websiteName": params['WEBSITE'],
132
+ "orderId": params['ORDER_ID'],
133
+ "callbackUrl": params['CALLBACK_URL'],
134
+ "txnAmount": {
135
+ "value": params['TXN_AMOUNT'],
136
+ "currency": params['CURRENCY'] || "INR",
137
+ },
138
+ "userInfo": {
139
+ "custId": params['CUST_ID'],
140
+ "mobile": params['MOBILE_NO'],
141
+ "firstName": params['NAME'],
142
+ "email": params['EMAIL']
143
+ }
144
+ };
145
+ let checksum = await PaytmChecksum.generateSignature(JSON.stringify(initTxnbody), config.KEY)
146
+ let initTxnUrl = config.paytm_url + `/theia/api/v1/initiateTransaction?mid=${params['MID']}&orderId=${params['ORDER_ID']}`;
147
+
148
+ request.post(
149
+ initTxnUrl,
150
+ {
151
+ json: {
152
+ "body": initTxnbody,
153
+ "head": {
154
+ "signature": checksum,
155
+ "channelId": params['CHANNEL_ID']
156
+ }
157
+ }
158
+ },
159
+ function (error, response, body) {
112
160
 
113
- checksum_lib.genchecksum(params, config.KEY, function (err, checksum) {
161
+ if (!error && response.statusCode != undefined
162
+ && response.statusCode != NaN &&
163
+ response.statusCode == 200 &&
164
+ body.body &&
165
+ body.body.resultInfo &&
166
+ body.body.resultInfo.resultStatus == "S") {
114
167
 
115
168
 
116
- var txn_url = config.paytm_url + "/theia/processTransaction"; // for staging
169
+ let paytmJsCheckouHtml = `<html>
170
+ <head>
171
+ <title>Merchant Checkout</title>
172
+ <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, maximum-scale=1.0"/>
173
+
174
+ </head>
175
+ <body>
176
+ <center>
177
+ <h1>Please donot close this page or press the back button. Processing...</h1>
178
+ <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="margin:auto;background:#fff;display:block;" width="200px" height="200px" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid">
179
+ <g transform="rotate(0 50 50)">
180
+ <rect x="47" y="24" rx="3" ry="6" width="6" height="12" fill="#fe718d">
181
+ <animate attributeName="opacity" values="1;0" keyTimes="0;1" dur="1s" begin="-0.9166666666666666s" repeatCount="indefinite"></animate>
182
+ </rect>
183
+ </g><g transform="rotate(30 50 50)">
184
+ <rect x="47" y="24" rx="3" ry="6" width="6" height="12" fill="#fe718d">
185
+ <animate attributeName="opacity" values="1;0" keyTimes="0;1" dur="1s" begin="-0.8333333333333334s" repeatCount="indefinite"></animate>
186
+ </rect>
187
+ </g><g transform="rotate(60 50 50)">
188
+ <rect x="47" y="24" rx="3" ry="6" width="6" height="12" fill="#fe718d">
189
+ <animate attributeName="opacity" values="1;0" keyTimes="0;1" dur="1s" begin="-0.75s" repeatCount="indefinite"></animate>
190
+ </rect>
191
+ </g><g transform="rotate(90 50 50)">
192
+ <rect x="47" y="24" rx="3" ry="6" width="6" height="12" fill="#fe718d">
193
+ <animate attributeName="opacity" values="1;0" keyTimes="0;1" dur="1s" begin="-0.6666666666666666s" repeatCount="indefinite"></animate>
194
+ </rect>
195
+ </g><g transform="rotate(120 50 50)">
196
+ <rect x="47" y="24" rx="3" ry="6" width="6" height="12" fill="#fe718d">
197
+ <animate attributeName="opacity" values="1;0" keyTimes="0;1" dur="1s" begin="-0.5833333333333334s" repeatCount="indefinite"></animate>
198
+ </rect>
199
+ </g><g transform="rotate(150 50 50)">
200
+ <rect x="47" y="24" rx="3" ry="6" width="6" height="12" fill="#fe718d">
201
+ <animate attributeName="opacity" values="1;0" keyTimes="0;1" dur="1s" begin="-0.5s" repeatCount="indefinite"></animate>
202
+ </rect>
203
+ </g><g transform="rotate(180 50 50)">
204
+ <rect x="47" y="24" rx="3" ry="6" width="6" height="12" fill="#fe718d">
205
+ <animate attributeName="opacity" values="1;0" keyTimes="0;1" dur="1s" begin="-0.4166666666666667s" repeatCount="indefinite"></animate>
206
+ </rect>
207
+ </g><g transform="rotate(210 50 50)">
208
+ <rect x="47" y="24" rx="3" ry="6" width="6" height="12" fill="#fe718d">
209
+ <animate attributeName="opacity" values="1;0" keyTimes="0;1" dur="1s" begin="-0.3333333333333333s" repeatCount="indefinite"></animate>
210
+ </rect>
211
+ </g><g transform="rotate(240 50 50)">
212
+ <rect x="47" y="24" rx="3" ry="6" width="6" height="12" fill="#fe718d">
213
+ <animate attributeName="opacity" values="1;0" keyTimes="0;1" dur="1s" begin="-0.25s" repeatCount="indefinite"></animate>
214
+ </rect>
215
+ </g><g transform="rotate(270 50 50)">
216
+ <rect x="47" y="24" rx="3" ry="6" width="6" height="12" fill="#fe718d">
217
+ <animate attributeName="opacity" values="1;0" keyTimes="0;1" dur="1s" begin="-0.16666666666666666s" repeatCount="indefinite"></animate>
218
+ </rect>
219
+ </g><g transform="rotate(300 50 50)">
220
+ <rect x="47" y="24" rx="3" ry="6" width="6" height="12" fill="#fe718d">
221
+ <animate attributeName="opacity" values="1;0" keyTimes="0;1" dur="1s" begin="-0.08333333333333333s" repeatCount="indefinite"></animate>
222
+ </rect>
223
+ </g><g transform="rotate(330 50 50)">
224
+ <rect x="47" y="24" rx="3" ry="6" width="6" height="12" fill="#fe718d">
225
+ <animate attributeName="opacity" values="1;0" keyTimes="0;1" dur="1s" begin="0s" repeatCount="indefinite"></animate>
226
+ </rect>
227
+ </g>
228
+ </svg>
229
+ </center>
230
+ <form id="cancelform" action="${params['CALLBACK_URL']}" method="post">
231
+ <input type="hidden" name="TXNID" value="na"/>
232
+ <input type="hidden" name="STATUS" value="TXN_FAILURE"/>
233
+ <input type="hidden" name="CANCELLED" value="cancelled"/>
234
+ <input id="RESPMSG" type="hidden" name="RESPMSG" value=""/>
235
+ <input type="hidden" name="ORDERID" value="${params["ORDER_ID"]}"/>
236
+ </form>
237
+
117
238
 
118
- // console.log(checksum)
119
- var form_fields = "";
120
- for (var x in params) {
121
- form_fields += "<input type='hidden' name='" + x + "' value='" + params[x] + "' >";
122
- }
123
- form_fields += "<input type='hidden' name='CHECKSUMHASH' value='" + checksum + "' >";
239
+ <script>
124
240
 
125
- res.writeHead(200, { 'Content-Type': 'text/html' });
126
- res.write('<html><head><title>Merchant Checkout Page</title></head><body><center><h1>Processing ! Please do not refresh this page...</h1></center><form method="post" action="' + txn_url + '" name="f1">' + form_fields + '</form><script type="text/javascript">document.f1.submit();</script></body></html>');
127
- res.end();
241
+ function getBodyColor(color){
242
+ const hex = color.replace('#', '');
243
+ const c_r = parseInt(hex.substr(0, 2), 16);
244
+ const c_g = parseInt(hex.substr(2, 2), 16);
245
+ const c_b = parseInt(hex.substr(4, 2), 16);
246
+ const brightness = ((c_r * 299) + (c_g * 587) + (c_b * 114)) / 1000;
247
+ // console.log(brightness , brightness > 155 ? "#fff" : "#1a1a1c")
248
+ return brightness > 155 ? "#1a1a1c" : "#ffffff";
249
+ }
128
250
 
129
- });
130
- }
131
- else if (config.razor_url) {
251
+ function shadeColor(color, percent) {
252
+
253
+ var R = parseInt(color.substring(1,3),16);
254
+ var G = parseInt(color.substring(3,5),16);
255
+ var B = parseInt(color.substring(5,7),16);
256
+
257
+ R = parseInt(R * (100 + percent) / 100);
258
+ G = parseInt(G * (100 + percent) / 100);
259
+ B = parseInt(B * (100 + percent) / 100);
260
+
261
+ R = (R<255)?R:255;
262
+ G = (G<255)?G:255;
263
+ B = (B<255)?B:255;
264
+
265
+ var RR = ((R.toString(16).length==1)?"0"+R.toString(16):R.toString(16));
266
+ var GG = ((G.toString(16).length==1)?"0"+G.toString(16):G.toString(16));
267
+ var BB = ((B.toString(16).length==1)?"0"+B.toString(16):B.toString(16));
268
+
269
+ return "#"+RR+GG+BB;
270
+ }
271
+
272
+ function failTxn(reason) {
273
+ var form = document.getElementById("cancelform");
274
+ var element2 = document.getElementById("RESPMSG");
275
+ element2.value=reason;
276
+ form.submit();
277
+ }
278
+ function onScriptLoad(){
279
+ var config = {
280
+ "root": "",
281
+ "flow": "DEFAULT",
282
+ "style": {
283
+ // "bodyColor": shadeColor("${config.theme_color}",+40),
284
+ "themeBackgroundColor": "${config.theme_color}",
285
+ "themeColor": getBodyColor("${config.theme_color}"),
286
+ "headerBackgroundColor": "${config.theme_color}",
287
+ "headerColor": getBodyColor("${config.theme_color}")
288
+ },
289
+ "data": {
290
+ "orderId": "${params['ORDER_ID']}", /* update order id */
291
+ "token": "${body.body.txnToken}", /* update token value */
292
+ "tokenType": "TXN_TOKEN",
293
+ "amount": "${params['TXN_AMOUNT']}" /* update amount */
294
+ },
295
+ "handler": {
296
+ "notifyMerchant": function(eventName,data){
297
+ // console.log("notifyMerchant handler function called");
298
+ // console.log("eventName => ",eventName);
299
+ // console.log("data => ",data);
300
+ if(eventName == "APP_CLOSED"){
301
+ failTxn(eventName)
302
+ }
303
+ }
304
+ }
305
+ };
306
+
307
+ if(window.Paytm && window.Paytm.CheckoutJS){
308
+ window.Paytm.CheckoutJS.onLoad(function excecuteAfterCompleteLoad() {
309
+ // initialze configuration using init method
310
+ window.Paytm.CheckoutJS.init(config).then(function onSuccess() {
311
+ // after successfully updating configuration, invoke JS Checkout
312
+ window.Paytm.CheckoutJS.invoke();
313
+ }).catch(function onError(error){
314
+ // console.log("error => ",error);
315
+ failTxn(error.message)
316
+ });
317
+ });
318
+ }
319
+ }
320
+ </script>
321
+ <script type="application/javascript" crossorigin="anonymous" src="${config.paytm_url}/merchantpgpui/checkoutjs/merchants/${params['MID']}.js" onload="onScriptLoad();" crossorigin="anonymous"></script>
322
+
323
+
324
+ </body>
325
+ </html>`
326
+ return res.send(paytmJsCheckouHtml)
327
+
328
+ }
329
+ else {
330
+ console.log('ERROR:::', error, '\n', body);
331
+ res.status(500)
332
+ var form_fields = "";
333
+ let errorResp = {
334
+ TXNID: "na",
335
+ STATUS: "TXN_FAILURE",
336
+ CANCELLED: "cancelled",
337
+ ORDERID: params["ORDER_ID"]
338
+ }
339
+ for (var x in errorResp) {
340
+ form_fields += "<input type='hidden' name='" + x + "' value='" + errorResp[x] + "' >";
341
+ }
342
+ form_fields += "<input type='hidden' name='CHECKSUMHASH' value='" + checksum + "' >";
343
+
344
+ res.writeHead(200, { 'Content-Type': 'text/html' });
345
+ res.write(`<html>
346
+
347
+ <head>
348
+ <title>Merchant Checkout Error</title>
349
+ </head>
350
+
351
+ <body>
352
+ <center>
353
+ <h1>Something went wrong. Please wait you will be redirected automatically...</h1>
354
+ </center>
355
+ <form method="post" action="${params['CALLBACK_URL']}" name="f1">${form_fields}</form>
356
+ <script type="text/javascript">document.f1.submit();</script>
357
+ </body>
358
+
359
+ </html>`);
360
+ res.end();
132
361
 
362
+ }
363
+ }
364
+ );
133
365
 
366
+ }
367
+ else if (config.razor_url) {
134
368
 
135
369
  let fail = `<div style="display:none">
136
370
 
@@ -174,6 +408,29 @@ module.exports = function (app, callbacks) {
174
408
  res.end();
175
409
 
176
410
  }
411
+ else if (config.open_money_url) {
412
+ try {
413
+ let pmttoken = await openMoneyInstance.generatePaymentToken(params);
414
+ openMoneyInstance.renderProcessingPage(params, pmttoken, res);
415
+
416
+ var myquery = { orderId: params['ORDER_ID'] };
417
+ Transaction.findOne(myquery, function (err, objForUpdate) {
418
+
419
+ objForUpdate.extra = JSON.stringify({
420
+ layer_pay_token_id: pmttoken.tokenid
421
+ });
422
+
423
+ var newvalues = { $set: objForUpdate };
424
+ Transaction.updateOne(myquery, newvalues, function (err, saveRes) {
425
+ let status = 'Updated TXNID'
426
+ });
427
+
428
+ }, usingMultiDbOrm ? Transaction : undefined)
429
+
430
+ } catch (e) {
431
+ openMoneyInstance.renderError(params, e, res)
432
+ }
433
+ }
177
434
  if (callbacks !== undefined)
178
435
  callbacks.onStart(params['ORDER_ID'], params);
179
436
  }
@@ -232,6 +489,8 @@ module.exports = function (app, callbacks) {
232
489
  checksum_lib.genchecksum(params, config.KEY, showConfirmation);
233
490
  else if (config.razor_url) {
234
491
  showConfirmation()
492
+ } else if (config.open_money_url) {
493
+ showConfirmation()
235
494
  }
236
495
 
237
496
  };
@@ -242,11 +501,11 @@ module.exports = function (app, callbacks) {
242
501
 
243
502
 
244
503
  var myquery = { orderId: req.body.ORDER_ID };
245
- Transaction.findOne(myquery, function (err, objForUpdate) {
504
+ Transaction.findOne(myquery, function (err, orderData) {
246
505
 
247
- onTxn(objForUpdate);
506
+ onTxn(orderData);
248
507
 
249
- }, Transaction);
508
+ }, usingMultiDbOrm ? Transaction : undefined);
250
509
 
251
510
 
252
511
 
@@ -261,6 +520,7 @@ module.exports = function (app, callbacks) {
261
520
  orderId: orderId,
262
521
  cusId: user.id,
263
522
  time: Date.now(),
523
+ timeStamp: Date.now(),
264
524
  status: 'INITIATED',
265
525
  name: user.name,
266
526
  email: user.email,
@@ -282,7 +542,7 @@ module.exports = function (app, callbacks) {
282
542
 
283
543
  let orderId;
284
544
  if (config.paytm_url) {
285
- orderId = makeid(config.id_length || IDLEN)
545
+ orderId = "pay_" + makeid(config.id_length || IDLEN)
286
546
  onOrder(orderId)
287
547
  }
288
548
  else if (config.razor_url) {
@@ -296,13 +556,17 @@ module.exports = function (app, callbacks) {
296
556
 
297
557
  razorPayInstance.orders.create(options, function (err, order) {
298
558
  if (err) {
299
- res.send({ message: "An error occurred ! " + err.message })
559
+ res.send({ message: "An error occurred ! " + err.description })
300
560
  return;
301
561
  }
302
562
  orderId = order.id
303
563
  onOrder(orderId)
304
564
  })
305
565
  }
566
+ else if (config.open_money_url) {
567
+ orderId = "pay_" + makeid(config.id_length || IDLEN)
568
+ onOrder(orderId)
569
+ }
306
570
 
307
571
 
308
572
 
@@ -346,14 +610,60 @@ module.exports = function (app, callbacks) {
346
610
 
347
611
  }
348
612
 
613
+ function updateTransaction(req, res) {
614
+ var myquery = { orderId: req.body.ORDERID };
615
+
616
+ Transaction.findOne(myquery, function (err, objForUpdate) {
349
617
 
350
- module.callback = (req, res) => {
618
+ if (err) {
619
+ res.send({ message: "Transaction Not Found !", ORDERID: req.body.ORDERID, TXNID: req.body.TXNID })
620
+ return;
621
+ }
622
+ if (objForUpdate.status != ("INITIATED") && objForUpdate.status != ("TXN_PENDING")) {
623
+ objForUpdate.readonly = "readonly"
624
+ objForUpdate.action = config.homepage
625
+ res.render(vp + "result.hbs", objForUpdate);
626
+ console.log("Transaction already processed ", req.body.ORDERID)
627
+ // res.send({ message: "Transaction already processed", status: objForUpdate.status, ORDERID: objForUpdate.orderId, TXNID: objForUpdate.TXNID, TXNID: req.body.TXNID })
628
+ return;
629
+ }
630
+ if (req.body.status == "paid" && !req.body.STATUS) {
631
+ req.body.STATUS = "TXN_SUCCESS"
632
+ }
633
+ objForUpdate.status = req.body.STATUS;
634
+ objForUpdate.TXNID = req.body.TXNID;
635
+ objForUpdate.extra = JSON.stringify(req.body);
636
+
637
+ var newvalues = { $set: objForUpdate };
638
+ Transaction.updateOne(myquery, newvalues, function (err, saveRes) {
639
+
640
+ if (err) {
641
+ res.send({ message: "Error Occured !", ORDERID: req.body.ORDERID, TXNID: req.body.TXNID })
642
+ }
643
+ else {
644
+
645
+ if (callbacks !== undefined)
646
+ callbacks.onFinish(req.body.ORDERID, req.body);
647
+ objForUpdate.readonly = "readonly"
648
+ objForUpdate.action = config.homepage
649
+ res.render(vp + "result.hbs", objForUpdate);
650
+ }
651
+ });
652
+
653
+ }, usingMultiDbOrm ? Transaction : undefined)
654
+ }
655
+
656
+ module.callback = async (req, res) => {
351
657
 
352
658
  var result = false;
353
659
  let isCancelled = false;
354
660
  if (config.paytm_url) {
355
661
  var checksumhash = req.body.CHECKSUMHASH;
356
662
  result = checksum_lib.verifychecksum(req.body, config.KEY, checksumhash);
663
+ if (req.body.STATUS == 'TXN_FAILURE' && req.body.CANCELLED == "cancelled" && req.body.TXNID) {
664
+ isCancelled = true;
665
+ }
666
+
357
667
  }
358
668
  else if (config.razor_url) {
359
669
 
@@ -374,10 +684,19 @@ module.exports = function (app, callbacks) {
374
684
  req.body.razorpay_order_id = orderId
375
685
  }
376
686
  req.body.STATUS = 'TXN_FAILURE'
377
- req.body.ORDERID = req.body.razorpay_order_id
687
+ req.body.ORDERID = req.body.razorpay_order_id || req.query.order_id
378
688
  isCancelled = true;
379
689
  }
380
690
  }
691
+ else if (config.open_money_url) {
692
+ let openRest = await openMoneyInstance.verifyResult(req);
693
+ result = true;
694
+ req.body.STATUS = openRest.STATUS
695
+ req.body.TXNID = openRest.TXNID
696
+ req.body.ORDERID = openRest.ORDERID || req.query.order_id
697
+ req.body.extras = openRest.data
698
+ }
699
+
381
700
 
382
701
  //console.log("Checksum Result => ", result, "\n");
383
702
  console.log("NodePayTMPG::Transaction => ", req.body.ORDERID, req.body.STATUS);
@@ -385,34 +704,7 @@ module.exports = function (app, callbacks) {
385
704
 
386
705
  if (result || isCancelled) {
387
706
 
388
- var myquery = { orderId: req.body.ORDERID };
389
- Transaction.findOne(myquery, function (err, objForUpdate) {
390
-
391
- if (err) {
392
- res.send({ message: "Transaction Not Found !", ORDERID: req.body.ORDERID, TXNID: req.body.TXNID })
393
- return;
394
- }
395
- objForUpdate.status = req.body.STATUS;
396
- objForUpdate.TXNID = req.body.TXNID;
397
- objForUpdate.extra = JSON.stringify(req.body);
398
-
399
- var newvalues = { $set: objForUpdate };
400
- Transaction.updateOne(myquery, newvalues, function (err, saveRes) {
401
-
402
- if (err) {
403
- res.send({ message: "Error Occured !", ORDERID: req.body.ORDERID, TXNID: req.body.TXNID })
404
- }
405
- else {
406
-
407
- if (callbacks !== undefined)
408
- callbacks.onFinish(req.body.ORDERID, req.body);
409
- objForUpdate.readonly = "readonly"
410
- objForUpdate.action = config.homepage
411
- res.render(vp + "result.hbs", objForUpdate);
412
- }
413
- });
414
-
415
- }, Transaction)
707
+ updateTransaction(req, res);
416
708
 
417
709
  }
418
710
  else {
@@ -423,6 +715,64 @@ module.exports = function (app, callbacks) {
423
715
 
424
716
  }
425
717
 
718
+ module.webhook = (req, res) => {
719
+ if (config.paytm_url) {
720
+ module.callback(req, res)
721
+ }
722
+ else if (config.razor_url) {
723
+ let events = ["payment.captured", "payment.pending", "payment.failed"]
724
+ if (req.body.event && events.indexOf(req.body.event) > -1) {
725
+ if (req.body.payload &&
726
+ req.body.payload.payment &&
727
+ req.body.payload.payment.entity) {
728
+
729
+ let entity = req.body.payload.payment.entity;
730
+ let razorpay_order_id = entity.order_id;
731
+ let razorpay_payment_id = entity.id;
732
+ let status = entity.status;
733
+ let event = req.body.event;
734
+ console.log(`Razorpay webhook payment order=${razorpay_order_id} payid=${razorpay_payment_id} status=${status}`)
735
+
736
+ let reqBody = req.rawBody, signature = req.headers["x-razorpay-signature"];
737
+
738
+ result = RazorPay.validateWebhookSignature(reqBody, req.headers['x-razorpay-signature'], config.SECRET)
739
+ req.signatureVerified = result;
740
+ if (result) {
741
+ if (event == events[0]) {
742
+ req.body.STATUS = "TXN_SUCCESS";
743
+ }
744
+ else if (event == events[1]) { //pending
745
+ req.body.STATUS = "TXN_PENDING";
746
+ }
747
+ else { // failed
748
+ req.body.STATUS = "TXN_FAILURE";
749
+ }
750
+ req.body.ORDERID = razorpay_order_id;
751
+ req.body.TXNID = razorpay_payment_id;
752
+ setTimeout(() => {
753
+ updateTransaction(req, res)
754
+ }, 3000)
755
+ }
756
+ else {
757
+ res.status(401)
758
+ res.send({ message: "Invalid Rzpay signature" })
759
+ }
760
+ }
761
+ else {
762
+ res.status(400)
763
+ res.send({ message: "Invalid Payload" })
764
+ }
765
+ }
766
+ else {
767
+ res.status(400)
768
+ res.send({ message: "Unsupported event : " + req.body.event })
769
+ }
770
+ }
771
+ else if (config.open_money_url) {
772
+ openMoneyInstance.processWebhook(req, res, updateTransaction)
773
+ }
774
+ }
775
+
426
776
  module.createTxn = (req, res) => {
427
777
 
428
778
 
@@ -432,7 +782,7 @@ module.exports = function (app, callbacks) {
432
782
 
433
783
  let id;
434
784
  if (config.paytm_url) {
435
- id = makeid(config.id_length || IDLEN)
785
+ id = "pay_" + makeid(config.id_length || IDLEN)
436
786
  }
437
787
  else if (config.razor_url) {
438
788
 
@@ -489,15 +839,18 @@ module.exports = function (app, callbacks) {
489
839
 
490
840
  module.status = (req, res) => {
491
841
 
842
+ if (!req.body.ORDER_ID && req.query.ORDER_ID) {
843
+ req.body.ORDER_ID = req.query.ORDER_ID
844
+ }
492
845
  var myquery = { orderId: req.body.ORDER_ID };
493
- Transaction.findOne(myquery, async function (err, objForUpdate) {
846
+ Transaction.findOne(myquery, async function (err, orderData) {
494
847
 
495
848
 
496
849
  if (err) {
497
850
  res.send(err)
498
851
  return
499
852
  }
500
- if (objForUpdate.status === "INITIATED") {
853
+ if (orderData.status === "INITIATED") {
501
854
 
502
855
  var params = {}
503
856
  params["MID"] = config.MID;
@@ -505,10 +858,10 @@ module.exports = function (app, callbacks) {
505
858
 
506
859
  async function onStatusUpdate(paytmResponse) {
507
860
  if (paytmResponse.TXNID.length > 4) {
508
- objForUpdate.status = paytmResponse.STATUS;
509
- objForUpdate.extra = JSON.stringify(paytmResponse);
861
+ orderData.status = paytmResponse.STATUS;
862
+ orderData.extra = JSON.stringify(paytmResponse);
510
863
 
511
- var newvalues = { $set: objForUpdate };
864
+ var newvalues = { $set: orderData };
512
865
  Transaction.updateOne(myquery, newvalues, function (err, saveRes) {
513
866
 
514
867
  if (err) {
@@ -516,13 +869,13 @@ module.exports = function (app, callbacks) {
516
869
  }
517
870
  else {
518
871
  if (callbacks !== undefined)
519
- callbacks.onFinish(req.body.ORDER_ID, objForUpdate);
872
+ callbacks.onFinish(req.body.ORDER_ID, orderData);
520
873
  res.send(paytmResponse)
521
874
  }
522
875
  });
523
876
  }
524
877
  else {
525
- res.send(objForUpdate)
878
+ res.send(orderData)
526
879
 
527
880
  }
528
881
  }
@@ -565,17 +918,45 @@ module.exports = function (app, callbacks) {
565
918
  onStatusUpdate(result)
566
919
  }
567
920
  else {
568
- res.send(objForUpdate);
921
+ res.send(orderData);
922
+ }
923
+ }
924
+ else if (config.open_money_url) {
925
+ let extras = JSON.parse(orderData.extra)
926
+ if (!extras || !extras.layer_pay_token_id) {
927
+ res.status(500)
928
+ return res.send({ message: 'An unexpected error occured. No payment token exists' })
929
+ }
930
+ let result = await openMoneyInstance.getPaymentStatus(extras.layer_pay_token_id)
931
+ result = JSON.parse(result)
932
+ result.ORDERID = req.body.ORDER_ID
933
+ if (result.status == 'paid' || result.status == 'captured') {
934
+ result.STATUS = 'TXN_SUCCESS'
935
+ result.TXNID = result.id
936
+ onStatusUpdate(result)
937
+ }
938
+ else if (result.status == 'pending' || result.status == 'attempted') {
939
+ result.STATUS = 'TXN_PENDING'
940
+ result.TXNID = result.id
941
+ onStatusUpdate(result)
942
+ }
943
+ else if (result.status == 'failed' || result.status == 'cancelled') {
944
+ result.STATUS = 'TXN_FAILED'
945
+ result.TXNID = result.id
946
+ onStatusUpdate(result)
947
+ }
948
+ else {
949
+ res.send(orderData);
569
950
  }
570
951
  }
571
952
 
572
953
  }
573
954
  else {
574
- res.send(objForUpdate);
955
+ res.send(orderData);
575
956
  }
576
957
 
577
958
 
578
- }, Transaction);
959
+ }, usingMultiDbOrm ? Transaction : undefined);
579
960
 
580
961
 
581
962
  }