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 answered401: nothing is recorded and process-paid is not invoked.- Delayed notify (
delayednotify.py), which/notifyinvokes after that check and which has no route of its own, checks it again and markschecksumVerifiedon the record of the notify'sidonly. - The mark is an attribute update (
record.update(actions=[...checksumVerified.set(verified)])), never a whole-itemsave(): a save writes the record back through this model, dropping the fields it does not define (cardtoken'schargeResponse,userId, the paid claim'sprocessPaidState) and racing/callback.
Function Flow
Entry Points
/notify(functions/callback/notify.py) callsverify_and_handle_checksum(event, function_name="notify", ..., update_status=False)before anything else. It marks nothing: a failed checksum is answered401and nothing is recorded.- Delayed notify (
functions/callback/delayednotify.py), invoked by/notifyafter that check, callsverify_and_handle_checksum(...)with the defaultupdate_status=True, after refusing a body that names a charge other than itsid. That call markschecksumVerified.
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)
- The charge is the body's
id(extract_charge_id), the only field naming a charge that the checksum covers. - Verify the checksum with K Bank's secret key
(
checksum_verifier.verify_notification_checksum). - Mark it (only when
update_statusis true, so in delayed notify):update_checksum_verification_status(charge_id, verified)setschecksumVerifiedon that charge's card record, an attribute update. - 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:
- First: Try to find record in branch-specific table (
payment3-card-payment-record-{BRANCH}) - If not found: Try master table (
payment3-card-payment-record-master) - 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 noid(a non-empty string), or also names a charge inobjectId,chargeIdorcharge_idthat is not itsid.extract_charge_id(event)returns that id or None;verify_and_handle_checksummarkschecksumVerifiedon that charge's record only./notifyanswers 400 to a refused body; delayed notify refuses it before anything is recorded (refuse_notify). Both hand the id toCreditCardCallbackProcessor.checksummed_charge_id, which wins over the body'sobjectId(the browser return's field, read by/callbackonly).
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 verifiedFalse: Checksum verification failedNone: Checksum verification was not attempted or charge_id was not found
When Checksum is Marked
True: Whenverify_notification_checksum()returnsTrueFalse: Whenverify_notification_checksum()returnsFalseor raises an exceptionNone: Whencharge_idcannot 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:
- Rejected: the answer is
401; nothing is recorded, no card record is changed and process-paid is not invoked - Error Logging: Error is logged to
CallbackErrorLogTable - Email Notification: Error email is sent via SES
- 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.
Related Files
functions/callback/notify.py- Main entry pointfunctions/callback/src/checksum_handler.py- Checksum verification and status update logicfunctions/callback/src/checksum_verifier.py- KBank checksum verification algorithmfunctions/callback/src/cardPaymentRecordTable.py- Branch table modelfunctions/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
chargeIdusing GSI - Updating
checksumVerifiedfield - Accessing KBank secret keys for checksum verification