ProcessPaidAmexOrderInternal Lambda Function
Quick Reference
- Function Name:
payment3-process-paid-amex-order-internal-${BRANCH} - Handler:
process_paid_amex_internal.lambda_handler - Runtime: Python 3.13 (Docker Image)
- Trigger: Lambda invocation (asynchronous)
- Timeout: 200 seconds
- Template.yaml: Lines 868-916
Function Overview
The ProcessPaidAmexOrderInternal function processes paid orders for American Express payments. It is invoked internally by the AmexCallback function to handle order processing after payment confirmation. This function recalculates order costs, creates payment headers, sends notifications, and logs comprehensive processing records to AmexProcessPaidOrderLogTable.
Entry Point
File: functions/processPaidOrder/process_paid_amex_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 = ProcessPaidAmexOrder(orderId, success, payment_id, amount)
processor.save_paid_order()
processor.save_process_paid_order()
processor.send_notification(success)
# Logs comprehensive processing record to AmexProcessPaidOrderLogTable
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_amex_abc123",
"amount": 300.0
}
Field Aliases (supported):
orderIdororder_idpaymentIdorpayment_id
Example Event:
{
"orderId": "492500005643",
"success": true,
"paymentId": "pay_amex_abc123",
"amount": 300.0
}
Core Classes
ProcessPaidAmexOrder
Main processor class for handling Amex payment orders.
Initialization:
processor = ProcessPaidAmexOrder(
orderId="492500005643",
success=True,
payment_id="pay_amex_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 Amex payment@cached_property
def payment_header(self) -> dict:
return create_payment_header(
order=self.calculated_order,
paymentId=self.payment_id,
isPaid=self.success,
paymentMethod="amex",
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
AmexProcessPaidOrderLogTable
Table Name: payment3-process-paid-amex-order-internal-log-${BRANCH}
Access Pattern: Put item
Schema:
orderId(hash_key)created_at(range_key)payment_id: Payment identifiersuccess: Success booleanamount: Payment amountpayment_type: "amex"log_level: "INFO" or "ERROR"message: Log messagedata(JSON): Processing datais_error: Error flagerror_details(JSON): Error details if error occurred
GSI: payment_id-index for querying by payment_id
Lambda Invocations
Invoked Functions
calculate-cost-3-master: Recalculates order costs including shipping and discounts
Invoked By
AmexCallback: After Amex payment callback
Process Flow
- Receive Lambda Invocation: Function receives event with orderId, success, paymentId, amount
- Parse Event: Extract and validate required fields
- Initialize Processing Events Tracking: Start tracking processing events
- Check Already Paid: Skip if order.payment.isPaid is True
- Initialize Processor: Create ProcessPaidAmexOrder instance
- Recalculate Order Cost: Invoke CalculateCost Lambda to get updated costs
- Create Payment Header: Build payment header with Amex payment details
- Save Order: Update OrderTable with payment information
- Log Processing: Record in ProcessPaidOrderTable
- Send Notifications: Send success/failure notifications and email
- Log Comprehensive Record: Log to AmexProcessPaidOrderLogTable with all processing events
- 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 both ProcessPaidOrderTable and AmexProcessPaidOrderLogTable
- Comprehensive Logging: All processing events are tracked and logged to AmexProcessPaidOrderLogTable
- Exception Propagation: All exceptions are caught, logged, and returned as HTTP 500
IAM Policies
Required Permissions:
DynamoDBReadPolicyonCardPaymentRecordTableDynamoDBReadPolicyonCheckStatusTableDynamoDBCrudPolicyonProcessPaidOrderTableDynamoDBCrudPolicyonAmexProcessPaidOrderLogTableDynamoDBCrudPolicyonEmailLogTableDynamoDBReadPolicyonorder-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 and comprehensive processing event tracking.
Comprehensive Logging
The function logs detailed processing records to AmexProcessPaidOrderLogTable including:
- Processing start/end times
- All processing events
- Final status (success/error)
- Error details if applicable
- Payment information
Related Functions
ProcessPaidOrderInternal: QR and Card payment processingProcessPaidWalletOrderInternal: Wallet payment processingAmexCallback: Invokes this function after Amex callback
Notes
- This function handles Amex payments only
- Order costs are recalculated before processing
- Payment amount comes from the callback event
- Comprehensive logging to AmexProcessPaidOrderLogTable for audit trail
- Similar structure to ProcessPaidWalletOrderInternal but with additional logging