extra fields on apipayments + index payments by payment_hash

This commit is contained in:
fiatjaf
2020-09-02 11:10:48 -03:00
parent c96b22664e
commit bf3c44b3c4
24 changed files with 360 additions and 349 deletions
+31 -19
View File
@@ -1,4 +1,4 @@
from typing import List, Optional
from typing import List, Optional, Dict
from uuid import uuid4
from lnbits.db import open_db
@@ -136,18 +136,18 @@ def get_wallet_for_key(key: str, key_type: str = "invoice") -> Optional[Wallet]:
# ---------------
def get_wallet_payment(wallet_id: str, checking_id: str) -> Optional[Payment]:
def get_wallet_payment(wallet_id: str, payment_hash: str) -> Optional[Payment]:
with open_db() as db:
row = db.fetchone(
"""
SELECT id as checking_id, amount, fee, pending, memo, time
FROM apipayment
WHERE wallet = ? AND id = ?
SELECT *
FROM apipayments
WHERE wallet = ? AND hash = ?
""",
(wallet_id, checking_id),
(wallet_id, payment_hash),
)
return Payment(**row) if row else None
return Payment.from_row(row) if row else None
def get_wallet_payments(
@@ -179,7 +179,7 @@ def get_wallet_payments(
with open_db() as db:
rows = db.fetchall(
f"""
SELECT id as checking_id, amount, fee, pending, memo, time
SELECT *
FROM apipayments
WHERE wallet = ? {clause}
ORDER BY time DESC
@@ -187,7 +187,7 @@ def get_wallet_payments(
(wallet_id,),
)
return [Payment(**row) for row in rows]
return [Payment.from_row(row) for row in rows]
def delete_wallet_payments_expired(wallet_id: str, *, seconds: int = 86400) -> None:
@@ -195,7 +195,7 @@ def delete_wallet_payments_expired(wallet_id: str, *, seconds: int = 86400) -> N
db.execute(
"""
DELETE
FROM apipayment WHERE wallet = ? AND pending = 1 AND time < strftime('%s', 'now') - ?
FROM apipayments WHERE wallet = ? AND pending = 1 AND time < strftime('%s', 'now') - ?
""",
(wallet_id, seconds),
)
@@ -206,18 +206,30 @@ def delete_wallet_payments_expired(wallet_id: str, *, seconds: int = 86400) -> N
def create_payment(
*, wallet_id: str, checking_id: str, payment_hash: str, amount: int, memo: str, fee: int = 0, pending: bool = True
*,
wallet_id: str,
checking_id: str,
payment_request: str,
payment_hash: str,
amount: int,
memo: str,
fee: int = 0,
preimage: Optional[str] = None,
pending: bool = True,
extra: Optional[Dict] = None,
) -> Payment:
with open_db() as db:
db.execute(
"""
INSERT INTO apipayment (wallet, id, payment_hash, amount, pending, memo, fee)
VALUES (?, ?, ?, ?, ?, ?, ?)
INSERT INTO apipayments
(wallet, checking_id, bolt11, hash, preimage,
amount, pending, memo, fee, extra)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(wallet_id, checking_id, payment_hash, amount, int(pending), memo, fee),
(wallet_id, checking_id, payment_request, payment_hash, preimage, amount, int(pending), memo, fee, extra),
)
new_payment = get_wallet_payment(wallet_id, checking_id)
new_payment = get_wallet_payment(wallet_id, payment_hash)
assert new_payment, "Newly created payment couldn't be retrieved"
return new_payment
@@ -225,18 +237,18 @@ def create_payment(
def update_payment_status(checking_id: str, pending: bool) -> None:
with open_db() as db:
db.execute("UPDATE apipayment SET pending = ? WHERE id = ?", (int(pending), checking_id,))
db.execute("UPDATE apipayments SET pending = ? WHERE checking_id = ?", (int(pending), checking_id,))
def delete_payment(checking_id: str) -> None:
with open_db() as db:
db.execute("DELETE FROM apipayment WHERE id = ?", (checking_id,))
db.execute("DELETE FROM apipayments WHERE checking_id = ?", (checking_id,))
def check_internal(payment_hash: str) -> None:
with open_db() as db:
row = db.fetchone("SELECT * FROM apipayment WHERE payment_hash = ?", (payment_hash,))
row = db.fetchone("SELECT checking_id FROM apipayments WHERE hash = ?", (payment_hash,))
if not row:
return False
else:
return row['id']
return row["checking_id"]
+12 -64
View File
@@ -69,74 +69,22 @@ def m001_initial(db):
GROUP BY wallet;
"""
)
db.execute("DROP VIEW balances")
db.execute(
"""
CREATE VIEW IF NOT EXISTS balances AS
SELECT wallet, COALESCE(SUM(s), 0) AS balance FROM (
SELECT wallet, SUM(amount) AS s -- incoming
FROM apipayment
WHERE amount > 0 AND pending = 0 -- don't sum pending
GROUP BY wallet
UNION ALL
SELECT wallet, SUM(amount + fee) AS s -- outgoing, sum fees
FROM apipayment
WHERE amount < 0 -- do sum pending
GROUP BY wallet
)
GROUP BY wallet;
def m002_add_fields_to_apipayments(db):
"""
)
def m002_changed(db):
db.execute(
"""
CREATE TABLE IF NOT EXISTS apipayment (
id TEXT NOT NULL,
payment_hash TEXT NOT NULL,
amount INTEGER NOT NULL,
fee INTEGER NOT NULL DEFAULT 0,
wallet TEXT NOT NULL,
pending BOOLEAN NOT NULL,
memo TEXT,
time TIMESTAMP NOT NULL DEFAULT (strftime('%s', 'now')),
UNIQUE (wallet, id)
);
Adding fields to apipayments for better accounting,
and renaming payhash to checking_id since that is what it really is.
"""
)
db.execute("ALTER TABLE apipayments RENAME COLUMN payhash TO checking_id")
db.execute("ALTER TABLE apipayments ADD COLUMN hash TEXT")
db.execute("CREATE INDEX by_hash ON apipayments (hash)")
db.execute("ALTER TABLE apipayments ADD COLUMN preimage TEXT")
db.execute("ALTER TABLE apipayments ADD COLUMN bolt11 TEXT")
db.execute("ALTER TABLE apipayments ADD COLUMN extra TEXT")
for row in [list(row) for row in db.fetchall("SELECT * FROM apipayments")]:
db.execute(
"""
INSERT INTO apipayment (
id,
payment_hash,
amount,
fee,
wallet,
pending,
memo,
time
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
""",
(
row[0],
"oldinvoice",
row[1],
row[2],
row[3],
row[4],
row[5],
row[6],
),
)
db.execute("DROP TABLE apipayments")
def migrate():
with open_db() as db:
m001_initial(db)
m002_changed(db)
m002_add_fields_to_apipayments(db)
+28 -3
View File
@@ -1,4 +1,6 @@
from typing import List, NamedTuple, Optional
import json
from typing import List, NamedTuple, Optional, Dict
from sqlite3 import Row
class User(NamedTuple):
@@ -29,10 +31,10 @@ class Wallet(NamedTuple):
def balance(self) -> int:
return self.balance_msat // 1000
def get_payment(self, checking_id: str) -> Optional["Payment"]:
def get_payment(self, payment_hash: str) -> Optional["Payment"]:
from .crud import get_wallet_payment
return get_wallet_payment(self.id, checking_id)
return get_wallet_payment(self.id, payment_hash)
def get_payments(
self, *, complete: bool = True, pending: bool = False, outgoing: bool = True, incoming: bool = True
@@ -54,6 +56,29 @@ class Payment(NamedTuple):
fee: int
memo: str
time: int
bolt11: str
preimage: str
payment_hash: str
extra: Dict
@classmethod
def from_row(cls, row: Row):
return cls(
checking_id=row["checking_id"],
payment_hash=row["hash"],
bolt11=row["bolt11"],
preimage=row["preimage"],
extra=json.loads(row["extra"] or "{}"),
pending=row["pending"],
amount=row["amount"],
fee=row["fee"],
memo=row["memo"],
time=row["time"],
)
@property
def tag(self) -> Optional[str]:
return self.extra.get("tag")
@property
def msat(self) -> int:
+60 -50
View File
@@ -1,14 +1,20 @@
from typing import Optional, Tuple
from typing import Optional, Tuple, Dict
from lnbits.bolt11 import decode as bolt11_decode # type: ignore
from lnbits import bolt11
from lnbits.helpers import urlsafe_short_hash
from lnbits.settings import WALLET
from .crud import get_wallet, create_payment, delete_payment, check_internal, update_payment_status
from .crud import get_wallet, create_payment, delete_payment, check_internal, update_payment_status, get_wallet_payment
def create_invoice(*, wallet_id: str, amount: int, memo: str, description_hash: bytes = None) -> Tuple[str, str]:
def create_invoice(
*,
wallet_id: str,
amount: int,
memo: Optional[str] = None,
description_hash: Optional[bytes] = None,
extra: Optional[Dict] = None,
) -> Tuple[str, str]:
try:
ok, checking_id, payment_request, error_message = WALLET.create_invoice(
amount=amount, memo=memo, description_hash=description_hash
@@ -18,77 +24,81 @@ def create_invoice(*, wallet_id: str, amount: int, memo: str, description_hash:
if not ok:
raise Exception(error_message or "Unexpected backend error.")
invoice = bolt11_decode(payment_request)
invoice = bolt11.decode(payment_request)
amount_msat = amount * 1000
create_payment(wallet_id=wallet_id, checking_id=checking_id, payment_hash=invoice.payment_hash, amount=amount_msat, memo=memo)
create_payment(
wallet_id=wallet_id,
checking_id=checking_id,
payment_request=payment_request,
payment_hash=invoice.payment_hash,
amount=amount_msat,
memo=memo,
extra=extra,
)
return checking_id, payment_request
return invoice.payment_hash, payment_request
def pay_invoice(*, wallet_id: str, bolt11: str, max_sat: Optional[int] = None) -> str:
def pay_invoice(
*, wallet_id: str, payment_request: str, max_sat: Optional[int] = None, extra: Optional[Dict] = None
) -> str:
temp_id = f"temp_{urlsafe_short_hash()}"
try:
invoice = bolt11_decode(bolt11)
internal = check_internal(invoice.payment_hash)
invoice = bolt11.decode(payment_request)
if invoice.amount_msat == 0:
raise ValueError("Amountless invoices not supported.")
if max_sat and invoice.amount_msat > max_sat * 1000:
raise ValueError("Amount in invoice is too high.")
fee_reserve = max(1000, int(invoice.amount_msat * 0.01))
# put all parameters that don't change here
payment_kwargs = dict(
wallet_id=wallet_id,
payment_request=payment_request,
payment_hash=invoice.payment_hash,
amount=-invoice.amount_msat,
memo=invoice.description,
extra=extra,
)
if not internal:
create_payment(
wallet_id=wallet_id,
checking_id=temp_id,
payment_hash=invoice.payment_hash,
amount=-invoice.amount_msat,
fee=-fee_reserve,
memo=temp_id,
)
# check_internal() returns the checking_id of the invoice we're waiting for
internal = check_internal(invoice.payment_hash)
if internal:
# create a new payment from this wallet
create_payment(checking_id=temp_id, fee=0, pending=False, **payment_kwargs)
else:
# create a temporary payment here so we can check if
# the balance is enough in the next step
fee_reserve = max(1000, int(invoice.amount_msat * 0.01))
create_payment(checking_id=temp_id, fee=-fee_reserve, **payment_kwargs)
# do the balance check
wallet = get_wallet(wallet_id)
assert wallet, "invalid wallet id"
if wallet.balance_msat < 0:
raise PermissionError("Insufficient balance.")
if internal:
create_payment(
wallet_id=wallet_id,
checking_id=temp_id,
payment_hash=invoice.payment_hash,
amount=-invoice.amount_msat,
fee=0,
pending=False,
memo=invoice.description,
)
# mark the invoice from the other side as not pending anymore
# so the other side only has access to his new money when we are sure
# the payer has enough to deduct from
update_payment_status(checking_id=internal, pending=False)
return temp_id
ok, checking_id, fee_msat, error_message = WALLET.pay_invoice(bolt11)
if ok:
create_payment(
wallet_id=wallet_id,
checking_id=checking_id,
payment_hash=invoice.payment_hash,
amount=-invoice.amount_msat,
fee=fee_msat,
memo=invoice.description,
)
else:
# actually pay the external invoice
ok, checking_id, fee_msat, error_message = WALLET.pay_invoice(payment_request)
if ok:
create_payment(checking_id=checking_id, fee=fee_msat, **payment_kwargs)
delete_payment(temp_id)
except Exception as e:
ok, error_message = False, str(e)
delete_payment(temp_id)
if not ok:
raise Exception(error_message or "Unexpected backend error.")
return checking_id
return invoice.payment_hash
def check_payment(*, checking_id: str) -> str:
pass
def check_invoice_status(wallet_id: str, payment_hash: str) -> str:
payment = get_wallet_payment(wallet_id, payment_hash)
return WALLET.get_invoice_status(payment.checking_id)
+60 -52
View File
@@ -1,3 +1,5 @@
/* globals Vue, VueQrcodeReader, VueQrcode, Quasar, LNbits, _ */
Vue.component(VueQrcode.name, VueQrcode)
Vue.use(VueQrcodeReader)
@@ -12,10 +14,10 @@ function generateChart(canvas, payments) {
}
_.each(
payments.slice(0).sort(function (a, b) {
payments.slice(0).sort(function(a, b) {
return a.time - b.time
}),
function (tx) {
function(tx) {
txs.push({
hour: Quasar.utils.date.formatDate(tx.date, 'YYYY-MM-DDTHH:00'),
sat: tx.sat
@@ -23,17 +25,17 @@ function generateChart(canvas, payments) {
}
)
_.each(_.groupBy(txs, 'hour'), function (value, day) {
_.each(_.groupBy(txs, 'hour'), function(value, day) {
var income = _.reduce(
value,
function (memo, tx) {
function(memo, tx) {
return tx.sat >= 0 ? memo + tx.sat : memo
},
0
)
var outcome = _.reduce(
value,
function (memo, tx) {
function(memo, tx) {
return tx.sat < 0 ? memo + Math.abs(tx.sat) : memo
},
0
@@ -65,14 +67,20 @@ function generateChart(canvas, payments) {
type: 'bar',
label: 'in',
barPercentage: 0.75,
backgroundColor: window.Color('rgb(76,175,80)').alpha(0.5).rgbString() // green
backgroundColor: window
.Color('rgb(76,175,80)')
.alpha(0.5)
.rgbString() // green
},
{
data: data.outcome,
type: 'bar',
label: 'out',
barPercentage: 0.75,
backgroundColor: window.Color('rgb(233,30,99)').alpha(0.5).rgbString() // pink
backgroundColor: window
.Color('rgb(233,30,99)')
.alpha(0.5)
.rgbString() // pink
}
]
},
@@ -113,7 +121,7 @@ function generateChart(canvas, payments) {
new Vue({
el: '#vue',
mixins: [windowMixin],
data: function () {
data: function() {
return {
receive: {
show: false,
@@ -169,49 +177,49 @@ new Vue({
}
},
computed: {
filteredPayments: function () {
filteredPayments: function() {
var q = this.paymentsTable.filter
if (!q || q == '') return this.payments
return LNbits.utils.search(this.payments, q)
},
balance: function () {
balance: function() {
if (this.payments.length) {
return (
_.pluck(this.payments, 'amount').reduce(function (a, b) {
_.pluck(this.payments, 'amount').reduce(function(a, b) {
return a + b
}, 0) / 1000
)
}
return this.g.wallet.sat
},
fbalance: function () {
fbalance: function() {
return LNbits.utils.formatSat(this.balance)
},
canPay: function () {
canPay: function() {
if (!this.send.invoice) return false
return this.send.invoice.sat <= this.balance
},
pendingPaymentsExist: function () {
pendingPaymentsExist: function() {
return this.payments
? _.where(this.payments, {pending: 1}).length > 0
: false
}
},
methods: {
closeCamera: function () {
closeCamera: function() {
this.sendCamera.show = false
},
showCamera: function () {
showCamera: function() {
this.sendCamera.show = true
},
showChart: function () {
showChart: function() {
this.paymentsChart.show = true
this.$nextTick(function () {
this.$nextTick(function() {
generateChart(this.$refs.canvas, this.payments)
})
},
showReceiveDialog: function () {
showReceiveDialog: function() {
this.receive = {
show: true,
status: 'pending',
@@ -223,7 +231,7 @@ new Vue({
paymentChecker: null
}
},
showSendDialog: function () {
showSendDialog: function() {
this.send = {
show: true,
invoice: null,
@@ -233,20 +241,20 @@ new Vue({
paymentChecker: null
}
},
closeReceiveDialog: function () {
closeReceiveDialog: function() {
var checker = this.receive.paymentChecker
setTimeout(function () {
setTimeout(function() {
clearInterval(checker)
}, 10000)
},
closeSendDialog: function () {
closeSendDialog: function() {
this.sendCamera.show = false
var checker = this.send.paymentChecker
setTimeout(function () {
setTimeout(function() {
clearInterval(checker)
}, 1000)
},
createInvoice: function () {
createInvoice: function() {
var self = this
this.receive.status = 'loading'
LNbits.api
@@ -255,14 +263,14 @@ new Vue({
this.receive.data.amount,
this.receive.data.memo
)
.then(function (response) {
.then(function(response) {
self.receive.status = 'success'
self.receive.paymentReq = response.data.payment_request
self.receive.paymentChecker = setInterval(function () {
self.receive.paymentChecker = setInterval(function() {
LNbits.api
.getPayment(self.g.wallet, response.data.checking_id)
.then(function (response) {
.getPayment(self.g.wallet, response.data.payment_hash)
.then(function(response) {
if (response.data.paid) {
self.fetchPayments()
self.receive.show = false
@@ -271,17 +279,17 @@ new Vue({
})
}, 2000)
})
.catch(function (error) {
.catch(function(error) {
LNbits.utils.notifyApiError(error)
self.receive.status = 'pending'
})
},
decodeQR: function (res) {
decodeQR: function(res) {
this.send.data.bolt11 = res
this.decodeInvoice()
this.sendCamera.show = false
},
decodeInvoice: function () {
decodeInvoice: function() {
if (this.send.data.bolt11.startsWith('lightning:')) {
this.send.data.bolt11 = this.send.data.bolt11.slice(10)
}
@@ -306,7 +314,7 @@ new Vue({
fsat: LNbits.utils.formatSat(invoice.human_readable_part.amount / 1000)
}
_.each(invoice.data.tags, function (tag) {
_.each(invoice.data.tags, function(tag) {
if (_.isObject(tag) && _.has(tag, 'description')) {
if (tag.description == 'payment_hash') {
cleanInvoice.hash = tag.value
@@ -327,10 +335,10 @@ new Vue({
this.send.invoice = Object.freeze(cleanInvoice)
},
payInvoice: function () {
payInvoice: function() {
var self = this
dismissPaymentMsg = this.$q.notify({
let dismissPaymentMsg = this.$q.notify({
timeout: 0,
message: 'Processing payment...',
icon: null
@@ -338,11 +346,11 @@ new Vue({
LNbits.api
.payInvoice(this.g.wallet, this.send.data.bolt11)
.then(function (response) {
self.send.paymentChecker = setInterval(function () {
.then(function(response) {
self.send.paymentChecker = setInterval(function() {
LNbits.api
.getPayment(self.g.wallet, response.data.checking_id)
.then(function (res) {
.getPayment(self.g.wallet, response.data.payment_hash)
.then(function(res) {
if (res.data.paid) {
self.send.show = false
clearInterval(self.send.paymentChecker)
@@ -352,58 +360,58 @@ new Vue({
})
}, 2000)
})
.catch(function (error) {
.catch(function(error) {
dismissPaymentMsg()
LNbits.utils.notifyApiError(error)
})
},
deleteWallet: function (walletId, user) {
deleteWallet: function(walletId, user) {
LNbits.utils
.confirmDialog('Are you sure you want to delete this wallet?')
.onOk(function () {
.onOk(function() {
LNbits.href.deleteWallet(walletId, user)
})
},
fetchPayments: function (checkPending) {
fetchPayments: function(checkPending) {
var self = this
return LNbits.api
.getPayments(this.g.wallet, checkPending)
.then(function (response) {
.then(function(response) {
self.payments = response.data
.map(function (obj) {
.map(function(obj) {
return LNbits.map.payment(obj)
})
.sort(function (a, b) {
.sort(function(a, b) {
return b.time - a.time
})
})
},
checkPendingPayments: function () {
checkPendingPayments: function() {
var dismissMsg = this.$q.notify({
timeout: 0,
message: 'Checking pending transactions...',
icon: null
})
this.fetchPayments(true).then(function () {
this.fetchPayments(true).then(function() {
dismissMsg()
})
},
exportCSV: function () {
exportCSV: function() {
LNbits.utils.exportCSV(this.paymentsTable.columns, this.payments)
}
},
watch: {
payments: function () {
payments: function() {
EventHub.$emit('update-wallet-balance', [this.g.wallet.id, this.balance])
}
},
created: function () {
created: function() {
this.fetchPayments()
setTimeout(this.checkPendingPayments(), 1200)
},
mounted: function () {
mounted: function() {
if (
this.$refs.disclaimer &&
!this.$q.localStorage.getItem('lnbits.disclaimerShown')
+6 -6
View File
@@ -23,7 +23,7 @@
Returns 201 CREATED (application/json)
</h5>
<code
>{"checking_id": &lt;string&gt;, "payment_request":
>{"payment_hash": &lt;string&gt;, "payment_request":
&lt;string&gt;}</code
>
<h5 class="text-caption q-mt-sm q-mb-none">Curl example</h5>
@@ -51,7 +51,7 @@
<h5 class="text-caption q-mt-sm q-mb-none">
Returns 201 CREATED (application/json)
</h5>
<code>{"checking_id": &lt;string&gt;}</code>
<code>{"payment_hash": &lt;string&gt;}</code>
<h5 class="text-caption q-mt-sm q-mb-none">Curl example</h5>
<code
>curl -X POST {{ request.url_root }}api/v1/payments -d '{"out": true,
@@ -73,7 +73,7 @@
<q-card-section>
<code
><span class="text-light-blue">GET</span>
/api/v1/payments/&lt;checking_id&gt;</code
/api/v1/payments/&lt;payment_hash&gt;</code
>
<h5 class="text-caption q-mt-sm q-mb-none">Headers</h5>
<code>{"X-Api-Key": "{{ wallet.inkey }}"}</code>
@@ -83,9 +83,9 @@
<code>{"paid": &lt;bool&gt;}</code>
<h5 class="text-caption q-mt-sm q-mb-none">Curl example</h5>
<code
>curl -X GET {{ request.url_root }}api/v1/payments/&lt;checking_id&gt;
-H "X-Api-Key: <i>{{ wallet.inkey }}"</i> -H "Content-type:
application/json"</code
>curl -X GET {{ request.url_root
}}api/v1/payments/&lt;payment_hash&gt; -H "X-Api-Key:
<i>{{ wallet.inkey }}"</i> -H "Content-type: application/json"</code
>
</q-card-section>
</q-card>
+1 -1
View File
@@ -84,7 +84,7 @@
dense
flat
:data="filteredPayments"
row-key="payhash"
row-key="checking_id"
:columns="paymentsTable.columns"
:pagination.sync="paymentsTable.pagination"
>
+31 -11
View File
@@ -2,12 +2,12 @@ from flask import g, jsonify, request
from http import HTTPStatus
from binascii import unhexlify
from lnbits import bolt11
from lnbits.core import core_app
from lnbits.core.services import create_invoice, pay_invoice
from lnbits.decorators import api_check_wallet_key, api_validate_post_request
from lnbits.settings import WALLET
from ..services import create_invoice, pay_invoice
@core_app.route("/api/v1/payments", methods=["GET"])
@api_check_wallet_key("invoice")
@@ -41,20 +41,31 @@ def api_payments_create_invoice():
memo = g.data["memo"]
try:
checking_id, payment_request = create_invoice(
payment_hash, payment_request = create_invoice(
wallet_id=g.wallet.id, amount=g.data["amount"], memo=memo, description_hash=description_hash
)
except Exception as e:
return jsonify({"message": str(e)}), HTTPStatus.INTERNAL_SERVER_ERROR
return jsonify({"checking_id": checking_id, "payment_request": payment_request}), HTTPStatus.CREATED
invoice = bolt11.decode(payment_request)
return (
jsonify(
{
"payment_hash": invoice.payment_hash,
"payment_request": payment_request,
# maintain backwards compatibility with API clients:
"checking_id": invoice.payment_hash,
}
),
HTTPStatus.CREATED,
)
@api_check_wallet_key("admin")
@api_validate_post_request(schema={"bolt11": {"type": "string", "empty": False, "required": True}})
def api_payments_pay_invoice():
try:
checking_id = pay_invoice(wallet_id=g.wallet.id, bolt11=g.data["bolt11"])
payment_hash = pay_invoice(wallet_id=g.wallet.id, payment_request=g.data["bolt11"])
except ValueError as e:
return jsonify({"message": str(e)}), HTTPStatus.BAD_REQUEST
except PermissionError as e:
@@ -62,7 +73,16 @@ def api_payments_pay_invoice():
except Exception as e:
return jsonify({"message": str(e)}), HTTPStatus.INTERNAL_SERVER_ERROR
return jsonify({"checking_id": checking_id}), HTTPStatus.CREATED
return (
jsonify(
{
"payment_hash": payment_hash,
# maintain backwards compatibility with API clients:
"checking_id": payment_hash,
}
),
HTTPStatus.CREATED,
)
@core_app.route("/api/v1/payments", methods=["POST"])
@@ -73,10 +93,10 @@ def api_payments_create():
return api_payments_create_invoice()
@core_app.route("/api/v1/payments/<checking_id>", methods=["GET"])
@core_app.route("/api/v1/payments/<payment_hash>", methods=["GET"])
@api_check_wallet_key("invoice")
def api_payment(checking_id):
payment = g.wallet.get_payment(checking_id)
def api_payment(payment_hash):
payment = g.wallet.get_payment(payment_hash)
if not payment:
return jsonify({"message": "Payment does not exist."}), HTTPStatus.NOT_FOUND
@@ -85,9 +105,9 @@ def api_payment(checking_id):
try:
if payment.is_out:
is_paid = not WALLET.get_payment_status(checking_id).pending
is_paid = not WALLET.get_payment_status(payment.checking_id).pending
elif payment.is_in:
is_paid = not WALLET.get_invoice_status(checking_id).pending
is_paid = not WALLET.get_invoice_status(payment.checking_id).pending
except Exception:
return jsonify({"paid": False}), HTTPStatus.OK
+1 -1
View File
@@ -64,7 +64,7 @@ def wallet():
allowed_users = getenv("LNBITS_ALLOWED_USERS", "all")
if allowed_users != "all" and user_id not in allowed_users.split(","):
abort(HTTPStatus.UNAUTHORIZED, f"User not authorized.")
abort(HTTPStatus.UNAUTHORIZED, "User not authorized.")
if not wallet_id:
if user.wallets and not wallet_name: