Skip to content

Instantly share code, notes, and snippets.

@whiteyhat
Created August 18, 2019 16:42
Show Gist options
  • Save whiteyhat/391f9e03d7bebd8fba4d88b8aaace1ae to your computer and use it in GitHub Desktop.
Save whiteyhat/391f9e03d7bebd8fba4d88b8aaace1ae to your computer and use it in GitHub Desktop.
Subscribe to invoices using EXPRESS + SERVERLESS (Lambda)
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