newIdempotencyKey function

String newIdempotencyKey()

A fresh random UUID (version 4) for the Idempotency-Key of one purchase intent.

Make it once, before the first attempt, and keep it for that purchase: after a timeout or a 5xx repeat the same key and body. Never reuse a key for a different purchase.

Implementation

String newIdempotencyKey() {
  final random = Random.secure();
  final bytes = List<int>.generate(16, (_) => random.nextInt(256));
  bytes[6] = (bytes[6] & 0x0f) | 0x40; // version 4
  bytes[8] = (bytes[8] & 0x3f) | 0x80; // RFC 4122 variant
  final hex = bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join();
  return '${hex.substring(0, 8)}-${hex.substring(8, 12)}-${hex.substring(12, 16)}-'
      '${hex.substring(16, 20)}-${hex.substring(20)}';
}