Files
timmy-tower/artifacts/api-server/src/lib/lnbits.ts

88 lines
2.0 KiB
TypeScript
Raw Normal View History

const LNBITS_URL = process.env.LNBITS_URL;
const LNBITS_API_KEY = process.env.LNBITS_API_KEY;
function getBaseUrl(): string {
if (!LNBITS_URL) {
throw new Error("LNBITS_URL environment variable is not set");
}
return LNBITS_URL.replace(/\/$/, "");
}
function getHeaders(): Record<string, string> {
if (!LNBITS_API_KEY) {
throw new Error("LNBITS_API_KEY environment variable is not set");
}
return {
"Content-Type": "application/json",
"X-Api-Key": LNBITS_API_KEY,
};
}
export interface LNbitsInvoice {
paymentHash: string;
paymentRequest: string;
}
export interface LNbitsInvoiceStatus {
paid: boolean;
paidAt?: Date;
}
export async function createInvoice(
amountSats: number,
memo: string,
): Promise<LNbitsInvoice> {
const baseUrl = getBaseUrl();
const response = await fetch(`${baseUrl}/api/v1/payments`, {
method: "POST",
headers: getHeaders(),
body: JSON.stringify({
out: false,
amount: amountSats,
memo,
}),
});
if (!response.ok) {
const body = await response.text();
throw new Error(`LNbits createInvoice failed (${response.status}): ${body}`);
}
const data = (await response.json()) as {
payment_hash: string;
payment_request: string;
};
return {
paymentHash: data.payment_hash,
paymentRequest: data.payment_request,
};
}
export async function checkInvoicePaid(
paymentHash: string,
): Promise<LNbitsInvoiceStatus> {
const baseUrl = getBaseUrl();
const response = await fetch(`${baseUrl}/api/v1/payments/${paymentHash}`, {
method: "GET",
headers: getHeaders(),
});
if (!response.ok) {
const body = await response.text();
throw new Error(`LNbits checkInvoice failed (${response.status}): ${body}`);
}
const data = (await response.json()) as {
paid: boolean;
details?: { time?: number };
};
return {
paid: data.paid,
paidAt: data.paid && data.details?.time
? new Date(data.details.time * 1000)
: undefined,
};
}