collect method

void collect({
  1. required BuildContext context,
  2. required String collectRequestId,
  3. required void onSuccess(
    1. String collectRequestId
    ),
  4. required VoidCallback onError,
})

Implementation

void collect({
  required BuildContext context,
  required String collectRequestId,
  required void Function(String collectRequestId) onSuccess,
  required VoidCallback onError,
}) {
  final prefix = mode == EdvironMode.production ? 'pg' : 'dev.pg';
  final collectUrl =
      'https://$prefix.edviron.com/collect-sdk-payments?collect_id=$collectRequestId';

  final controller = WebViewController()
    ..setJavaScriptMode(JavaScriptMode.unrestricted)
    ..setNavigationDelegate(
      NavigationDelegate(
        onNavigationRequest: (request) async {
          final url = request.url;
          final uri = Uri.parse(url);
          final scheme = uri.scheme.toLowerCase();

          debugPrint('URL: $url');
          debugPrint('URI: $uri');
          debugPrint('Scheme: $scheme');

          const externalSchemes = [
            'upi',
            'tez',
            'phonepe',
            'paytmmp',
            'gpay',
            'bhim',
            'amazonpay',
            'mobikwik',
            'freecharge',
            'intent',
          ];

          if (externalSchemes.contains(scheme) || scheme.isEmpty) {
            if (await canLaunchUrl(uri)) {
              debugPrint('Launching URL: $url');
              await launchUrl(uri, mode: LaunchMode.externalApplication);
            }
            return NavigationDecision.prevent;
          }

          if (scheme != 'http' && scheme != 'https') {
            if (await canLaunchUrl(uri)) {
              debugPrint('Launching URL: $url');

              await launchUrl(uri, mode: LaunchMode.externalApplication);
            }
            return NavigationDecision.prevent;
          }

          if (url.contains('payment-success')) {
            if (context.mounted) {
              Navigator.of(context).pop();
              onSuccess(collectRequestId);
            }
            return NavigationDecision.prevent;
          } else if (url.contains('payment-failure')) {
            if (context.mounted) {
              Navigator.of(context).pop();
              onError();
            }
            return NavigationDecision.prevent;
          }

          return NavigationDecision.navigate;
        },
      ),
    )
    ..loadRequest(Uri.parse(collectUrl));

  Navigator.of(context).push(
    MaterialPageRoute(
      builder: (_) => Scaffold(
        appBar: AppBar(
          title: const Text("Complete Payment"),
        ),
        body: WebViewWidget(controller: controller),
      ),
    ),
  );
}