display method

Future<void> display()

Implementation

Future<void> display() async {
  try {
    _openLoader();
    // 1. Fetch Session Data
    final responseData = await fetchSessionDataFromApi(token);
    final checkoutStatus = extractCheckoutStatus(responseData);
    if (checkoutStatus.$1 == 'PAID' || checkoutStatus.$1 == 'SUCCESS' || checkoutStatus.$1 == 'APPROVED') {
      _closeLoader();
      onPaymentResult(PaymentResultObject('SUCCESS', checkoutStatus.$2 ?? ""));
      return;
    }
    if(checkoutStatus.$1 == 'EXPIRED') {
      _closeLoader();
      onPaymentResult(PaymentResultObject('EXPIRED', checkoutStatus.$2 ?? ""));
      return;
    }
    final referrer = extractReferer(responseData);
    final merchantDetails = extractMerchantDetails(responseData);
    final backurl = extractBackURL(responseData);
    final enabledFields = extractEnabledFields(responseData);
    final shopperDetails = extractShopperDetails(responseData);
    bool isValidShopperDetails = isShopperValid(shopperDetails, enabledFields);

    // 2. Prepare UPI Data
    final upiApps = await UPIAppDetector.getInstalledUpiApps();

    const upiAppMappings = {
      'gpay': 'gp=1',
      'paytm': 'pm=1',
      'phonepe': 'pp=1',
      'bhim': 'bm=1',
      'amazon_pay': 'ap=1',
      'mobikwik': 'mk=1',
      'bharatpe': 'bp=1',
      'jupiter': 'jp=1',
      'pop': 'pu=1',
    };

    final upiAppsString = upiAppMappings.entries
        .where((entry) => upiApps.contains(entry.key))
        .map((entry) => entry.value)
        .join('&');

    await storeMerchantDetailsAndReturnUrlInSharedPreferences(merchantDetails, backurl);

    // 3. FETCH RECOMMENDED INSTRUMENTS
    // Only attempt if we have a shopperToken (usually required for saved cards)
    Map<String, dynamic>? recommendedInstrument;
    if (shopperToken.isNotEmpty) {
      try {
        String uniqueRef = extractUniqueRef(responseData);
        recommendedInstrument = await fetchRecommendedInstruments(uniqueRef);
      } catch (e) {
        _showErrorDialog();
      }
    }

    // 4. LOGIC: Show Swipe UI OR Go to WebView
    if (recommendedInstrument != null && recommendedInstrument.isNotEmpty && isValidShopperDetails) {
      // Show the native Swipe to Pay UI
      final merchantSettingsButtonColor = merchantDetails['checkoutTheme']['primaryButtonColor'] ?? Color(0xFF000000);
      final buttonColor = Color(
            int.parse(merchantSettingsButtonColor.substring(1, 7), radix: 16) + 0xFF000000);
            _closeLoader();
      _showSwipeToPayModal(
        instrument: recommendedInstrument,
        merchantColor: buttonColor,
        amount: extractAmount(responseData),
        upiApps: upiAppsString,
        referrer: referrer,
        shopperDetails: shopperDetails
      );
    } else {
      // No saved card? Go straight to WebView
      _closeLoader();
      _navigateToWebView(upiAppsString, referrer);
    }
  } catch (e) {
    _closeLoader();
    _showErrorDialog();
  }
}