Better form amount parsing

This commit is contained in:
polyfloyd 2025-04-13 15:07:06 +02:00
parent 21067e3b1d
commit d19c990039

21
main.py
View file

@ -22,18 +22,25 @@ async def welcome(request: Request):
return templates.TemplateResponse(request=request, name="welcome.html.j2")
@app.post("/", response_class=RedirectResponse)
async def pay(request: Request, amount: Annotated[int, Form()]):
# Amount is in cents. Depositing less than a euro does not really make sense, so interpret this
# as full Euro's.
if amount < 100:
amount *= 100
@app.post("/")
async def pay(request: Request, amount: Annotated[str, Form()]):
# Normalize input.
if "," in amount:
amount = amount.replace(",", ".")
if "." not in amount:
amount = f"{amount}.00"
# Conversion.
[i, f] = amount.split(".")
cents = int(i) * 100 + int(f)
# Sanity checks.
if cents < 10_00 or 150_00 < cents:
raise HTTPException(status_code=400, detail=f"invalid amount: {amount}")
payment = mollie_client.payments.create(
{
"amount": {
"currency": "EUR",
"value": f"{amount // 100}.{amount % 100:02}",
"value": f"{cents // 100}.{cents % 100:02}",
},
"description": "Bitlair bar tegoed",
"redirectUrl": f"{public_url}/return",