-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.js
786 lines (665 loc) · 26.7 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
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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
var PAGE_ACCESS_TOKEN = process.env.PAGE_ACCESS_TOKEN;
var MESSENGER_VALIDATION_TOKEN = process.env.MESSENGER_VALIDATION_TOKEN;
var SERVER_URL = 'https://hellopanpan.azurewebsites.net';
var express = require('express'),
config = require('./config/config'),
users = require('./config/users'),
mm = require('minimatch'),
bodyParser = require('body-parser'),
request = require('request');
var app = express();
app.use(bodyParser.json());
var qr = require('qr-image');
app.get('/webhook', function(req, res) {
if (req.query['hub.mode'] === 'subscribe' &&
req.query['hub.verify_token'] === MESSENGER_VALIDATION_TOKEN) {
console.log("Validating webhook");
res.status(200).send(req.query['hub.challenge']);
} else {
console.error("Failed validation. Make sure the validation tokens match.");
res.sendStatus(403);
}
});
app.post('/webhook', function (req, res) {
var data = req.body;
// Make sure this is a page subscription
if (data.object == 'page') {
// Iterate over each entry - there may be multiple if batched
data.entry.forEach(function(entry) {
var pageID = entry.id;
var timeOfEvent = entry.time;
// Iterate over each messaging event
entry.messaging.forEach(function(event) {
if (event.message) {
receivedMessage(event);
} else if (event.postback) {
receivedPostback(event);
}else {
console.log("Webhook received unknown event: ", event);
}
});
});
// Assume all went well.
//
// You must send back a 200, within 20 seconds, to let us know
// you've successfully received the callback. Otherwise, the request
// will time out and we will keep trying to resend.
res.sendStatus(200);
}
});
function receivedMessage(event) {
// Putting a stub for now, we'll expand it in the following steps
// console.log("Message data: ", event.message);
var senderID = event.sender.id;
var recipientID = event.recipient.id;
var timeOfMessage = event.timestamp;
var message = event.message;
console.log("Received message for user %d and page %d at %d with message:",
senderID, recipientID, timeOfMessage);
console.log(JSON.stringify(message));
var messageId = message.mid;
var messageText = message.text;
var messageAttachments = message.attachments;
if (messageText) {
// If we receive a text message, check to see if it matches a keyword
// and send back the example. Otherwise, just echo the text we received.
messageText = messageText.toLowerCase();
// user wants to save money
if (mm(messageText, "save *")) {
var amountToSave = parseInt(messageText.replace(/[^0-9\.]/g, ''), 10).toString();
if (isNaN(amountToSave)){
console.log('user did not include a valid amount to save in message: ' + messageText);
// send message scolding them
return;
}
console.log("User wants to save: " + amountToSave);
saveMoney(senderID, amountToSave, messageText);
return;
} else if (mm(messageText, "send * to *")) {
var splitMessageText = messageText.split("to");
var transactionAmount = parseInt(splitMessageText[0].replace(/[^0-9\.]/g, ''), 10).toString();
if (isNaN(transactionAmount)){
console.log('user did not include a valid amount to save in message: ' + messageText);
// send message scolding them
return;
}
var recipientAccountNo = parseInt(splitMessageText[1].replace(/[^0-9\.]/g, ''), 10);
var recipientAccountNoStr = "";
console.log("splitMessageText[1]: " + splitMessageText[1]);
if (isNaN(recipientAccountNo)) {
console.log("inside switch");
switch(splitMessageText[1]) {
case ' panpan lin':
recipientAccountNoStr = "10000388";
break;
case ' mauricio reis':
recipientAccountNoStr = "10000374";
break;
case ' julia sn':
recipientAccountNoStr = "10000389";
break;
case ' jeisse rocha':
recipientAccountNoStr = "10000375";
break;
case ' ying feng':
recipientAccountNoStr = "10000390";
break;
default:
break;
}
console.log("recipientAccountNoStr: " + recipientAccountNoStr);
if (recipientAccountNoStr == "") {
sendTextMessage(senderID, "Can't find registered user with this name among your friends. Please use full name.");
return;
}
} else {
recipientAccountNoStr = recipientAccountNo.toString();
}
var paymentReference = "received " + transactionAmount + " GBP from " + users[senderID]["givenName"] + " " + users[senderID]["familyName"];
var serverFeedbackToUser = "Your request to send " + transactionAmount + " GBP has been received.";
console.log("Send money with params: ", senderID, recipientAccountNoStr, transactionAmount, paymentReference, serverFeedbackToUser);
sendMoney(senderID, recipientAccountNoStr, transactionAmount, paymentReference, serverFeedbackToUser);
return;
} else if (mm(messageText, "request *")){
//Create the QrCOde and send to fb
var amountToSend = parseInt(messageText.replace(/[^0-9\.]/g, ''), 10);
console.log("generate qrCode: "+amountToSend);
createQrCode(senderID, amountToSend);
//senderID aqui
sendImageMessage(senderID);
console.log("Seller generate qrCode: " + amountToSave);
return;
}
switch (messageText) {
case 'generic':
case 'info':
case 'information':
case 'about ulster bank':
case 'about':
sendGenericMessage(senderID);
break;
case 'help':
sendTextMessage(senderID, "To sign up, type\nsign up. If you have already signed up, try type some of these to the chat window:\ncurrent account balance\nsaving account balance\ncurrent account transaction history\nsend 5 GBP to account XXXXX");
sendTextMessage(senderID, "To find your nearest ATMs, use your phone to send us your location");
sendTextMessage(senderID, "You can also request payments or pay others via QR code, without adding the other person as a friend, as long as the other party has also registered their bank account with us. For more information, type\nqrcode");
break;
case 'transaction history':
case 'transactions history':
case 'recent transactions':
case 'recent transaction':
case 'current account history':
case 'current account transactions':
case 'current account transaction':
case 'current account transaction history':
case 'current account transactions history':
case 'current account recent transactions':
case 'current account recent transactions history':
getTransactionsHistory(senderID, "current");
break;
case 'saving account history':
case 'saving account transactions':
case 'saving account transaction':
case 'saving account transaction history':
case 'saving account transactions history':
case 'saving account recent transactions':
case 'saving account recent transactions history':
getTransactionsHistory(senderID, "saving");
break;
case 'current account balance':
case 'current account':
case 'check current account balance':
console.log('user checking current account ' + users[senderID]["currentAccountId"]);
var currentAccountID = users[senderID]["currentAccountId"];
checkBalance(senderID, currentAccountID, "current");
break;
case 'saving account balance':
case 'saving account':
case 'check saving account balance':
console.log('user checking saving account ' + users[senderID]["savingAccountId"]);
var savingAccountID = users[senderID]["savingAccountId"];
checkBalance(senderID, savingAccountID, "saving");
break;
case 'account balance':
case 'accounts balance':
case 'balance':
case 'check account balance':
case 'check accounts balance':
var currentAccountID = users[senderID]["currentAccountId"];
checkBalance(senderID, currentAccountID, "current");
var savingAccountID = users[senderID]["savingAccountId"];
checkBalance(senderID, savingAccountID, "saving");
default:
sendTextMessage(senderID, messageText);
}
} else if (messageAttachments) {
console.log('received attachment');
if (messageAttachments[0] && messageAttachments[0].payload && messageAttachments[0].payload.coordinates && mm(messageAttachments[0].url, "https://l.facebook.com/l.php?*www.bing.com%2Fmaps*") ) {
sendTextMessage(senderID, "querying nearest ATMs");
var latitude = messageAttachments[0].payload.coordinates.lat.toString();
var longitude = messageAttachments[0].payload.coordinates.long.toString();
console.log('User ' + senderID + "looking for ATM near: " + latitude + ", " + longitude);
getNearAtm(senderID, latitude, longitude);
}else{
console.log('entered on decodeQrCode');
decodeQrCode('', senderID);
}
console.log("messageAttachments: " + JSON.stringify(messageAttachments));
}
}
/*
* Postback Event
*
* This event is called when a postback is tapped on a Structured Message.
* https://developers.facebook.com/docs/messenger-platform/webhook-reference/postback-received
*
*/
function receivedPostback(event) {
var senderID = event.sender.id;
var recipientID = event.recipient.id;
var timeOfPostback = event.timestamp;
// The 'payload' param is a developer-defined field which is set in a postback
// button for Structured Messages.
var payload = event.postback.payload;
console.log("Received postback for user %d and page %d with payload '%s' " +
"at %d", senderID, recipientID, payload, timeOfPostback);
// When a postback is called, we'll send a message back to the sender to
// let them know it was successful
if (payload == "cancel"){
sendTextMessage(senderID, "Transaction cancelled. Your account has NOT been deducted.");
} else if (payload == "request callback") {
sendTextMessage(senderID, "Thanks for your interests, we'll contact you shortly.");
} else {
var args = JSON.parse(payload);
sendMoneyRequest.apply(this, args);
}
}
/*
* Send a Structured Message (Generic Message type) using the Send API.
*
*/
function sendGenericMessage(recipientId, messageText) {
var messageData = {
recipient: {
id: recipientId
},
message: {
attachment: {
type: "template",
payload: {
template_type: "generic",
elements: [{
title: "Ulster Bank",
subtitle: "",
item_url: "http://digital.ulsterbank.ie/",
image_url: "https://pbs.twimg.com/profile_images/481434724317945859/bspl1Agb_400x400.jpeg",
buttons: [{
type: "web_url",
url: "http://digital.ulsterbank.ie/",
title: "Open Web URL"
}, {
type: "phone_number",
title: "Call Representative",
payload: "1850211690",
}],
}, {
title: "Mortgages",
subtitle: "Your saving account looks great!",
item_url: "http://digital.ulsterbank.ie/personal/mortgages.html",
image_url: "http://www.irishhome.ie/wp-content/uploads/2015/08/a-mortgage-you-can-live-with-ulster-bank.jpg",
buttons: [{
type: "web_url",
url: "http://digital.ulsterbank.ie/personal/mortgages.html",
title: "Open Web URL"
}, {
type: "postback",
title: "Request a callback",
payload: "request callback",
}]
}]
}
}
}
};
callSendAPI(messageData);
}
function sendTextMessage(recipientId, messageText) {
var messageData = {
recipient: {
id: recipientId
},
message: {
text: messageText
}
};
callSendAPI(messageData);
}
function callSendAPI(messageData) {
request({
uri: 'https://graph.facebook.com/v2.6/me/messages',
qs: { access_token: PAGE_ACCESS_TOKEN },
method: 'POST',
json: messageData
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
var recipientId = body.recipient_id;
var messageId = body.message_id;
console.log("Successfully sent generic message with id %s to recipient %s",
messageId, recipientId);
} else {
console.error("Unable to send message.");
console.error(response);
console.error(error);
}
});
}
function getNearAtm(recipientId, latitude, longitude) {
console.log('inside function getNEarAtm');
var queryUrl = 'https://bluebank.azure-api.net/api/v0.6.3/atms/near?lat=' + latitude + '&long=' + longitude + '&radius=500';
console.log("queryUrl: " + queryUrl);
request({
headers: {
'Ocp-Apim-Subscription-Key': users[recipientId]['token']
},
uri: queryUrl,
method: 'GET'
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log("Successfully sent atm inquiry for account for location Lat: %s, Long: %s",
latitude, longitude);
var parsedBody = JSON.parse(body);
if (parsedBody.length == 0) {
sendTextMessage(recipientId, "Sorry, no ATM info nearby.");
return;
}
for (var i = 0; i < parsedBody.length; i++) {
var atm = parsedBody[i];
var messageText = atm.brand + " ATM: " + atm.atmName + "\n" + "Address: " + atm.streetAddress + ", " + atm.city + ", " + atm.postCode;
sendTextMessage(recipientId, messageText);
}
} else {
console.error("Unable to inquire account balance");
console.error(response);
console.error(error);
sendTextMessage(recipientId, "Sorry, failed to query nearby ATMs.");
}
});
}
function getTransactionsHistory(customerId, accountType) {
var accountTypeQueryStr = accountType + "AccountId";
var accountId = users[customerId][accountTypeQueryStr];
var queryUrl = 'https://bluebank.azure-api.net/api/v0.6.3/accounts/' + accountId + '/transactions?sortOrder=-transactionDateTime&limit=5'
request({
headers: {
'Ocp-Apim-Subscription-Key': users[customerId]['token'],
'bearer': users[customerId]['bearer']
},
uri: queryUrl,
method: 'GET'
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log("Successfully inquire recenet transactions for account %s for user %s",
accountId, customerId);
console.log(body);
var parsedBody = JSON.parse(body);
var transactionHistoryMessageText = "You don't have any transactions on your" + accountType + " account yet.";
if (parsedBody.length > 0) {
transactionHistoryMessageText = "That is your " + accountType + " account recent transaction history.";
}
sendTextMessage(customerId, transactionHistoryMessageText);
for (var i = 0; i < parsedBody.length; i++) {
var transactionTimestamp = parsedBody[i]["transactionDateTime"].split("T");
var transactionTimeStr = transactionTimestamp[0] + " " + transactionTimestamp[1].slice(0,8);
var transactionInfoStr = parsedBody[i]["transactionAmount"] + "\n" + parsedBody[i]["transactionDescription"] + "\n" + transactionTimeStr;
sendTextMessage(customerId, transactionInfoStr);
}
} else {
console.error("Unable to inquire transaction history");
console.error(response);
console.error(error);
var failedMessageText = "Failed to inquire transaction history on your " + accountType + " account. Try again later or contact the page admin.";
sendTextMessage(customerId, failedMessageText);
}
});
}
function sendMoney(senderId, recipientAccountNo, transactionAmount, messageText, serverFeedbackToUser) {
var recipientId = "";
var recipientAccountType = "";
for (var facebookKey in users) {
if (users.hasOwnProperty(facebookKey)) {
for (var accountProp in users[facebookKey]) {
if (users[facebookKey][accountProp] == recipientAccountNo) {
recipientId = facebookKey;
recipientAccountType = accountProp.split("Account")[0];
}
}
}
}
if (recipientId == senderId) {
confirmSavingMoney(senderId, recipientAccountNo, transactionAmount, messageText, serverFeedbackToUser);
} else if (recipientId != "") {
confirmSendingMoneyWithRecipientFacebook(senderId, recipientAccountNo, transactionAmount, messageText, serverFeedbackToUser, recipientId, recipientAccountType);
} else {
confirmSendingMoney(senderId, recipientAccountNo, transactionAmount, messageText, serverFeedbackToUser);
}
}
function sendMoneyRequest(senderId, recipientAccountNo, transactionAmount, messageText, serverFeedbackToUser, recipientId, recipientAccountType) {
var queryUrl = 'https://bluebank.azure-api.net/api/v0.6.3/accounts/' + users[senderId]["currentAccountId"] +'/payments';
var bodyStr = JSON.stringify({
"toAccountNumber":recipientAccountNo,
"toSortCode":"839999",
"paymentReference":messageText + ", via Facebook MoneyTalk Page",
"paymentAmount":transactionAmount
});
request.post({
headers: {
'Ocp-Apim-Subscription-Key': users[senderId]['token'],
'bearer': users[senderId]['bearer'],
'Content-Type': 'application/json'
},
uri: queryUrl,
method: 'POST',
body: bodyStr
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log("Successfully send: " + transactionAmount);
sendTextMessage(senderId, serverFeedbackToUser);
if (recipientId != "") {
setTimeout(function () {
if (recipientId != senderId) {
sendTextMessage(recipientId, "You have received " + transactionAmount + " GBP in your " + recipientAccountType + " account " + " from " + users[senderId]["givenName"] + " " + users[senderId]['familyName'] + "\n https://www.facebook.com/" + users[senderId]["facebookHandler"]);
sendTextMessage(senderId, "Your earlier request to send " + transactionAmount + " GBP to "+ users[recipientId]["givenName"] + " " + users[recipientId]['familyName'] + "\n https://www.facebook.com/" + users[recipientId]["facebookHandler"] + " has been processed successfully.");
} else {
sendTextMessage(recipientId, "Your request to save " + transactionAmount + " GBP into your saving account has been processed.");
}
}, 20000)
}
} else {
console.error("Unable to carry out transaction");
console.error(response);
console.error(error);
var parsedBody = JSON.parse(body);
var errorMessage = "unknown error";
if (parsedBody.errorMessage) {
errorMessage = parsedBody.errorMessage;
}
var failedMessageText = "Transaction failed due to error: " + errorMessage + ".";
sendTextMessage(senderId, failedMessageText);
}
});
}
function confirmSendingMoney(senderId, recipientAccountNo, transactionAmount, messageText, serverFeedbackToUser) {
var messageData = {
recipient: {
id: senderId
},
message: {
attachment: {
type: "template",
payload: {
template_type: "generic",
elements: [{
title: "Send " + transactionAmount + " GBP to account: " + recipientAccountNo,
subtitle: "",
item_url: "",
image_url: "",
buttons: [{
type: "postback",
title: "Confirm",
payload: JSON.stringify([senderId, recipientAccountNo, transactionAmount, messageText, serverFeedbackToUser, "", ""])
}, {
type: "postback",
title: "Cancel",
payload: "cancel",
}]
}]
}
}
}
};
callSendAPI(messageData);
}
function confirmSavingMoney(senderId, recipientAccountNo, transactionAmount, messageText, serverFeedbackToUser) {
var messageData = {
recipient: {
id: senderId
},
message: {
attachment: {
type: "template",
payload: {
template_type: "generic",
elements: [{
title: "Save " + transactionAmount + " GBP to saving account.",
subtitle: "",
item_url: "",
image_url: "",
buttons: [{
type: "postback",
title: "Confirm",
payload: JSON.stringify([senderId, recipientAccountNo, transactionAmount, messageText, serverFeedbackToUser, senderId, "saving"])
}, {
type: "postback",
title: "Cancel",
payload: "cancel",
}]
}]
}
}
}
};
callSendAPI(messageData);
}
function confirmSendingMoneyWithRecipientFacebook(senderId, recipientAccountNo, transactionAmount, messageText, serverFeedbackToUser, recipientId, recipientAccountType) {
var messageData = {
recipient: {
id: senderId
},
message: {
attachment: {
type: "template",
payload: {
template_type: "generic",
elements: [{
title: "Send " + transactionAmount + " GBP to " + users[recipientId]["givenName"] + " " + users[recipientId]["familyName"],
subtitle: "",
item_url: "https://www.facebook.com/" + users[recipientId]["facebookHandler"],
image_url: "https://panpan-lin.github.io/roots/img/team/" + recipientId + ".jpg",
buttons: [{
type: "postback",
title: "Confirm",
payload: JSON.stringify([senderId, recipientAccountNo, transactionAmount, messageText, serverFeedbackToUser, recipientId, recipientAccountType])
}, {
type: "postback",
title: "Cancel",
payload: "cancel",
}]
}]
}
}
}
};
callSendAPI(messageData);
}
function saveMoney(recipientId, amountToSave, messageText) {
var savingAccountNo = users[recipientId]["savingAccountNumber"];
var serverFeedbackToUser = "Your request to save " + amountToSave + " GBP into your saving account has been received.";
sendMoney(recipientId, savingAccountNo, amountToSave, messageText, serverFeedbackToUser);
}
function checkBalance(recipientId, bankAccountId, accountType) {
var queryUrl = 'https://bluebank.azure-api.net/api/v0.6.3/accounts/' + bankAccountId;
request({
headers: {
'Ocp-Apim-Subscription-Key': users[recipientId]['token'],
'bearer': users[recipientId]['bearer']
},
uri: queryUrl,
method: 'GET'
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log("Successfully sent balance inquiry for account %s for user %s",
bankAccountId, recipientId);
console.log(body);
var parsedBody = JSON.parse(body);
var accountBalance = parsedBody.accountBalance;
var accountCurrency = parsedBody.accountCurrency;
var accountBalanceMessage = "Your " + accountType + " account balance is: " + accountBalance + " " + accountCurrency;
sendTextMessage(recipientId, accountBalanceMessage);
} else {
console.error("Unable to inquire account balance");
console.error(response);
console.error(error);
sendTextMessage(recipientId, "Failed to inquire account balance.");
}
});
}
function callBankAPI(accountId) {
request({
uri: 'https://bluebank.azure-api.net/api/v0.6.3/accounts/' + accountId,
qs: { access_token: PAGE_ACCESS_TOKEN },
method: 'POST',
json: messageData
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
var recipientId = body.recipient_id;
var messageId = body.message_id;
console.log("Successfully sent generic message with id %s to recipient %s",
messageId, recipientId);
} else {
console.error("Unable to send message.");
console.error(response);
console.error(error);
}
});
}
function createQrCode(sellerID, amountToSend) {
console.log('inside createQrCode');
//var queryUrl = 'https://bluebank.azure-api.net/api/v0.6.3/accounts/' + sellerID +'/payments?amount='+amountToSend;
var queryUrl = '{"seller":'+sellerID+', "amount":'+amountToSend+'}';
var qr_png = qr.image(queryUrl, {type: 'png' });
qr_png.pipe(require('fs').createWriteStream('public/img/qrcode.png'));
console.log('generated qrcode name:qrcode'+sellerID+'.png');
}
/* function decodeQrCode() {
//get this from messageAttachments
var imag_url = 'http://api.qrserver.com/v1/read-qr-code/?fileurl=https://hellopanpan.azurewebsites.net/img/qrcode58a1737f06d0f9e7189d1db7.png';
request({
uri: imag_url
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
var resp = JSON.parse(body);
var full_url = resp[0]['symbol'][0]['data'];
var qrcode_img = ;
console.log("aqui "+ qrcode_img);
}
});
}
decodeQrCode();
*/
function sendImageMessage(recipientId) {
var messageData = {
recipient: {
id: recipientId
},
message: {
attachment:{
type:"image",
payload:{
url:SERVER_URL+"/img/qrcode"+recipientId+".png"
}
}
}
};
callSendAPI(messageData);
}
function decodeQrCode(qrCodeUrl, senderID) {
//get this from messageAttachments
//todo put dinamic url
var imag_url = 'http://api.qrserver.com/v1/read-qr-code/?fileurl=https://hellopanpan.azurewebsites.net/img/qrcode.png';
console.log('image url'+imag_url);
request({
uri: imag_url
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
var resp = JSON.parse(body);
var transactionsInfo = JSON.parse(resp[0]['symbol'][0]['data']);
console.log('json from image'+transactionsInfo);
var paymentReference = "received " + transactionsInfo.amount + " from " + users[senderID]["givenName"];
console.log('payment'+paymentReference);
var serverFeedbackToUser = "Successfully sent " + transactionsInfo.amount + " to account : " + users[transactionsInfo.seller]['givenName'];
console.log("Send QR money with params: ", senderID, users[transactionsInfo.seller]['currentAccountNo'], transactionsInfo.amount, paymentReference, serverFeedbackToUser);
sendMoney(senderID, users[transactionsInfo.seller]['currentAccountNo'], transactionsInfo.amount, paymentReference, serverFeedbackToUser);
}else{
console.log('error on request image decode: '+error);
}
});
}
//TODO test if this send image message is working
//sendImageMessage("1217825631647606", "./png_sample.png");
app.get('/imageMessageToMauricio', function(req, res) {
sendImageMessage("1217825631647606", "./qrcode83787384783793840.png");
res.status(200).send({"foo" : "bar"});
});
module.exports = require('./config/express')(app, config);
app.listen(config.port, function () {
console.log('Express server listening on port ' + config.port);
});