Skip to main content

Checksum Marking Documentation

Overview​

This document explains how K Bank's card notifications are checked and how checksum verification status is marked in the CardPaymentRecordTable. The checksum verification process ensures that webhook notifications from KBank payment gateway are authentic and have not been tampered with.

  • /notify (notify.py) checks the checksum first, without marking anything (update_status=False). A notify whose checksum fails is answered 401: nothing is recorded and process-paid is not invoked.
  • Delayed notify (delayednotify.py), which /notify invokes after that check and which has no route of its own, checks it again and marks checksumVerified on the record of the notify's id only.
  • The mark is an attribute update (record.update(actions=[...checksumVerified.set(verified)])), never a whole-item save(): a save writes the record back through this model, dropping the fields it does not define (cardtoken's chargeResponse, userId, the paid claim's processPaidState) and racing /callback.

Function Flow​

Entry Points​

  • /notify (functions/callback/notify.py) calls verify_and_handle_checksum(event, function_name="notify", ..., update_status=False) before anything else. It marks nothing: a failed checksum is answered 401 and nothing is recorded.
  • Delayed notify (functions/callback/delayednotify.py), invoked by /notify after that check, calls verify_and_handle_checksum(...) with the default update_status=True, after refusing a body that names a charge other than its id. That call marks checksumVerified.

Checksum Verification Process​

File: functions/callback/src/checksum_handler.py Function: verify_and_handle_checksum(event, function_name, branch=None, debug_mode=False, update_status=True)

  1. The charge is the body's id (extract_charge_id), the only field naming a charge that the checksum covers.
  2. Verify the checksum with K Bank's secret key (checksum_verifier.verify_notification_checksum).
  3. Mark it (only when update_status is true, so in delayed notify): update_checksum_verification_status(charge_id, verified) sets checksumVerified on that charge's card record, an attribute update.
  4. A failed checksum is logged to CallbackErrorLogTable, mailed and sent to Sentry; the function answers (False, error, charge_id) and the caller rejects the notify.

DynamoDB Table Schema​

CardPaymentRecordTable (Branch Table)​

Table Name: payment3-card-payment-record-{BRANCH}
Region: ap-southeast-1

PynamoDB Model:

class CardPaymentRecordTable(Model):
class Meta:
table_name = f"payment3-card-payment-record-{BRANCH}"
region = "ap-southeast-1"

chargeId_index = ChargeIdIndex()
tokenId = UnicodeAttribute(hash_key=True)
orderId = UnicodeAttribute()
createdAt = UTCDateTimeAttribute()
chargeId = UnicodeAttribute(null=True)
status = BooleanAttribute(null=True)
checksumVerified = BooleanAttribute(null=True)

def __post_init__(self):
self.createdAt = datetime.now()

Key Fields:

  • Hash Key: tokenId (UnicodeAttribute)
  • Global Secondary Index: chargeId_index (hash_key: chargeId)
  • checksumVerified: BooleanAttribute(null=True) - Marks if checksum was verified
  • status: BooleanAttribute(null=True) - Payment status (True = success, False = failure)

CardPaymentRecordTableMaster (Master Table)​

Table Name: payment3-card-payment-record-master
Region: ap-southeast-1

PynamoDB Model:

class CardPaymentRecordTableMaster(Model):
class Meta:
table_name = f"payment3-card-payment-record-master"
region = "ap-southeast-1"

chargeId_index = ChargeIdIndex()
tokenId = UnicodeAttribute(hash_key=True)
orderId = UnicodeAttribute()
createdAt = UTCDateTimeAttribute()
chargeId = UnicodeAttribute(null=True)
status = BooleanAttribute(null=True)
checksumVerified = BooleanAttribute(null=True)

def __post_init__(self):
self.createdAt = datetime.now()

Note: Master table has the same schema as branch table. Used as fallback when record is not found in branch table.

Updating Checksum Verification Status​

Function: update_checksum_verification_status()​

File: functions/callback/src/checksum_handler.py

This function updates the checksumVerified field in the CardPaymentRecordTable:

def update_checksum_verification_status(charge_id: str, verified: bool, debug_mode: bool = False):
"""
Update checksumVerified field in CardPaymentRecordTable.

Args:
charge_id: The charge ID to update
verified: Boolean indicating if checksum was verified successfully
debug_mode: If True, skip actual database updates
"""
if debug_mode:
print(f"DEBUG_MODE: Skipping checksum verification status update. Would update chargeId={charge_id}, checksumVerified={verified}")
return

try:
# Try branch-specific table first
try:
query_result = CardPaymentRecordTable.chargeId_index.query(charge_id)
record = next(query_result)
# Only this attribute: save() would write the whole item back
# through this model, dropping what it does not define (cardtoken's
# chargeResponse, the paid claim's state) and racing /callback.
record.update(actions=[CardPaymentRecordTable.checksumVerified.set(verified)])
print(f"[SUCCESS] Updated checksumVerified={verified} for chargeId={charge_id} in branch table")
return
except StopIteration:
print(f"[INFO] Record not found in branch table, trying master table")
except Exception as e:
print(f"[WARNING] Error updating branch table: {type(e).__name__}: {e}")

# Try master table
try:
query_result = CardPaymentRecordTableMaster.chargeId_index.query(charge_id)
record = next(query_result)
record.update(actions=[CardPaymentRecordTableMaster.checksumVerified.set(verified)])
print(f"[SUCCESS] Updated checksumVerified={verified} for chargeId={charge_id} in master table")
return
except StopIteration:
print(f"[WARNING] Card payment record not found in both tables for chargeId={charge_id}")
except Exception as e:
print(f"[WARNING] Error updating master table: {type(e).__name__}: {e}")
except Exception as e:
print(f"[ERROR] Failed to update checksum verification status: {type(e).__name__}: {e}")
# Don't raise - this is a non-critical update

Query Pattern​

The function uses the chargeId_index Global Secondary Index to find records:

PynamoDB Query Example:

from src.cardPaymentRecordTable import CardPaymentRecordTable

# Query by chargeId using GSI
charge_id = "chrg_prod_1234567890"
query_result = CardPaymentRecordTable.chargeId_index.query(charge_id)

try:
record = next(query_result)
# Update the checksumVerified attribute only (never record.save()).
record.update(actions=[CardPaymentRecordTable.checksumVerified.set(True)]) # or False
print(f"Updated checksumVerified for chargeId={charge_id}")
except StopIteration:
print(f"Record not found for chargeId={charge_id}")

Fallback Logic​

The update process follows this fallback pattern:

  1. First: Try to find record in branch-specific table (payment3-card-payment-record-{BRANCH})
  2. If not found: Try master table (payment3-card-payment-record-master)
  3. If still not found: Log warning but don't raise exception (non-critical update)

This fallback ensures that records created in master branch can still have their checksum status updated.

Charge ID Extraction​

Functions: notify_charge_id() and extract_charge_id() (functions/callback/src/checksum_handler.py)

K Bank's notify is its charge object. Its checksum covers the charge's id (with amount, currency, status, transaction_state, failure_code) and no other field that names a charge. So the charge a notify is about is its id, and nothing else:

  • notify_charge_id(body) returns (id, None), or (None, reason) when the body has no id (a non-empty string), or also names a charge in objectId, chargeId or charge_id that is not its id.
  • extract_charge_id(event) returns that id or None; verify_and_handle_checksum marks checksumVerified on that charge's record only.
  • /notify answers 400 to a refused body; delayed notify refuses it before anything is recorded (refuse_notify). Both hand the id to CreditCardCallbackProcessor.checksummed_charge_id, which wins over the body's objectId (the browser return's field, read by /callback only).

Before this, objectId was read first: a genuine paid notify of one charge, replayed with objectId set to an unpaid 3-D Secure charge of another order, passed the checksum, set checksumVerified on that other charge and invoked process-paid for the other order.

Checksum Verification Values​

Possible Values for checksumVerified​

  • True: Checksum was successfully verified
  • False: Checksum verification failed
  • None: Checksum verification was not attempted or charge_id was not found

When Checksum is Marked​

  1. True: When verify_notification_checksum() returns True
  2. False: When verify_notification_checksum() returns False or raises an exception
  3. None: When charge_id cannot be extracted from event

Usage in Other Functions​

checksumVerified only says that a K Bank notify with a valid checksum named the charge; it says nothing about whether that notify reported the charge paid (a notify of a failed charge sets it too), for how much, or for which order. processPaidOrder decides nothing on it: every card charge is checked with K Bank through check-status (functions/processPaidOrder/README.md, "No checksum shortcut").

Never decide a payment on checksumVerified and status: status True is also what POST /cardpayment writes for the 3-D Secure create reply, and next() of orderId_index can be any attempt of the order (the index has no sort key). Ask K Bank (src/payment_verification.py verify_kbank_charge_paid, or check-status) for the charge, with the order and its total.

Error Handling​

If checksum verification fails at /notify:

  1. Rejected: the answer is 401; nothing is recorded, no card record is changed and process-paid is not invoked
  2. Error Logging: Error is logged to CallbackErrorLogTable
  3. Email Notification: Error email is sent via SES
  4. Sentry: Exception is captured in Sentry

Delayed notify only runs for a notify that passed this check; it marks the result on the charge's record.

  • functions/callback/notify.py - Main entry point
  • functions/callback/src/checksum_handler.py - Checksum verification and status update logic
  • functions/callback/src/checksum_verifier.py - KBank checksum verification algorithm
  • functions/callback/src/cardPaymentRecordTable.py - Branch table model
  • functions/callback/src/cardPaymentRecordTableMaster.py - Master table model

Template.yaml Configuration​

Function: Notify (lines 348-413 in template.yaml)

Required IAM Policies:

  • DynamoDBCrudPolicy for CardPaymentRecordTable (line 372-373)
  • DynamoDBCrudPolicy for payment3-card-payment-record-master (line 375-376)
  • AWSSecretsManagerGetSecretValuePolicy for kbank-dev and kbank-prod secrets (lines 396-399)

These permissions are required for:

  • Querying records by chargeId using GSI
  • Updating checksumVerified field
  • Accessing KBank secret keys for checksum verification