pay method

Future<void> pay(
  1. String orderId, {
  2. required PaymentCompletionCallback onFinish,
  3. required PaymentErrorCallback onError,
})

Initiates and manages the complete payment flow for a specific order.

This method handles the entire payment process:

  1. Validates the order ID and fetches payment details
  2. Opens a secure in-app browser with the payment URL
  3. Monitors the payment process for completion or errors
  4. Calls appropriate callbacks based on the outcome

Parameters:

  • orderId: The unique identifier for the payment order
  • onFinish: Callback invoked when payment completes successfully
  • onError: Callback invoked if any error occurs during the process

The onError callback receives a PaymentException with detailed error information. Common error scenarios include:

  • Invalid order ID (ERR_PAYMENT_ORDER_NOT_FOUND)
  • Network connectivity issues
  • API errors (authentication, server errors)
  • Invalid response formats

Example:

await paymentService.pay(
  'order-123',
  onFinish: () => showSuccessMessage(),
  onError: (error) => handleError(error),
);

Implementation

Future<void> pay(
  String orderId, {
  required PaymentCompletionCallback onFinish,
  required PaymentErrorCallback onError,
}) async {
  try {
    // Fetch payment details from the provider
    final paymentDetails = await paymentDetailsProvider.getPaymentDetails(
      orderId,
      paymentEnvironment,
    );

    // Create and configure the payment browser with required URLs and callbacks
    final paymentBrowser = PaymentBrowser(
      paymentUrl: paymentDetails.getWebUrl ?? '',
      redirectUrl: paymentDetails.redirectUrl ?? '',
      onFinishCallback: onFinish,
      onUrlChange: (url) {
        // Optional: Handle URL changes if needed for tracking or validation
      },
    );

    // Open the payment browser and start the payment process
    await paymentBrowser.open();
  } on PaymentException catch (e) {
    onError(e);
  } catch (e) {
    onError(PaymentException('Unexpected error occurred: $e'));
  }
}