django_program.registration.stripe_utils

Currency conversion helpers for Stripe API integration and key obfuscation for logging.

Stripe represents monetary amounts as integers in the smallest currency unit (e.g. cents for USD). Most currencies are “normal-decimal” where 1 unit = 100 smallest units, but a subset of currencies are “zero-decimal” where the integer amount is the unit amount.

This module provides bidirectional conversion between Decimal values used in Django models and the integer representation expected by the Stripe API, as well as a helper to safely obfuscate API keys for log output.

Functions

convert_amount_for_api(amount, currency)

Convert a Decimal amount to the integer representation expected by the Stripe API.

convert_amount_for_db(amount, currency)

Convert an integer amount from the Stripe API back to a Decimal for database storage.

obfuscate_key(key)

Obfuscate an API key so it can be safely written to logs.

django_program.registration.stripe_utils.convert_amount_for_api(amount, currency)[source]

Convert a Decimal amount to the integer representation expected by the Stripe API.

For most currencies the smallest unit is 1/100 of the standard unit (e.g. cents for USD), so Decimal("10.00") becomes 1000. Zero-decimal currencies such as JPY are returned as int(amount) directly because one unit already is the smallest unit.

Parameters:
  • amount (Decimal) – The monetary amount as a Decimal.

  • currency (str) – An ISO 4217 currency code (case-insensitive).

Return type:

int

Returns:

The amount as an integer in the smallest currency unit suitable for Stripe.

django_program.registration.stripe_utils.convert_amount_for_db(amount, currency)[source]

Convert an integer amount from the Stripe API back to a Decimal for database storage.

This is the inverse of convert_amount_for_api(). For normal-decimal currencies the integer is divided by 100 (e.g. 1000 becomes Decimal("10.00")). For zero-decimal currencies the integer is returned as-is wrapped in a Decimal.

Parameters:
  • amount (int) – The integer amount in the smallest currency unit as returned by Stripe.

  • currency (str) – An ISO 4217 currency code (case-insensitive).

Return type:

Decimal

Returns:

The amount as a Decimal suitable for a Django DecimalField.

django_program.registration.stripe_utils.obfuscate_key(key)[source]

Obfuscate an API key so it can be safely written to logs.

Returns the last four characters of the key prefixed with "****". If the key is shorter than four characters the entire value is masked and only "****" is returned.

Parameters:

key (str) – The secret key to obfuscate.

Return type:

str

Returns:

A partially masked string safe for log output.