Skip to main content

Notify Lambda Function

Quick Reference​

  • Function Name: payment3-notify-${BRANCH}
  • Handler: notify.lambda_handler
  • Runtime: Python 3.12 (Docker Image)
  • Timeout: 240 seconds
  • Trigger: API Gateway (POST /notify)
  • Template.yaml: Lines 348-413

Function Overview​

The Notify function receives webhook notifications from KBank payment gateway for credit card payments. It performs checksum verification, saves notification records, processes paid orders, and triggers delayed notification processing. This is the primary entry point for credit card payment webhooks.

Entry Point​

File: functions/callback/notify.py
Handler: lambda_handler(event, _)

In order (functions/callback/notify.py), answering K Bank fast ("ack-fast"):

  1. A declined transaction_state is acknowledged (200) and nothing else happens.
  2. The checksum is checked first (verify_and_handle_checksum, update_status=False: nothing is marked here). A notify whose checksum fails is not from K Bank: it is answered 401 and nothing is recorded.
  3. The charge is the notify's id (notify_charge_id); a body that names another charge is refused (400).
  4. A checkout payment (a CHK… description, or a charge the checkout recorded) is handed to the checkout, which asks K Bank itself (src/checkout_bridge.py), and acknowledged.
  5. Otherwise the notify is recorded (CreditCardNotifyTable), delayed notify is invoked asynchronously, and K Bank gets 200 {"message": "received"}. /notify itself changes no card record and does not invoke process-paid.
  6. Delayed notify (delayednotify.py, payment3-delayed-notify-<branch>, no route of its own) refuses a body that names another charge, checks the checksum again and marks checksumVerified on the record of that id, records the notify, and invokes process-paid for a charge reported paid, twice, 60 seconds apart. (The paid claim on the card record, processPaidState, is /callback's, not this path's.)

Event Structure​

API Gateway Event​

Path: POST /notify
Auth: NONE (public endpoint - called by KBank)

Request Body (JSON):

{
"id": "chrg_test_EXAMPLE2",
"object": "charge",
"amount": 1583.0,
"currency": "THB",
"status": "success",
"transaction_state": "Settled",
...
}

Key Fields:

  • id - KBank charge ID (required). It is the only field naming a charge that K Bank's checksum covers: a body that also names a charge in objectId, chargeId or charge_id that is not its id is refused (400), and delayed notify refuses it too (src/checksum_handler.py notify_charge_id).
  • status - Payment status: "success" or "failure" (required)
  • amount - Charged amount
  • currency - Currency code (typically "THB")

Response: 200 {"message": "received"} (K Bank only needs a quick answer; the work runs in delayed notify), 401 for a bad checksum, 400 for a body that names another charge.

Checksum Verification​

Critical: This function performs checksum verification FIRST before any processing.

Process:

  1. Take the charge id from the body's id (the only charge field the checksum covers)
  2. Verify the checksum with K Bank's secret key
  3. A notify whose checksum fails is rejected: 401, nothing recorded, process-paid not invoked (the error is logged, mailed and sent to Sentry)
  4. checksumVerified is marked by delayed notify, which /notify invokes after this check, on that charge's record only (an attribute update, so no other field of the record is written)

See: functions/callback/docs/CHECKSUM_MARKING_DOCUMENTATION.md for detailed documentation.

DynamoDB Tables​

CreditCardNotifyTable​

Table Name: payment3-credit-card-notify-{BRANCH}
Region: ap-southeast-1

PynamoDB Model:

class CreditCardNotifyTable(Model):
class Meta:
table_name = f"payment3-credit-card-notify-{BRANCH}"
region = "ap-southeast-1"

id = UnicodeAttribute(hash_key=True)
data = JSONAttribute()
chargeId = UnicodeAttribute(null=True)
raw_input = JSONAttribute(null=True)
orderId = UnicodeAttribute(null=True)
note = UnicodeAttribute(default="")

Save Pattern:

from src.credit_card_notify_table import CreditCardNotifyTable

CreditCardNotifyTable(
id=charge_id,
chargeId=charge_id,
data=body_data,
raw_input=event,
orderId=order_id,
note=""
).save()

CardPaymentRecordTable​

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

Update: checksumVerified field is updated during checksum verification.

Query: Records are queried by chargeId using GSI chargeId_index.

Lambda Invocations​

ProcessPaidOrder​

Function: payment3-process-paid-order-${BRANCH}
Invoked When: processor.card_payment_record exists

Payload: DynamoDB Stream event format

Invocation Type: Synchronous (via processor.process_paid_order())

DelayedNotify​

Function: payment3-delayed-notify-${BRANCH}
Invoked When: After all processing is complete

Payload: Original event

Invocation Type: Event (asynchronous)

Note: Only called once per invocation (uses environment variable flag)

Processing Flow​

Main Flow​

  1. Reset Flag: Reset the delayed notify flag for this invocation
  2. Declined: a Declined transaction_state is acknowledged (200), nothing else
  3. Verify Checksum: 401 when it fails (nothing is marked or recorded here)
  4. The charge: the body's id; a body naming another charge gets 400
  5. Checkout charge: handed to the checkout, acknowledged
  6. Save Notification: CreditCardNotifyTable
  7. Call Delayed Notify: invoked asynchronously, once
  8. Return Response: 200 {"message": "received"}

Delayed notify then marks checksumVerified on the charge's card record and invokes ProcessPaidOrder (asynchronously) for a charge reported paid, twice, 60 seconds apart.

Error Handling​

Checksum Verification Failures​

A notify whose checksum fails is answered 401: nothing is recorded, no card record is changed and process-paid is not invoked.

if not checksum_valid:
# A notify without a valid K Bank checksum is not from K Bank:
# reject it, record nothing and never mark the order paid.
return {"statusCode": 401, ...}

Handling:

  • Checksum error logged to CallbackErrorLogTable
  • Error email sent via SES
  • Exception captured in Sentry
  • Nothing else happens

Processor Errors​

Exception: Caught in lambda_handler

Handling:

  • Error logged via handle_notify_error()
  • Logged to CallbackErrorLogTable
  • Error email sent via SES
  • Exception captured in Sentry
  • Error re-raised

IAM Policies​

From template.yaml (lines 358-399):

  • DynamoDBWritePolicy for CreditCardNotifyTable (line 360-361)
  • DynamoDBReadPolicy for order-table-dev (line 363-364)
  • DynamoDBWritePolicy for CreditCardCallbackTable (line 366-367)
  • DynamoDBWritePolicy for QRCallbackRecordTable (line 369-370)
  • DynamoDBCrudPolicy for CardPaymentRecordTable (line 372-373)
  • DynamoDBCrudPolicy for payment3-card-payment-record-master (line 375-376)
  • DynamoDBWritePolicy for PaymentErrorLogTable (line 378-379)
  • DynamoDBWritePolicy for CallbackErrorLogTable (line 381-382)
  • LambdaInvokePolicy for ProcessPaidOrder (line 384-385)
  • LambdaInvokePolicy for ProcessPaidOrderInternal (line 387-388)
  • LambdaInvokePolicy for DelayedNotify (line 390-391)
  • SESCrudPolicy for sending error emails (line 393-394)
  • AWSSecretsManagerGetSecretValuePolicy for kbank-dev (line 396-397)
  • AWSSecretsManagerGetSecretValuePolicy for kbank-prod (line 398-399)

Dependencies​

External Lambda Functions​

  • payment3-process-paid-order-${BRANCH} - Process paid orders (invoked)
  • payment3-delayed-notify-${BRANCH} - Delayed notification processing (invoked)

DynamoDB Tables​

  • payment3-credit-card-notify-${BRANCH} - Notification records (write)
  • payment3-card-payment-record-${BRANCH} - Payment records (read/update)
  • payment3-card-payment-record-master - Master payment records (read/update)
  • order-table-dev - Order data (read)
  • payment3-error-log-${BRANCH} - Error logs (write)
  • payment3-callback-error-log-${BRANCH} - Callback error logs (write)

External Services​

  • KBank Payment Gateway: Webhook source
  • AWS Secrets Manager: KBank API credentials for checksum verification
  • SES: Send error notification emails

Environment Variables​

  • BRANCH - Git branch name
  • DEBUG_MODE - Debug mode flag (skip table writes if True)
  • DELAYED_NOTIFY_CALLED - Flag to prevent duplicate delayed notify calls

Testing​

Local Testing​

File: functions/callback/notify.py (lines 58-106)

if __name__ == "__main__":
import json
from src.credit_card_callback_processor import CreditCardCallbackProcessor

# Enable debug mode
os.environ["DEBUG_MODE"] = "true"
os.environ["BRANCH"] = "master"

# Sample input
sample_body = {
"id": "chrg_test_EXAMPLE2",
"object": "charge",
"amount": 1583.0,
"currency": "THB"
}

event = {"body": json.dumps(sample_body)}
result = lambda_handler(event, None)

Test Event Example​

{
"body": "{\"id\": \"chrg_test_EXAMPLE2\", \"object\": \"charge\", \"amount\": 1583.0, \"currency\": \"THB\", \"status\": \"success\"}"
}

Code Structure​

File Organization:

functions/callback/
├── notify.py # Main handler
└── src/
├── checksum_handler.py # Checksum verification
├── credit_card_callback_processor.py # Callback processor
├── delayed_notify_handler.py # Delayed notify invocation
├── notify_processor.py # Error handling
└── credit_card_notify_table.py # Notification table
  • DelayedNotify - Called after processing completes
  • ProcessPaidOrder - Processes successfully paid orders
  • Callback - Handles 3D Secure callbacks
  • Checksum Documentation: functions/callback/docs/CHECKSUM_MARKING_DOCUMENTATION.md

Common Patterns​

Checksum Verification Pattern​

# Verify checksum FIRST before any other processing
checksum_valid, checksum_error, charge_id = verify_and_handle_checksum(
event=event,
function_name="notify",
branch=BRANCH,
debug_mode=DEBUG_MODE
)

Delayed Notify Pattern​

# Call delayed notify AFTER all processing is complete (only once)
call_delayed_notify(event, BRANCH, DEBUG_MODE)

Troubleshooting​

Common Issues​

  1. Checksum Verification Failures

    • Check KBank secret keys in Secrets Manager
    • Verify checksum algorithm matches KBank specification
    • Check CloudWatch logs for checksum calculation details
  2. Card Payment Record Not Found

    • Verify chargeId exists in CardPaymentRecordTable
    • Check if record was created in master table
    • Verify chargeId matches between CardPayment and Notify
  3. Delayed Notify Not Called

    • Check DELAYED_NOTIFY_CALLED flag is reset
    • Verify Lambda invocation permissions
    • Check CloudWatch logs for invocation errors

Debugging​

  • Check CloudWatch logs for checksum verification details
  • Review CallbackErrorLogTable for error history
  • Check Sentry for exception tracking
  • Verify CreditCardNotifyTable records are being saved
  • Test with known good charge IDs

References​

  • Template.yaml: Lines 348-413
  • Checksum Documentation: functions/callback/docs/CHECKSUM_MARKING_DOCUMENTATION.md
  • Related Functions: DelayedNotify, ProcessPaidOrder, Callback