How to Build a Bitcoin Donation Page with Optional Amounts
A donation page can offer suggested amounts without forcing a fixed contribution.
Implementation approach
Use integer satoshis and format exactly eight decimal places in a BIP21 URI. Omit the amount parameter for open contributions. The configured address must be validated separately. Never infer payment from a browser redirect.
Source code
1from urllib.parse import urlencode
2
3def payment_uri(address, sats=None):
4 if not address.isascii() or not address.isalnum():
5 raise ValueError('unsafe address characters')
6 if sats is None: return 'bitcoin:' + address
7 if type(sats) is not int or not 0 < sats <= 21_000_000 * 100_000_000:
8 raise ValueError('invalid amount')
9 whole, fraction = divmod(sats, 100_000_000)
10 return 'bitcoin:' + address + '?' + urlencode({'amount': f'{whole}.{fraction:08d}'})
11
12if __name__ == '__main__':
13 assert payment_uri('fixture', 1234) == 'bitcoin:fixture?amount=0.00001234'
14 assert payment_uri('fixture') == 'bitcoin:fixture'
15 try: payment_uri('fixture', True)
16 except ValueError: pass
17 else: raise AssertionError('boolean amount accepted')Local validation
Run stage23-donation-page.py with Python 3. Fixtures are not valid Bitcoin addresses. This is an educational example, not a production donation service. No SEND operation is included.
Related documentation
https://thamer.org/api
