forked from lnbits/tpos
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathviews_api.py
More file actions
315 lines (273 loc) · 10 KB
/
views_api.py
File metadata and controls
315 lines (273 loc) · 10 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
import json
from http import HTTPStatus
import httpx
from fastapi import APIRouter, Depends, HTTPException, Query
from lnbits.core.crud import (
get_latest_payments_by_extension,
get_standalone_payment,
get_user,
)
from lnbits.core.models import CreateInvoice, Payment, WalletTypeInfo
from lnbits.core.services import create_payment_request
from lnbits.decorators import (
require_admin_key,
require_invoice_key,
)
from lnurl import LnurlPayResponse
from lnurl import decode as decode_lnurl
from lnurl import handle as lnurl_handle
from .crud import (
create_tpos,
delete_tpos,
get_tpos,
get_tposs,
update_tpos,
)
from .models import (
CreateTposData,
CreateTposInvoice,
CreateUpdateItemData,
PayLnurlWData,
Tpos,
)
tpos_api_router = APIRouter()
@tpos_api_router.get("/api/v1/tposs", status_code=HTTPStatus.OK)
async def api_tposs(
all_wallets: bool = Query(False),
key_info: WalletTypeInfo = Depends(require_invoice_key),
) -> list[Tpos]:
wallet_ids = [key_info.wallet.id]
if all_wallets:
user = await get_user(key_info.wallet.user)
wallet_ids = user.wallet_ids if user else []
return await get_tposs(wallet_ids)
@tpos_api_router.post("/api/v1/tposs", status_code=HTTPStatus.CREATED)
async def api_tpos_create(
data: CreateTposData, key_type: WalletTypeInfo = Depends(require_admin_key)
):
data.wallet = key_type.wallet.id
tpos = await create_tpos(data)
return tpos
@tpos_api_router.put("/api/v1/tposs/{tpos_id}")
async def api_tpos_update(
data: CreateTposData,
tpos_id: str,
wallet: WalletTypeInfo = Depends(require_admin_key),
):
tpos = await get_tpos(tpos_id)
if not tpos:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail="TPoS does not exist."
)
if wallet.wallet.id != tpos.wallet:
raise HTTPException(status_code=HTTPStatus.FORBIDDEN, detail="Not your TPoS.")
for field, value in data.dict().items():
setattr(tpos, field, value)
tpos = await update_tpos(tpos)
return tpos
@tpos_api_router.delete("/api/v1/tposs/{tpos_id}")
async def api_tpos_delete(
tpos_id: str, wallet: WalletTypeInfo = Depends(require_admin_key)
):
tpos = await get_tpos(tpos_id)
if not tpos:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail="TPoS does not exist."
)
if tpos.wallet != wallet.wallet.id:
raise HTTPException(status_code=HTTPStatus.FORBIDDEN, detail="Not your TPoS.")
await delete_tpos(tpos_id)
return "", HTTPStatus.NO_CONTENT
@tpos_api_router.post(
"/api/v1/tposs/{tpos_id}/invoices", status_code=HTTPStatus.CREATED
)
async def api_tpos_create_invoice(tpos_id: str, data: CreateTposInvoice) -> Payment:
tpos = await get_tpos(tpos_id)
if not tpos:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail="TPoS does not exist."
)
if not data.details:
tax_value = 0.0
if tpos.tax_default:
tax_value = (
(data.amount / data.exchange_rate) * (tpos.tax_default * 0.01)
if data.exchange_rate
else 0.0
)
data.details = {
"currency": tpos.currency,
"exchangeRate": data.exchange_rate,
"items": None,
"taxIncluded": True,
"taxValue": tax_value,
}
currency = tpos.currency if data.pay_in_fiat else "sat"
amount = data.amount + (data.tip_amount or 0.0)
if data.pay_in_fiat:
amount = (data.amount_fiat or 0.0) + (data.tip_amount_fiat or 0.0)
try:
invoice_data = CreateInvoice(
unit=currency,
out=False,
amount=amount,
memo=f"{data.memo} to {tpos.name}" if data.memo else f"{tpos.name}",
extra={
"tag": "tpos",
"tip_amount": data.tip_amount,
"tpos_id": tpos_id,
"amount": data.amount,
"exchangeRate": data.exchange_rate if data.exchange_rate else None,
"details": data.details if data.details else None,
"lnaddress": data.user_lnaddress if data.user_lnaddress else None,
"internal_memo": data.internal_memo if data.internal_memo else None,
},
fiat_provider=tpos.fiat_provider if data.pay_in_fiat else None,
)
return await create_payment_request(tpos.wallet, invoice_data)
except Exception as exc:
raise HTTPException(
status_code=HTTPStatus.INTERNAL_SERVER_ERROR, detail=str(exc)
) from exc
@tpos_api_router.get("/api/v1/tposs/{tpos_id}/invoices")
async def api_tpos_get_latest_invoices(tpos_id: str):
payments = await get_latest_payments_by_extension(ext_name="tpos", ext_id=tpos_id)
details = payments[0].extra.get("details", None)
exchange_rate = None
currency = None
if details:
exchange_rate = details.get("exchange_rate", None)
currency = details.get("currency", None)
return [
{
"checking_id": payment.checking_id,
"amount": payment.amount,
"time": payment.time,
"pending": payment.pending,
"currency": currency,
"exchange_rate": exchange_rate,
}
for payment in payments
]
@tpos_api_router.post(
"/api/v1/tposs/{tpos_id}/invoices/{payment_request}/pay", status_code=HTTPStatus.OK
)
async def api_tpos_pay_invoice(
lnurl_data: PayLnurlWData, payment_request: str, tpos_id: str
):
tpos = await get_tpos(tpos_id)
if not tpos:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail="TPoS does not exist."
)
lnurl = (
lnurl_data.lnurl.replace("lnurlw://", "")
.replace("lightning://", "")
.replace("LIGHTNING://", "")
.replace("lightning:", "")
.replace("LIGHTNING:", "")
)
if lnurl.lower().startswith("lnurl"):
lnurl = decode_lnurl(lnurl)
else:
lnurl = "https://" + lnurl
async with httpx.AsyncClient() as client:
try:
headers = {"user-agent": "lnbits/tpos"}
r = await client.get(lnurl, follow_redirects=True, headers=headers)
if r.is_error:
lnurl_response = {"success": False, "detail": "Error loading"}
else:
resp = r.json()
if resp.get("status") == "ERROR":
lnurl_response = {
"success": False,
"detail": resp.get("reason", ""),
}
return lnurl_response
if resp.get("tag") != "withdrawRequest":
lnurl_response = {"success": False, "detail": "Wrong tag type"}
else:
r2 = await client.get(
resp.get("callback", ""),
follow_redirects=True,
headers=headers,
params={
"k1": resp.get("k1", ""),
"pr": payment_request,
},
)
resp2 = r2.json()
if r2.is_error:
lnurl_response = {
"success": False,
"detail": "Error loading callback",
}
elif resp2.get("status") == "ERROR":
lnurl_response = {"success": False, "detail": resp2["reason"]}
else:
lnurl_response = {"success": True, "detail": resp2}
except (httpx.ConnectError, httpx.RequestError):
lnurl_response = {"success": False, "detail": "Unexpected error occurred"}
return lnurl_response
@tpos_api_router.get(
"/api/v1/tposs/{tpos_id}/invoices/{payment_hash}", status_code=HTTPStatus.OK
)
async def api_tpos_check_invoice(
tpos_id: str, payment_hash: str, extra: bool = Query(False)
):
tpos = await get_tpos(tpos_id)
if not tpos:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail="TPoS does not exist."
)
payment = await get_standalone_payment(payment_hash, incoming=True)
if not payment:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail="Payment does not exist."
)
if payment.extra.get("tag") != "tpos":
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail="TPoS payment does not exist."
)
if extra:
return {
"paid": payment.success,
"extra": payment.extra,
"created_at": payment.created_at,
"business_name": tpos.business_name,
"business_address": tpos.business_address,
"business_vat_id": tpos.business_vat_id,
}
return {"paid": payment.success}
@tpos_api_router.put("/api/v1/tposs/{tpos_id}/items", status_code=HTTPStatus.CREATED)
async def api_tpos_create_items(
data: CreateUpdateItemData,
tpos_id: str,
wallet: WalletTypeInfo = Depends(require_admin_key),
) -> Tpos:
tpos = await get_tpos(tpos_id)
if not tpos:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail="TPoS does not exist."
)
if wallet.wallet.id != tpos.wallet:
raise HTTPException(status_code=HTTPStatus.FORBIDDEN, detail="Not your TPoS.")
tpos.items = json.dumps(data.dict()["items"])
tpos = await update_tpos(tpos)
return tpos
@tpos_api_router.get("/api/v1/tposs/lnaddresscheck", status_code=HTTPStatus.OK)
async def api_tpos_check_lnaddress(lnaddress: str):
try:
res = await lnurl_handle(lnaddress)
except Exception as exc:
raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST,
detail=f"Error checking lnaddress: {exc!s}",
) from exc
if not isinstance(res, LnurlPayResponse):
raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST,
detail="The provided lnaddress returned an unexpected response type.",
)
return True