openUpiPayment method

Future<void> openUpiPayment(
  1. String appName
)

Launch UPI application

Implementation

Future<void> openUpiPayment(String appName) async {
  selectedUpiApp.value = appName;
  statusRx.value = PayerMaxStatusModel.processing();

  try {
    String packageId = "";
    if (appName == "Google Pay" || appName == "GPay") {
      packageId = "com.google.android.apps.nbu.paisa.user";
    } else if (appName == "PhonePe") {
      packageId = "com.phonepe.app";
    } else if (appName == "Paytm") {
      packageId = "net.one97.paytm";
    } else if (appName == "BHIM UPI" || appName == "BHIM") {
      packageId = "in.org.npci.upiapp";
    }

    String targetUrl = upiUri.value;
    if (appName == "PhonePe") {
      targetUrl = upiUri.value.replaceFirst("upi://", "phonepe://");
    } else if (appName == "Paytm") {
      targetUrl = upiUri.value.replaceFirst("upi://", "paytmmp://");
    }

    final uri = Uri.parse(targetUrl);
    final genericUri = Uri.parse(upiUri.value);

    bool launched = false;

    // 1. Try launching direct app intent
    try {
      if (await canLaunchUrl(uri)) {
        launched = await launchUrl(uri, mode: LaunchMode.externalApplication);
      }
    } catch (_) {}

    // 2. Fallback to generic upi://
    if (!launched && (appName == "UPI App" || appName == "Google Pay" || appName == "GPay")) {
      try {
        if (await canLaunchUrl(genericUri)) {
          launched = await launchUrl(genericUri, mode: LaunchMode.externalApplication);
        }
      } catch (_) {}
    }

    // 3. Fallback to redirectUrl if available and deep link failed
    if (!launched && redirectUrl.value.isNotEmpty) {
      try {
        final webUri = Uri.parse(redirectUrl.value);
        if (await canLaunchUrl(webUri)) {
          launched = await launchUrl(webUri, mode: LaunchMode.inAppBrowserView);
        }
      } catch (_) {}
    }

    // 4. Prompt to install from Play Store if app not found
    if (!launched) {
      statusRx.value = PayerMaxStatusModel.waiting();
      Get.defaultDialog(
        title: "$appName Not Installed",
        titleStyle: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
        middleText: "$appName is not installed on your phone. Would you like to install it from Google Play Store?",
        middleTextStyle: const TextStyle(fontSize: 13, color: Colors.black87),
        textConfirm: "Install $appName",
        textCancel: "Cancel",
        confirmTextColor: Colors.white,
        buttonColor: const Color(0xFF5B247A),
        cancelTextColor: Colors.black54,
        onConfirm: () async {
          Get.back();
          if (packageId.isNotEmpty) {
            final playStoreUri = Uri.parse("https://play.google.com/store/apps/details?id=$packageId");
            await launchUrl(playStoreUri, mode: LaunchMode.externalApplication);
          }
        },
      );
    }
  } catch (e) {
    debugPrint("Could not launch UPI app: $e");
  }
}