ProcessPaidWalletOrderInternal Lambda Function
Quick Reference
- Function Name:
payment3-process-paid-wallet-order-internal-${BRANCH} - Handler:
process_paid_wallet_internal.lambda_handler - Runtime: Python 3.13 (Docker Image)
- Trigger: Lambda invocation (asynchronous)
- Timeout: 200 seconds
- Template.yaml: Lines 820-866
Function Overview
The ProcessPaidWalletOrderInternal function processes paid orders for Wallet payments (e.g., KBank Wallet, Bank App). It is invoked internally by callback functions (WalletCallback, BankAppCallback) to handle order processing after payment confirmation. This function recalculates order costs, creates payment headers, and sends notifications.
Entry Point
File: functions/processPaidOrder/process_paid_wallet_internal.py
Handler: lambda_handler(event, context)
def lambda_handler(event, context):
payload = json.loads(event) if isinstance(event, str) else event
orderId = payload.get("orderId")
success = payload.get("success")
payment_id = payload.get("paymentId")
amount = payload.get("amount", 0)
processor = ProcessPaidWalletOrder(orderId, success, payment_id, amount)
processor.save_paid_order()
processor.save_process_paid_order()
processor.send_notification(success)
return {"statusCode": 200, "body": json.dumps("success")}
Event Structure
Lambda Invocation Event
Format: JSON string or dict
Required Fields:
{
"orderId": "492500005643",
"success": true,
"paymentId": "pay_wallet_abc123",
"amount": 300.0
}
Field Aliases (supported):
orderIdororder_idpaymentIdorpayment_id
Example Event:
{
"orderId": "492500005643",
"success": true,
"paymentId": "pay_wallet_abc123",
"amount": 300.0
}
Core Classes
ProcessPaidWalletOrder
Main processor class for handling wallet payment orders.
Initialization:
processor = ProcessPaidWalletOrder(
orderId="492500005643",
success=True,
payment_id="pay_wallet_abc123",
amount=300.0
)
Properties:
-
order(cached_property): Retrieves order from OrderTable -
calculated_order(cached_property): Recalculates order cost using CalculateCost Lambda@cached_property
def calculated_order(self) -> dict:
result = invokeCalculateCost(self.order)
order = result["body"]
order["basketName"] = str(self.orderId)
order["orderDate"] = round(datetime.now().timestamp())
return order -
payment_header(cached_property): Creates payment header for wallet payment@cached_property
def payment_header(self) -> dict:
return create_payment_header(
order=self.calculated_order,
paymentId=self.payment_id,
isPaid=self.success,
paymentMethod="wallet",
totalPaid=self.amount
)
Methods:
save_paid_order(): Saves order with payment header to OrderTablesave_process_paid_order(): Logs processing attempt to ProcessPaidOrderTablesend_notification(is_success: bool): Sends success/failure notifications and email
DynamoDB Tables
OrderTable
Table Name: order-table-dev (shared)
Access Pattern: Get by orderId (hash key)
ProcessPaidOrderTable
Table Name: payment3-process-paid-order-${BRANCH}
Access Pattern: Put item
Schema:
orderId(hash_key)created_at(range_key)data(JSON): Calculated order datais_error(boolean): Error flag
Lambda Invocations
Invoked Functions
calculate-cost-3-master: Recalculates order costs including shipping and discounts
Invoked By
WalletCallback: After wallet payment callbackBankAppCallback: After bank app payment callback
Process Flow
- Receive Lambda Invocation: Function receives event with orderId, success, paymentId, amount
- Parse Event: Extract and validate required fields
- Check Already Paid: Skip if order.payment.isPaid is True
- Initialize Processor: Create ProcessPaidWalletOrder instance
- Recalculate Order Cost: Invoke CalculateCost Lambda to get updated costs
- Create Payment Header: Build payment header with wallet payment details
- Save Order: Update OrderTable with payment information
- Log Processing: Record in ProcessPaidOrderTable
- Send Notifications: Send success/failure notifications and email
- Return Success: Return HTTP 200
Error Handling
- Validation Errors: Raises ValueError for missing required fields
- Order Not Found: Raises exception if order doesn't exist
- CalculateCost Errors: Raises exception if cost calculation fails
- Error Logging: Errors are logged to ProcessPaidOrderTable with
is_error=True - Exception Propagation: All exceptions are caught, logged, and returned as HTTP 500
IAM Policies
Required Permissions:
DynamoDBReadPolicyonCardPaymentRecordTableDynamoDBReadPolicyonCheckStatusTableDynamoDBCrudPolicyonProcessPaidOrderTableDynamoDBCrudPolicyonEmailLogTableDynamoDBReadPolicyonorder-table-devLambdaInvokePolicyonpayment3-check-status-${BRANCH}LambdaInvokePolicyonPayfunctionLambdaInvokePolicyoncalculate-cost-3-masterSESCrudPolicyon*SNS:Publishon*AWSSecretsManagerGetSecretValuePolicyon KBank secrets
Environment Variables
BRANCH: Deployment branch name (default: "dev")
Dependencies
src.tables.*: DynamoDB table modelssrc.updatePaymentHeader: Payment header creationsrc.savePaidOrder: Order saving logicsrc.notifications.*: Notification sendingsrc.calculatecost.invokeCalculateCost: Cost calculationlambdasdk.lambdasdk.Lambda: Lambda invocation
Debug Logging
The function includes comprehensive debug logging via debug_log() helper for troubleshooting.
Related Functions
ProcessPaidOrderInternal: QR and Card payment processingProcessPaidAmexOrderInternal: Amex payment processingWalletCallback: Invokes this function after wallet callbackBankAppCallback: Invokes this function after bank app callback
Notes
- This function handles Wallet payments only
- Order costs are recalculated before processing
- Payment amount comes from the callback event
- Similar structure to ProcessPaidAmexOrderInternal but for wallet payments