JourneyJoker/payment/sepa/functions.py

59 lines
1.4 KiB
Python
Raw Normal View History

import string
import re
import random
from dbsettings.functions import getValue
import qrcode
QRCODE_CONTENT = """
BCD
002
1
SCT
%s
%s
%s
%s%s
%s
%s
%s
%s
""".strip()
def generate_rf(reference):
reference = str(reference).upper().zfill(21) + "RF00"
pattern = re.compile("[A-Z0-9]+")
if not pattern.fullmatch(reference):
raise ValueError("Not a valid reference: %s may only contain 0-9 and A-Z!")
code = ""
chars = string.digits + string.ascii_uppercase
for char in reference:
code += str(chars.index(char))
remainder = int(code) % 97
checksum = 98 - remainder
return "RF%i%s" % (checksum, reference[:-4])
def generate_reference(length=21):
return "".join([random.SystemRandom().choice(string.digits + string.ascii_uppercase) for i in range(length)])
def generate_qrcode(amount, iban="", recipient="", bic="", reference="", currency="EUR", message="", purpose="", notice=""):
content = QRCODE_CONTENT % (
bic or getValue("sepa.bic", ""),
recipient or getValue("sepa.account_holder", ""),
iban or getValue("sepa.iban"),
currency,
"{:0.2f}".format(float(amount)).rstrip("0"),
purpose,
reference if (not reference) or str(reference).startswith("RF") or len(str(reference)) > 21 else generate_rf(reference),
message,
notice
)
return qrcode.make(content)