Skip to main content

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

  • orderId or order_id
  • paymentId or payment_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 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

Schema:

  • orderId (hash_key)
  • created_at (range_key)
  • data (JSON): Calculated order data
  • is_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 callback
  • BankAppCallback: After bank app 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. Check Already Paid: Skip if order.payment.isPaid is True
  4. Initialize Processor: Create ProcessPaidWalletOrder instance
  5. Recalculate Order Cost: Invoke CalculateCost Lambda to get updated costs
  6. Create Payment Header: Build payment header with wallet payment details
  7. Save Order: Update OrderTable with payment information
  8. Log Processing: Record in ProcessPaidOrderTable
  9. Send Notifications: Send success/failure notifications and email
  10. 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:

  • DynamoDBReadPolicy on CardPaymentRecordTable
  • DynamoDBReadPolicy on CheckStatusTable
  • DynamoDBCrudPolicy on ProcessPaidOrderTable
  • 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 for troubleshooting.

  • ProcessPaidOrderInternal: QR and Card payment processing
  • ProcessPaidAmexOrderInternal: Amex payment processing
  • WalletCallback: Invokes this function after wallet callback
  • BankAppCallback: 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