-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
1911 lines (1632 loc) · 49.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
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
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import express from 'express'
import bodyParser from 'body-parser'
import crypto from 'crypto'
import sqlite3 from 'sqlite3'
import { open } from 'sqlite'
import fetch from 'node-fetch'
import { pay } from 'ln-service'
import { authenticatedLndGrpc } from 'lightning'
import sgMail from '@sendgrid/mail'
import twilio from 'twilio'
// set all the env vars
const port = process.env.port
const webhookSecret = process.env.webhookSecret
const dbLocation = process.env.dbLocation
const btcpayBaseUri = process.env.btcpayBaseUri
const lnUrlBaseUri = process.env.lnUrlBaseUri
const btcpayApiKey = process.env.btcpayApiKey
const lndTlsCert = process.env.lndTlsCert
const lndMacaroon = process.env.lndMacaroon
const lndIpAndPort = process.env.lndIpAndPort
const onChainZpub = process.env.onChainZpub
const basePath = process.env.basePath
const defaultLogoUri = process.env.defaultLogoUri
const defaultCssUri = process.env.defaultCssUri
const internalKey = process.env.internalKey
const sendgridApiKey = process.env.sendgridApiKey
const bullBitcoinBaseUrl = "https://api.bullbitcoin.com"
const fooodAppUserId = process.env.fooodAppUserId
const twilioAccountSid = process.env.twilioAccountSid
const twilioAuthToken = process.env.twilioAuthToken
const twilioPhoneNumber = process.env.twilioPhoneNumber
sgMail.setApiKey(sendgridApiKey)
const twilioClient = twilio(twilioAccountSid, twilioAuthToken)
// these paths don't need to do hmac-sha256 verififaction
const noAuthPaths = [
'/addStore',
'/tipSplit',
'/tipLnurl',
'/getTipConfiguration',
'/updateStoreAppIds',
'/enableLnurl',
'/setTipSplit',
'/findStores',
'/foood-app-stores',
]
// connect to the db
const db = await open({
filename: dbLocation,
driver: sqlite3.Database
})
const app = express()
const {lnd} = authenticatedLndGrpc({
cert: lndTlsCert,
macaroon: lndMacaroon,
socket: lndIpAndPort,
})
app.use('/tipSplit', express.static(`${basePath}/tip-split/build`));
// parse as JSON, but also keep the rawBody for HMAC verification
app.use(bodyParser.json({
verify: (req, res, buf) => {
req.rawBody = buf
}
}))
// HMAC verification middleware
app.use((req, res, next) => {
if(noAuthPaths.indexOf(req.url.split("?")[0]) !== -1) {
next()
return
}
if(noAuthPaths.indexOf(req.url.split("?")[0].replace(/\/$/, "")) !== -1) {
next()
return
}
if(noAuthPaths.indexOf('/' + req.url.split("/")[1].replace(/\/$/, "")) !== -1) {
next()
return
}
const test = crypto.createHmac('sha256', webhookSecret).update(req.rawBody).digest("hex")
const sig = req.headers['btcpay-sig'].replace('sha256=', '')
if(test !== sig) {
console.log('signature failed')
res.sendStatus(401)
} else {
next()
}
})
// process the webhook from BTCPay Server
app.post('/forward', async (req, res) => {
console.log('webook post data', req.body)
// we only care about settled invoices
if(req.body.type !== "InvoiceSettled") {
console.log('not invoice settled type')
res.sendStatus(200)
return
}
// check to see if this invoice already exists in the db
const invoiceExists = await getInvoice(db, req.body.storeId, req.body.invoiceId)
// if the invoice does exist in the db, we need to do some additional checks
if(invoiceExists) {
// if the invoice is currently processing, we don't want a race condition
if(invoiceExists.isProcessing) {
console.log('invoice is currently processing')
res.sendStatus(404)
return
}
// if the invoice has already been processed, we don't have anything else to do
if(invoiceExists.isProcessed) {
console.log('invoice is already processed')
res.sendStatus(200)
return
}
}
// save the exeuction to the db
const saveInvoice = await addInvoice(db, req.body.storeId, req.body.invoiceId, true, false)
if(!saveInvoice) {
console.log('unexpected error saving invoice to db')
res.sendStatus(404)
return
}
// if the invoice was manually marked, don't send money, bc we didn't really get any money
// if(req.body.manuallyMarked) {
// // mark the invoice as processed so we don't try it again
// await setInvoiceProcessed(db, req.body.storeId, req.body.invoiceId)
// console.log('is manually marked')
// res.sendStatus(200)
// return
// }
// fetch store details from the db
const store = await getStore(db, req.body.storeId)
const bullBitcoin = store.bullBitcoin ? JSON.parse(store.bullBitcoin) : null
if(!store) {
console.log('no store')
res.sendStatus(404)
return
}
// fetch invoice details from btcpayserver
const invoice = await fetchInvoice(req.body.storeId, req.body.invoiceId)
if(!invoice) {
console.log('no invoice')
res.sendStatus(404)
return
}
// we only care about settled invoices
if(invoice.status !== "Settled") {
console.log('invoice not settled')
res.sendStatus(200)
return
}
// fetch invoice payments from btcpayserver
const payments = await fetchInvoicePayments(req.body.storeId, req.body.invoiceId)
// calculate the total BTC paid on the invoice
let btcTotal = 0
payments.forEach(el => {
// we only deal with BTC in this script
if(el.cryptoCode == "BTC") {
el.payments.forEach(el2 => {
btcTotal += parseFloat(el2.value)
})
}
})
// calculate the btc total in milli-satoshis
let milliSatAmount = btcTotal * 100000000 * 1000
// deduct the store's fee from the total we will pay out
milliSatAmount = Math.round(milliSatAmount * store.rate)
// round to the nearest full mill-satoshi
milliSatAmount = Math.round(milliSatAmount / 1000) * 1000
// the minimum is 1 satoshi, if less than that, round up to 1
if(milliSatAmount < 1000) {
milliSatAmount = 1000
}
console.log('milliSatAmount to pay out', milliSatAmount)
const feeRetainedMilliSatoshis = Math.round((btcTotal * 100000000 * 1000) - milliSatAmount)
console.log('fee we retain', feeRetainedMilliSatoshis)
let tipMilliSatAmount = 0
let tipUsernames = []
const appId = req.body.metadata?.orderUrl?.includes('/apps/') ? req.body.metadata.orderUrl.split('/apps/')[1]?.split('/pos')[0] || null : null
if(appId) {
tipUsernames = await getTipsByAppId(db, appId)
} else {
tipUsernames = await getTips(db, store.id)
}
if(invoice.metadata && invoice.metadata.posData && invoice.metadata.posData.tip && tipUsernames && tipUsernames.length) {
const tipAmount = parseFloat((typeof invoice.metadata.posData.tip === 'string' ? invoice.metadata.posData.tip.replaceAll(',', '') : invoice.metadata.posData.tip))
const subtotal = parseFloat((typeof invoice.metadata.posData.subTotal === 'string' ? invoice.metadata.posData.subTotal.replaceAll(',', '') : invoice.metadata.posData.subTotal))
const fullTotal = parseFloat((typeof invoice.metadata.posData.total === 'string' ? invoice.metadata.posData.total.replaceAll(',', '') : invoice.metadata.posData.total))
let tipPercent = 0
if(tipAmount > subtotal) {
tipPercent = tipAmount / fullTotal
} else {
tipPercent = tipAmount / subtotal
}
tipMilliSatAmount = Math.round((milliSatAmount * tipPercent) / 1000) * 1000
console.log('there was a tip!', tipMilliSatAmount)
milliSatAmount -= tipMilliSatAmount
console.log('new payout amount to business owner', milliSatAmount)
}
if(bullBitcoin && bullBitcoin.percent && bullBitcoin.recipientId && bullBitcoin.token) {
console.log('we have a bullbitcoin account!')
const milliSatsToConvertToFiat = Math.round((milliSatAmount * (bullBitcoin.percent / 100)) / 1000) * 1000
console.log('milliSatsToConvertToFiat', milliSatsToConvertToFiat)
try {
const bullBitcoinInvoiceToPay = await fetchBullBitcoinOrder(bullBitcoin.token, bullBitcoin.recipientId, milliSatsToConvertToFiat, req.body.invoiceId)
if(bullBitcoinInvoiceToPay) {
console.log('bullBitcoinInvoiceToPay', bullBitcoinInvoiceToPay)
const bbLnInvoice = await payLnInvoice(lnd, bullBitcoinInvoiceToPay)
if(bbLnInvoice && bbLnInvoice.is_confirmed) {
milliSatAmount -= milliSatsToConvertToFiat
console.log('bullBitcoin invoice paid', milliSatsToConvertToFiat, bullBitcoinInvoiceToPay)
}
}
} catch(e) {
console.log('error creating bullbitcoin order', e)
}
}
console.log('paying business owner', store.bitcoinJungleUsername, milliSatAmount)
const ownerLnInvoice = await payLnurl(store.bitcoinJungleUsername, milliSatAmount, req.body.invoiceId)
if(ownerLnInvoice) {
// we've now forwarded the payment, mark it as such in the db
await setInvoiceProcessed(db, req.body.storeId, req.body.invoiceId)
if(ownerLnInvoice.id) {
// store a record of the payment in the db
await addPayment(db, ownerLnInvoice.id, req.body.storeId, req.body.invoiceId, req.body.timestamp, feeRetainedMilliSatoshis)
}
if(tipMilliSatAmount > 0) {
const perUserTipMilliSatAmount = Math.floor( (tipMilliSatAmount / tipUsernames.length) / 1000 ) * 1000
let tipLnInvoice, tipUsername
for (var i = tipUsernames.length - 1; i >= 0; i--) {
tipUsername = tipUsernames[i].bitcoinJungleUsername
console.log('paying out tip to ', tipUsername, perUserTipMilliSatAmount)
tipLnInvoice = await payLnurl(tipUsername, perUserTipMilliSatAmount, req.body.invoiceId)
if(tipLnInvoice) {
// store a record of the payment in the db
await addTipPayment(db, tipLnInvoice.id, req.body.storeId, req.body.invoiceId, req.body.timestamp, tipUsername, perUserTipMilliSatAmount)
}
}
}
// send a text message to the store owner
if(req.body.metadata.buyerEmail) {
const buyerPhone = req.body.metadata.buyerEmail.split("@")[0]
if(buyerPhone) {
try {
await twilioClient.messages.create({
to: `${buyerPhone}`,
from: twilioPhoneNumber,
body: `Se ha recibido y enviado un pago de Foood App al monto de ${invoice.amount} ${invoice.currency} a su cuenta bancaria por SINPE.`
})
} catch(e) {
console.log('error sending text message', e)
}
}
}
console.log('payment succeded, marked as processed, all done')
// we're done!
res.sendStatus(200)
return
}
// the invoice didn't process fully :(
console.log('error occurred with lnInvoice')
res.sendStatus(404)
return
})
const fetchBullBitcoinOrder = async (token, recipientId, milliSatAmount, invoiceId) => {
const amountSats = Math.round(parseInt(milliSatAmount, 10) / 1000)
let outPaymentProcessor = null
const headers = {
'content-type': 'application/json; charset=utf-8',
'Authorization': 'Bearer ' + token,
};
const recipientBody = JSON.stringify({
jsonrpc: "2.0",
id: "654",
method: "listMyRecipients",
params: {
paginator: {
pageSize: 100,
},
}
})
try {
const response = await fetch(`${bullBitcoinBaseUrl}/api-recipients`, {
method: 'POST',
headers: headers,
body: recipientBody,
});
const data = await response.json();
if(data && data.result && data.result.elements) {
const recipients = data.result.elements
const myRecipient = recipients.find(el => el.recipientId === recipientId)
if(myRecipient) {
if(myRecipient.recipientType === "IBAN_CR") {
if(myRecipient.currency === "CRC") {
outPaymentProcessor = "OUT_CRC_RDV_IBAN"
} else if(myRecipient.currency === "USD") {
outPaymentProcessor = "OUT_USD_RDV_IBAN"
} else {
console.log('unsupported currency', myRecipient.currency)
return null
}
} else if(myRecipient.recipientType === "SINPE_MOVIL") {
outPaymentProcessor = "OUT_CRC_RDV_SINPE"
} else {
console.log('unsupported recipient type', myRecipient.recipientType)
return null
}
} else {
console.log('error locating bullbitcoin recipient', error)
return null
}
} else {
console.log('recipientsData', data)
return null
}
} catch (error) {
console.log('error locating bullbitcoin recipient', error)
return null
}
const body = JSON.stringify({
jsonrpc: "2.0",
id: "654",
method: "createMyOrder",
params: {
amount: amountSats / 100_000_000,
isInAmountFixed: true,
inPaymentProcessor: "IN_LN",
outPaymentProcessor: outPaymentProcessor,
outRecipientId: recipientId,
outTransactionData: { /* text: invoiceId.substr(0, 14) */ }
}
});
console.log('create order body', body)
try {
const response = await fetch(`${bullBitcoinBaseUrl}/api-orders`, {
method: 'POST',
headers: headers,
body: body,
});
const data = await response.json();
console.log('create order res', data)
if (data.result && data.result.element && data.result.element.inTransaction) {
const invoiceData = data.result.element.inTransaction.transactionPaymentProcessorData;
const bolt11Invoice = invoiceData.find(item => item.paymentProcessorData.paymentProcessorDataCode === 'bolt11');
return bolt11Invoice ? bolt11Invoice.value : null;
}
throw new Error('Invoice not found in response');
} catch (error) {
console.error('Error creating BullBitcoin order:', error);
return null;
}
}
app.post('/beds24', async (req, res) => {
console.log(req.body)
// we only care about settled invoices
if(req.body.type !== "InvoiceSettled") {
console.log('not invoice settled type')
res.sendStatus(200)
return
}
// fetch invoice details from btcpayserver
const invoice = await fetchInvoice(req.body.storeId, req.body.invoiceId)
if(!invoice) {
console.log('no invoice')
res.sendStatus(404)
return
}
// we only care about settled invoices
if(invoice.status !== "Settled") {
console.log('invoice not settled')
res.sendStatus(200)
return
}
if(!invoice.metadata || !invoice.metadata.orderId) {
console.log('no orderId')
res.sendStatus(200)
return
}
console.log('invoice', invoice)
const params = new URLSearchParams();
params.append('key', webhookSecret);
params.append('bookid', invoice.metadata.orderId)
params.append('amount', invoice.amount)
params.append('description', 'BTCPayServer Payment Invoice ID' + invoice.id)
params.append('payment_status', 'Received')
params.append('txnid', invoice.id)
const response = await fetch('https://api.beds24.com/custompaymentgateway/notify.php', {method: 'POST', body: params});
console.log(response);
// we're done!
res.sendStatus(200)
return
})
app.post('/addStore', async (req, res) => {
// input vars
const apiKey = req.body.apiKey
const storeName = req.body.storeName
const storeOwnerEmail = (req.body.storeOwnerEmail ? req.body.storeOwnerEmail.trim() : null)
const defaultCurrency = req.body.defaultCurrency
const defaultLanguage = req.body.defaultLanguage
const rate = req.body.rate
const bitcoinJungleUsername = req.body.bitcoinJungleUsername
const tipSplit = req.body.tipSplit
const bullBitcoin = req.body.bullBitcoin
if(bullBitcoin) {
console.log('bullBitcoin', bullBitcoin)
}
// these are needed but not user editable inputs
const paymentTolerance = 1
const defaultPaymentMethod = "BTC_LightningNetwork"
const customLogo = defaultLogoUri
const customCSS = defaultCssUri
const webhookUrl = btcpayBaseUri + "forward"
// do the validation
if(!apiKey) {
res.status(400).send({success: false, error: true, message: "apiKey is required"})
return
}
if(apiKey !== internalKey) {
res.status(400).send({success: false, error: true, message: "apiKey is incorrect"})
return
}
if(!storeName) {
res.status(400).send({success: false, error: true, message: "storeName is required"})
return
}
if(!storeOwnerEmail) {
res.status(400).send({success: false, error: true, message: "storeOwnerEmail is required"})
return
}
if(!defaultCurrency) {
res.status(400).send({success: false, error: true, message: "defaultCurrency is required"})
return
}
if(!defaultLanguage) {
res.status(400).send({success: false, error: true, message: "defaultLanguage is required"})
return
}
if(!rate) {
res.status(400).send({success: false, error: true, message: "rate is required"})
return
}
if(!bitcoinJungleUsername) {
res.status(400).send({success: false, error: true, message: "bitcoinJungleUsername is required"})
return
}
if(tipSplit && tipSplit.length) {
for (var i = tipSplit.length - 1; i >= 0; i--) {
if(tipSplit[i] != "") {
const usernameExists = await fetchGetBitcoinJungleUsername(tipSplit[i])
if(!usernameExists) {
res.status(400).send({success: false, error: true, message: tipSplit[i] + " is not a valid username"})
return
}
}
}
}
// create store via api
const store = await fetchCreateStore({
storeName,
storeOwnerEmail,
defaultCurrency,
defaultLanguage,
paymentTolerance,
defaultPaymentMethod,
customLogo,
customCSS,
})
if(!store.id) {
res.status(400).send({success: false, error: true, message: "error happened creating store in API"})
return
}
// create user via api
let user = await fetchCreateUser({
storeOwnerEmail,
})
if(!user.id) {
user = await fetchGetUser(storeOwnerEmail)
if(!user.id) {
res.status(400).send({success: false, error: true, message: "error happened creating user in API"})
return
}
}
// attach user to store via api
const userStore = await fetchCreateUserStore({
storeId: store.id,
userId: user.id,
})
// attach webhook to store via api
const webhook = await fetchCreateWebhook({
storeId: store.id,
url: webhookUrl,
secret: webhookSecret,
authorizedEvents: {
everything: false,
specificEvents: [
"InvoiceSettled",
],
},
})
if(!webhook.id) {
res.status(400).send({success: false, error: true, message: "error happened creating webhook in API"})
return
}
// create LN payment method via API
const lnPaymentMethod = await fetchCreateLnPaymentMethod({
storeId: store.id,
cryptoCode: "BTC",
connectionString: "Internal Node",
enabled: true,
})
const lnUrlPaymentMethod = await fetchCreateLnUrlPaymentMethod({
storeId: store.id,
cryptoCode: "BTC",
enabled: true,
useBech32Scheme: true,
lud12Enabled: false,
})
// create on-chain payment method via API
const onChainPaymentMethod = await fetchCreateOnChainPaymentMethod({
storeId: store.id,
cryptoCode: "BTC",
enabled: true,
derivationScheme: onChainZpub,
})
// add store to our internal db
const newStore = await addStore(db, store.id, rate, bitcoinJungleUsername, bullBitcoin)
if(!newStore) {
console.log('db error', newStore)
res.status(500).send({success: false, error: true, message: "error writing to db"})
return
}
// update store rate script for CRC support
const rateScript = `BTC_CRC = bitcoinjungle(BTC_CRC);\nBTC_USD = bitcoinjungle(BTC_USD);`
const btcPayServerRate = await updateBtcPayServerRate(store.id, rateScript)
// customize the Data we need for the App
let btcPayServerAppData = {
appName: storeName,
title: storeName,
currency: defaultCurrency.toUpperCase(),
defaultView: "Light",
showCustomAmount: true,
showDiscount: false,
enableTips: true,
requiresRefundEmail: false,
checkoutType: "V2",
}
// create the App record in the btcpayserver db
const btcPayServerApp = await createBtcPayServerApp(store.id, btcPayServerAppData)
const storeApp = await setStoreAppId(db, store.id, btcPayServerApp.id)
if(tipSplit && tipSplit.length) {
const internalStore = await getStore(db, store.id)
for (var i = tipSplit.length - 1; i >= 0; i--) {
if(tipSplit[i] !== "") {
await setTip(db, internalStore.id, tipSplit[i])
}
}
}
const emailSent = await sendEmail(storeOwnerEmail)
// we're done!
res.status(200).send({success: true, error: false, btcPayServerAppId: btcPayServerApp.id})
return
})
app.get('/addStore', (req, res) => {
res.sendFile('newStore/index.html', {root: basePath})
})
app.get('/getTipConfiguration', async (req, res) => {
const appId = req.query.appId
if(!appId) {
res.status(400).send({success: false, error: true, message: "appId is required"})
return
}
const data = await getTipsByAppId(db, appId)
res.status(200).send({success: true, error: false, data: data})
})
app.post('/setTipSplit', async (req, res) => {
const appId = req.body.appId
const tipUsernames = req.body.tipUsernames
if(!appId) {
res.status(400).send({success: false, error: true, message: "appId is required"})
return
}
if(!tipUsernames || !tipUsernames.length) {
res.status(400).send({success: false, error: true, message: "tipUsernames is a required array"})
return
}
const store = await getStoreByAppId(db, appId)
if(!store) {
res.status(404).send({success: false, error: true, message: "store not found"})
return
}
if(tipUsernames && tipUsernames.length) {
for (var i = tipUsernames.length - 1; i >= 0; i--) {
const usernameExists = await fetchGetBitcoinJungleUsername(tipUsernames[i])
if(!usernameExists) {
res.status(400).send({success: false, error: true, message: tipUsernames[i] + " is not a valid username"})
return
}
}
}
await clearTips(db, store.id)
for (var i = tipUsernames.length - 1; i >= 0; i--) {
await setTip(db, store.id, tipUsernames[i])
}
const data = await getTipsByAppId(db, appId)
res.status(200).send({success: true, error: false, data: data})
return
})
app.get('/tipLnurl/:appId', async (req, res) => {
const appId = req.params.appId
const amount = req.query.amount
const comment = req.query.comment
if(!appId || !appId.length) {
return res.status(200).send({
status: "ERROR",
reason: "Invalid LNURL code",
})
}
const app = await fetchGetApp(appId)
if(!app) {
return res.status(200).send({
status: "ERROR",
reason: "App not found",
})
}
const internalStore = await getStoreByAppId(db, appId)
if(!internalStore) {
return res.status(200).send({
status: "ERROR",
reason: "Store not found",
})
}
const store = await fetchGetStore(internalStore.storeId)
if(!store) {
return res.status(200).send({
status: "ERROR",
reason: "Store not found",
})
}
if(amount) {
const amountSats = Math.round(parseInt(amount, 10) / 1000)
if ((amountSats * 1000).toString() !== amount) {
return res.status(200).send({
status: "ERROR",
reason: "Millisatoshi amount is not supported, please send a value in full sats.",
})
}
const invoice = await fetchCreateInvoice(app.storeId, amountSats, comment)
if(!invoice) {
return res.status(200).send({
status: "ERROR",
reason: "Error creating invoice.",
})
}
const invoicePayments = await fetchInvoicePayments(app.storeId, invoice.id)
const lnurlPaymentMethod = invoicePayments.find((el) => el.paymentMethod === 'BTC-LNURLPAY')
if(!lnurlPaymentMethod) {
return res.status(200).send({
status: "ERROR",
reason: "Error finding invoice.",
})
}
const lightningInvoice = await fetchBtcPayServerLnUrl(invoice.id, Math.round(amountSats * 1000))
if(!lightningInvoice) {
return res.status(200).send({
status: "ERROR",
reason: "Error loading invoice.",
})
}
return res.status(200).send({
pr: lightningInvoice.pr,
routes: [],
successAction: {
tag: "message",
message: "Thank you for the tip!",
}
})
}
return res.status(200).send({
callback: `https://btcpayserver.bitcoinjungle.app/tipLnurl/${appId}`,
metadata: JSON.stringify([
["text/plain", `Paid to ${store.name}`]
]),
tag: "payRequest",
minSendable: 1000,
maxSendable: 612000000000,
commentAllowed: 2000
})
})
app.get('/updateStoreAppIds', async (req, res) => {
const stores = await getAllStores(db)
let store, app
for (var i = stores.length - 1; i >= 0; i--) {
store = stores[i]
console.log('store', store.storeId, store.bitcoinJungleUsername)
const apps = await fetchGetApps(store.storeId)
for(var y = apps.length - 1; y >= 0; y--) {
app = apps[y]
console.log('app', app.id)
await setStoreAppId(db, store.storeId, app.id)
}
}
res.status(200).send('ok')
return
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
app.get('/enableLnurl', async (req, res) => {
const stores = await fetchGetAllStores()
let store, lnUrlPaymentMethod
for (var i = stores.length - 1; i >= 0; i--) {
store = stores[i]
console.log('store', store.id)
lnUrlPaymentMethod = await fetchCreateLnUrlPaymentMethod({
storeId: store.id,
cryptoCode: "BTC",
enabled: true,
useBech32Scheme: true,
lud12Enabled: false,
})
console.log('lnUrlPaymentMethod', lnUrlPaymentMethod)
}
res.status(200).send('ok')
return
})
app.get('/findStores', async (req, res) => {
const userId = req.query.userId
const date = new Date().getUTCFullYear() + '-' + (new Date().getUTCMonth() + 1) + '-' + new Date().getUTCDate()
const hash = req.query.hash
if(!userId || !hash || !date) {
res.status(400).send({success: false, error: true, message: "userId, hash and date are required"})
return
}
const hashedUserId = hmacSHA256([userId, date], webhookSecret)
if(hashedUserId !== hash) {
console.log('invalid hash', hashedUserId, hash)
res.status(400).send({success: false, error: true, message: "Invalid hash"})
return
}
const stores = await findStoresByBbUserId(db, userId)
let output = []
const btcpayStores = await fetchGetAllStores()
if(stores && stores.length) {
output = stores.map((el) => {
const bb = JSON.parse(el.bullBitcoin)
const btcpayStore = btcpayStores.find((store) => store.id === el.storeId)
return {
id: el.id,
storeId: el.storeId,
rate: el.rate,
bitcoinJungleUsername: el.bitcoinJungleUsername,
appId: el.appId,
btcpayStore: btcpayStore,
bullBitcoin: JSON.stringify({
percent: bb.percent,
recipientId: bb.recipientId,
userId: bb.userId,
})
}
})
}
res.status(200).send({success: true, error: false, data: output})
return
})
app.get('/foood-app-stores', async (req, res) => {
const userId = fooodAppUserId
const stores = await findStoresByBbUserId(db, userId)
let output = []
const btcpayStores = await fetchGetAllStores()
if(stores && stores.length) {
output = stores.map((el) => {
const bb = JSON.parse(el.bullBitcoin)
const btcpayStore = btcpayStores.find((store) => store.id === el.storeId)
return {
id: el.id,
storeId: el.storeId,
rate: el.rate,
bitcoinJungleUsername: el.bitcoinJungleUsername,
appId: el.appId,
btcpayStore: btcpayStore,
bullBitcoin: JSON.stringify({
percent: bb.percent,
recipientId: bb.recipientId,
userId: bb.userId,
})
}
})
}
res.status(200).send({success: true, error: false, data: output})
return
})
const hmacSHA256 = (data, secret) => {
const hmac = crypto.createHmac('sha256', secret);
hmac.update(data.join('|'));
return hmac.digest('hex');
};
const sendEmail = async (storeOwnerEmail) => {
const msg = {
to: storeOwnerEmail,
from: 'noreply@bitcoinjungle.app',
subject: 'New Bitcoin Point of Sale Created',
html: 'Please visit <a href="https://btcpayserver.bitcoinjungle.app/login/forgot-password">btcpayserver.bitcoinjungle.app</a> and enter ' + storeOwnerEmail + ' to create a password and log into the Point of Sale Admin system.',
}
return sgMail.send(msg)
.then(() => {
return true
})
.catch((error) => {
console.error(error)
return false
})
}
const generateRandomString = (length) => {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for ( var i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}