Skip to main content

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):

  • orderId or order_id
  • paymentId or payment_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 OrderTable
  • save_process_paid_order(): Logs processing attempt to ProcessPaidOrderTable
  • send_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 identifier
  • success: Success boolean
  • amount: Payment amount
  • payment_type: "amex"
  • log_level: "INFO" or "ERROR"
  • message: Log message
  • data (JSON): Processing data
  • is_error: Error flag
  • error_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

  1. Receive Lambda Invocation: Function receives event with orderId, success, paymentId, amount
  2. Parse Event: Extract and validate required fields
  3. Initialize Processing Events Tracking: Start tracking processing events
  4. Check Already Paid: Skip if order.payment.isPaid is True
  5. Initialize Processor: Create ProcessPaidAmexOrder instance
  6. Recalculate Order Cost: Invoke CalculateCost Lambda to get updated costs
  7. Create Payment Header: Build payment header with Amex payment details
  8. Save Order: Update OrderTable with payment information
  9. Log Processing: Record in ProcessPaidOrderTable
  10. Send Notifications: Send success/failure notifications and email
  11. Log Comprehensive Record: Log to AmexProcessPaidOrderLogTable with all processing events
  12. 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:

  • DynamoDBReadPolicy on CardPaymentRecordTable
  • DynamoDBReadPolicy on CheckStatusTable
  • DynamoDBCrudPolicy on ProcessPaidOrderTable
  • DynamoDBCrudPolicy on AmexProcessPaidOrderLogTable
  • DynamoDBCrudPolicy on EmailLogTable
  • DynamoDBReadPolicy on order-table-dev
  • LambdaInvokePolicy on payment3-check-status-${BRANCH}
  • LambdaInvokePolicy on Pay function
  • LambdaInvokePolicy on calculate-cost-3-master
  • SESCrudPolicy on *
  • SNS:Publish on *
  • AWSSecretsManagerGetSecretValuePolicy on KBank secrets

Environment Variables

  • BRANCH: Deployment branch name (default: "dev")

Dependencies

  • src.tables.*: DynamoDB table models
  • src.updatePaymentHeader: Payment header creation
  • src.savePaidOrder: Order saving logic
  • src.notifications.*: Notification sending
  • src.calculatecost.invokeCalculateCost: Cost calculation
  • lambdasdk.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
  • ProcessPaidOrderInternal: QR and Card payment processing
  • ProcessPaidWalletOrderInternal: Wallet payment processing
  • AmexCallback: 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