lnbits-legend/lnbits/wallets/lnpay.py

65 lines
2.3 KiB
Python
Raw Normal View History

from os import getenv
from typing import Optional, Dict
2020-01-18 10:24:22 +00:00
from requests import get, post
from .base import InvoiceResponse, PaymentResponse, PaymentStatus, Wallet
2020-01-18 10:24:22 +00:00
class LNPayWallet(Wallet):
"""https://docs.lnpay.co/"""
def __init__(self):
endpoint = getenv("LNPAY_API_ENDPOINT")
2020-01-18 10:24:22 +00:00
self.endpoint = endpoint[:-1] if endpoint.endswith("/") else endpoint
self.auth_admin = getenv("LNPAY_ADMIN_KEY")
self.auth_invoice = getenv("LNPAY_INVOICE_KEY")
self.auth_read = getenv("LNPAY_READ_KEY")
self.auth_api = {"X-Api-Key": getenv("LNPAY_API_KEY")}
2020-01-18 10:24:22 +00:00
def create_invoice(
self, amount: int, memo: Optional[str] = None, description_hash: Optional[bytes] = None
) -> InvoiceResponse:
data: Dict = {"num_satoshis": f"{amount}"}
if description_hash:
data["description_hash"] = description_hash.hex()
else:
data["memo"] = memo or ""
2020-09-03 23:02:15 +02:00
r = post(
url=f"{self.endpoint}/user/wallet/{self.auth_invoice}/invoice",
headers=self.auth_api,
json=data,
)
2020-08-28 23:03:12 -03:00
ok, checking_id, payment_request, error_message = r.status_code == 201, None, None, r.text
if ok:
2020-01-18 10:24:22 +00:00
data = r.json()
checking_id, payment_request = data["id"], data["payment_request"]
2020-01-18 10:24:22 +00:00
return InvoiceResponse(ok, checking_id, payment_request, error_message)
2020-01-18 10:24:22 +00:00
def pay_invoice(self, bolt11: str) -> PaymentResponse:
r = post(
url=f"{self.endpoint}/user/wallet/{self.auth_admin}/withdraw",
headers=self.auth_api,
json={"payment_request": bolt11},
)
ok, checking_id, fee_msat, error_message = r.status_code == 201, None, 0, None
if ok:
checking_id = r.json()["lnTx"]["id"]
2020-01-18 10:24:22 +00:00
return PaymentResponse(ok, checking_id, fee_msat, error_message)
2020-01-18 10:24:22 +00:00
def get_invoice_status(self, checking_id: str) -> PaymentStatus:
return self.get_payment_status(checking_id)
2020-01-18 10:24:22 +00:00
def get_payment_status(self, checking_id: str) -> PaymentStatus:
r = get(url=f"{self.endpoint}/user/lntx/{checking_id}", headers=self.auth_api)
2020-01-18 10:24:22 +00:00
if not r.ok:
return PaymentStatus(None)
2020-01-18 10:24:22 +00:00
statuses = {0: None, 1: True, -1: False}
return PaymentStatus(statuses[r.json()["settled"]])