Created
August 18, 2019 16:42
-
-
Save whiteyhat/391f9e03d7bebd8fba4d88b8aaace1ae to your computer and use it in GitHub Desktop.
Subscribe to invoices using EXPRESS + SERVERLESS (Lambda)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import LndService from "./services/LndService"; | |
import paymentsService from "./services/paymentsService"; | |
const { subscribeToInvoices } = require("ln-service"); | |
const lnService = require('ln-service'); | |
class Subscriptions { | |
public initWS = async () => { | |
// Since BTCPay Server closes WS every 90 seconds it must be looped | |
try { | |
const {lnd}= lnService.authenticatedLndGrpc({ | |
socket: LndService.getNodeAddress(), | |
macaroon: process.env.LND_MACAROON | |
// cert: NOT NEEDED AS WORKING UNDER BTCPAY SERVER GRPC SUITES | |
}); | |
let websocket : any; | |
websocket = subscribeToInvoices({lnd}) | |
websocket.on('error', async err => { | |
// recursive call to reconnec on error as BTCPAY closes sockets connection every 90 secs | |
try { | |
await this.initWS() | |
} catch (err) { | |
console.log(err) | |
} | |
}) | |
websocket.on("invoice_updated", async (data: any) => { | |
console.log("Subscribed") | |
// If invoice is paid | |
if (data.is_confirmed) { | |
try { | |
const invoiceData = await paymentsService.getPaymentForViews( | |
data.id | |
); | |
if (invoiceData.Count && invoiceData.Items) { | |
const invoice = invoiceData[0]; | |
await paymentsService.payInvoice( | |
invoice.invoiceId, | |
invoice.keyId | |
); | |
console.log("Invoice paid: " + invoice.invoiceId); | |
} | |
} catch (error) { | |
console.error( | |
new Date().toLocaleString() +": " + error | |
); | |
} | |
} | |
}); | |
} catch (error) { | |
console.error(new Date().toLocaleString() + ": " + error); | |
} | |
}; | |
} | |
export default new Subscriptions(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment