handleTransaction method

Future<Map<String, dynamic>> handleTransaction({
  1. required String email,
  2. required int amount,
  3. required String callbackUrl,
  4. String? reference,
  5. List<String>? channels,
  6. String currency = 'NGN',
  7. required Future<PaystackTransactionResult> openWebView(
    1. String authorizationUrl
    ),
})

Handles the payment process and verifies the transaction automatically.

This method performs the following steps:

  1. Initializes the transaction.
  2. Handles the WebView interaction.
  3. Verifies the transaction after completion.
  4. Returns the result to the user.

Implementation

Future<Map<String, dynamic>> handleTransaction({
  required String email,
  required int amount,
  required String callbackUrl,
  String? reference,
  List<String>? channels,
  String currency = 'NGN',
  required Future<PaystackTransactionResult> Function(String authorizationUrl)
      openWebView,
}) async {
  try {
    // Step 1: Initialize transaction
    final initResponse = await initializeTransaction(
      email: email,
      amount: amount,
      callbackUrl: callbackUrl,
      reference: reference,
      channels: channels,
      currency: currency,
    );

    final authorizationUrl = initResponse.data?['authorization_url'];
    final transactionReference = initResponse.data?['reference'];

    if (authorizationUrl == null || transactionReference == null) {
      throw PaystackException('Authorization URL or reference is missing.');
    }

    // Step 2: Handle WebView interaction
    final transactionResult = await openWebView(authorizationUrl);

    // Step 3: Handle different transaction statuses
    if (transactionResult.success) {
      // Step 4: Automatically verify the transaction
      final verificationResponse =
          await verifyTransaction(transactionReference);
      return {
        'status': 'success',
        'message': 'Transaction completed successfully.',
        'data': verificationResponse.data,
      };
    } else if (transactionResult.message == 'Payment Cancelled') {
      return {
        'status': 'cancelled',
        'message': 'Transaction was cancelled by the user.',
        'data': transactionResult,
      };
    } else {
      return {
        'status': 'failed',
        'message': transactionResult.message,
        'data': transactionResult,
      };
    }
  } catch (e) {
    Logger.logError(e.toString());
    return {
      'status': 'error',
      'message': e.toString(),
      'data': null,
    };
  }
}