Skip to main content

tap_to_pay_fortis 0.0.1 copy "tap_to_pay_fortis: ^0.0.1" to clipboard
tap_to_pay_fortis: ^0.0.1 copied to clipboard

PlatformiOS

Flutter plugin for Fortis Tap to Pay on iPhone (Apple ProximityReader) with automatic token management, keychain caching, and REST API integration.

example/lib/main.dart

import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:tap_to_pay_fortis/tap_to_pay_fortis.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  try {
    await dotenv.load(fileName: '.env');
  } catch (e) {
    debugPrint('dotenv could not load: $e');
  }
  runApp(
    const MaterialApp(
      debugShowCheckedModeBanner: false,
      home: FortisTapToPayExample(),
    ),
  );
}

class FortisTapToPayExample extends StatefulWidget {
  const FortisTapToPayExample({super.key});

  @override
  State<FortisTapToPayExample> createState() => _FortisTapToPayExampleState();
}

class _FortisTapToPayExampleState extends State<FortisTapToPayExample> {
  final _plugin = TapToPayFortis.instance;
  StreamSubscription<TapToPayEvent>? _eventSubscription;

  bool _isSupported = false;
  bool _isReaderReady = false;
  bool _isLoading = false;
  bool _isGeneratingToken = false;
  String _statusMessage = 'Checking device compatibility...';
  String _cachedTokenStatus = 'None';
  final List<String> _eventLogs = [];

  // Error tracking state
  String? _lastErrorTitle;
  String? _lastErrorDetails;

  // Fortis API credentials loaded dynamically from .env
  late final TextEditingController _userIdController;
  late final TextEditingController _userApiKeyController;
  late final TextEditingController _developerIdController;
  late final TextEditingController _locationIdController;
  late final TextEditingController _productTxIdController;

  final _tokenController = TextEditingController();
  final _amountController = TextEditingController(text: '10.50');
  FortisEnvironment _environment = FortisEnvironment.sandbox;
  TapToPayReadResult? _lastReadResult;

  @override
  void initState() {
    super.initState();
    _userIdController = TextEditingController(
      text: dotenv.env['FORTIS_USER_ID'] ?? '',
    );
    _userApiKeyController = TextEditingController(
      text: dotenv.env['FORTIS_USER_API_KEY'] ?? '',
    );
    _developerIdController = TextEditingController(
      text: dotenv.env['FORTIS_DEVELOPER_ID'] ?? '',
    );
    _locationIdController = TextEditingController(
      text: dotenv.env['FORTIS_LOCATION_ID'] ?? '',
    );
    _productTxIdController = TextEditingController(
      text: dotenv.env['FORTIS_PRODUCT_TRANSACTION_ID'] ?? '',
    );

    final envStr = dotenv.env['FORTIS_ENVIRONMENT']?.toLowerCase();
    if (envStr == 'production') {
      _environment = FortisEnvironment.production;
    } else {
      _environment = FortisEnvironment.sandbox;
    }

    _checkSupportAndCachedToken();
    _subscribeToReaderEvents();
  }

  @override
  void dispose() {
    _eventSubscription?.cancel();
    _userIdController.dispose();
    _userApiKeyController.dispose();
    _developerIdController.dispose();
    _locationIdController.dispose();
    _productTxIdController.dispose();
    _tokenController.dispose();
    _amountController.dispose();
    super.dispose();
  }

  void _log(String text) {
    debugPrint('[TapToPayExample] $text');
    setState(() {
      _eventLogs.insert(
        0,
        '${DateTime.now().toIso8601String().substring(11, 19)} - $text',
      );
      if (_eventLogs.length > 60) _eventLogs.removeLast();
    });
  }

  void _recordError(String title, Object error, [StackTrace? stackTrace]) {
    String message = error.toString();
    String details = '';

    if (error is PlatformException) {
      details = 'Code: ${error.code}\nMessage: ${error.message}\nDetails: ${error.details ?? "None"}';
      message = '[${error.code}] ${error.message}';
    } else if (error is FortisApiException) {
      details = 'HTTP ${error.statusCode} ${error.method} ${error.uri}\nMessage: ${error.message}\n\nResponse Body:\n${error.responseBody}';
      message = 'HTTP ${error.statusCode}: ${error.message}';
    } else if (error is HttpException) {
      details = 'HttpException: ${error.message} (uri: ${error.uri})';
      message = error.message;
    } else {
      details = error.toString();
    }

    if (stackTrace != null) {
      details += '\n\nStack:\n$stackTrace';
    }

    debugPrint('==================== [ERROR: $title] ====================');
    debugPrint(details);
    debugPrint('========================================================');

    _log('ERROR [$title]: $message');

    setState(() {
      _lastErrorTitle = title;
      _lastErrorDetails = details;
      _statusMessage = 'Error: $message';
    });

    if (!mounted) return;
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text('$title: $message'),
        backgroundColor: Colors.red.shade800,
        duration: const Duration(seconds: 5),
        action: SnackBarAction(
          label: 'COPY',
          textColor: Colors.white,
          onPressed: () {
            Clipboard.setData(ClipboardData(text: details));
          },
        ),
      ),
    );
  }

  Future<void> _checkSupportAndCachedToken() async {
    try {
      final supported = await _plugin.isSupported();
      final cachedToken = await _plugin.getCachedToken();

      setState(() {
        _isSupported = supported;
        if (cachedToken != null) {
          final isExpired = cachedToken['isExpired'] == true;
          _cachedTokenStatus = isExpired
              ? 'Expired'
              : 'Valid (Stored in Keychain)';
          if (!isExpired && cachedToken['token'] != null) {
            _tokenController.text = cachedToken['token'] as String;
          }
        } else {
          _cachedTokenStatus = 'No token cached';
        }
        _statusMessage = supported
            ? 'Tap to Pay on iPhone is supported!'
            : 'Device or OS does not support Tap to Pay (requires iPhone XS+, iOS 17+)';
      });
    } on PlatformException catch (e, stack) {
      _recordError('Compatibility Check', e, stack);
    }
  }

  void _subscribeToReaderEvents() {
    _eventSubscription = _plugin.events.listen((event) {
      _log(
        'Event: ${event.type.name} ${event.progress != null ? "(${event.progress}%)" : ""}',
      );

      setState(() {
        switch (event.type) {
          case TapToPayEventType.preparing:
            _statusMessage = 'Preparing reader: ${event.progress ?? 0}%';
            _isReaderReady = false;
            break;
          case TapToPayEventType.ready:
            _statusMessage = 'Reader is ready to take payments!';
            _isReaderReady = true;
            break;
          case TapToPayEventType.readyForTap:
            _statusMessage = 'Apple sheet presented: Tap card or iPhone';
            break;
          case TapToPayEventType.cardDetected:
            _statusMessage = 'Card detected... Hold still';
            break;
          case TapToPayEventType.removeCard:
            _statusMessage = 'Card read: Please remove card';
            break;
          case TapToPayEventType.readResultReceived:
            _statusMessage =
                'Cryptogram received! Ready for payment authorization';
            break;
          case TapToPayEventType.userInterfaceDismissed:
            _statusMessage = 'Apple sheet dismissed. Safe to update UI.';
            break;
          case TapToPayEventType.appForegrounded:
            _log('Application returned to foreground (Application Switching)');
            break;
          case TapToPayEventType.appBackgrounded:
            _log(
              'Application sent to background (Session invalidated by Apple)',
            );
            _isReaderReady = false;
            break;
          case TapToPayEventType.sessionRestored:
            _log('Session automatically restored from Keychain token');
            _isReaderReady = true;
            break;
          case TapToPayEventType.sessionRestoreFailed:
            _log('Session restore failed: ${event.message}');
            break;
          case TapToPayEventType.error:
            _recordError(
              'Apple Reader Event Error',
              'Code: ${event.code}\nMessage: ${event.message}\nDetails: ${event.details ?? "None"}',
            );
            break;
          default:
            break;
        }
      });
    });
  }

  /// Step 1: Generate Payment Card Reader Token from Fortis API
  Future<String?> _generateTokenOnly() async {
    final userId = _userIdController.text.trim();
    final userApiKey = _userApiKeyController.text.trim();
    final developerId = _developerIdController.text.trim();
    var productTxId = _productTxIdController.text.trim();
    if (productTxId.isEmpty) {
      productTxId = _locationIdController.text.trim();
      _productTxIdController.text = productTxId;
    }

    if (userId.isEmpty || userApiKey.isEmpty || productTxId.isEmpty) {
      _recordError(
        'Input Validation Error',
        'User ID, User API Key, and Product Transaction ID are required.',
      );
      return null;
    }

    setState(() {
      _isGeneratingToken = true;
      _lastErrorTitle = null;
      _lastErrorDetails = null;
    });

    _log('Calling GET /v1/payment-card-reader-token?product_transaction_id=$productTxId (${_environment.name})...');

    try {
      final token = await _plugin.generateToken(
        productTransactionId: productTxId,
        userId: userId,
        userApiKey: userApiKey,
        developerId: developerId.isNotEmpty ? developerId : null,
        environment: _environment,
      );

      _tokenController.text = token;
      _log('SUCCESS: Generated Token (${token.substring(0, 25)}...)');

      if (!mounted) return token;
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('Payment Card Reader Token successfully generated!'),
          backgroundColor: Colors.green,
        ),
      );
      return token;
    } catch (e, stack) {
      _recordError('Fortis Token API Error', e, stack);
      return null;
    } finally {
      setState(() => _isGeneratingToken = false);
    }
  }

  /// Step 2: Initialize Apple ProximityReader session with the token
  Future<bool> _prepareReaderManually() async {
    final token = _tokenController.text.trim();
    if (token.isEmpty) {
      _recordError(
        'Prepare Reader',
        'Please generate or enter a Payment Card Reader Token first.',
      );
      return false;
    }

    setState(() {
      _isLoading = true;
      _lastErrorTitle = null;
      _lastErrorDetails = null;
    });

    try {
      _log('Calling Apple ProximityReader prepare()...');
      final success = await _plugin.prepareReader(token: token);
      _log('Apple prepareReader returned: $success');
      setState(() {
        _cachedTokenStatus = 'Valid (Stored in Keychain for 24h)';
      });
      return success;
    } on PlatformException catch (e, stack) {
      _recordError('Apple Reader Prepare Failed', e, stack);
      return false;
    } catch (e, stack) {
      _recordError('Prepare Reader Error', e, stack);
      return false;
    } finally {
      setState(() => _isLoading = false);
    }
  }

  /// Prompts merchant to accept Apple Terms and Conditions on device
  Future<bool> _linkAccountManually() async {
    final token = _tokenController.text.trim();
    if (token.isEmpty) {
      _recordError(
        'Apple Terms & Conditions',
        'Please generate a token first before accepting Apple Terms & Conditions.',
      );
      return false;
    }

    setState(() {
      _isLoading = true;
      _lastErrorTitle = null;
      _lastErrorDetails = null;
    });

    try {
      _log('Calling Apple ProximityReader linkAccount()...');
      final success = await _plugin.linkAccount(token: token);
      _log('Apple linkAccount returned: $success');
      if (!mounted) return success;
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('Apple Terms & Conditions accepted! You can now prepare the reader.'),
          backgroundColor: Colors.green,
        ),
      );
      return success;
    } on PlatformException catch (e, stack) {
      _recordError('Apple Terms Acceptance Failed', e, stack);
      return false;
    } catch (e, stack) {
      _recordError('Terms Acceptance Error', e, stack);
      return false;
    } finally {
      setState(() => _isLoading = false);
    }
  }

  /// Combined: Generate Token and immediately initialize reader
  Future<void> _generateTokenAndPrepare() async {
    final token = await _generateTokenOnly();
    if (token != null && token.isNotEmpty && _lastErrorDetails == null) {
      await _prepareReaderManually();
    }
  }

  Future<void> _startContactlessPayment() async {
    final amount = double.tryParse(_amountController.text) ?? 10.0;

    setState(() {
      _isLoading = true;
      _lastReadResult = null;
      _lastErrorTitle = null;
      _lastErrorDetails = null;
    });

    try {
      _log('Starting contactless payment sheet for \$$amount USD...');
      final result = await _plugin.readPaymentCard(
        amount: amount,
        currencyCode: 'USD',
      );

      setState(() {
        _lastReadResult = result;
      });

      _log(
        'SUCCESS: Captured cryptogram: ${result.cardDataCryptogram.substring(0, 20)}...',
      );
    } on PlatformException catch (e, stack) {
      _recordError('Card Read Failed', e, stack);
    } catch (e, stack) {
      _recordError('Card Read Error', e, stack);
    } finally {
      setState(() => _isLoading = false);
    }
  }

  Future<void> _clearCachedToken() async {
    await _plugin.clearCachedToken();
    _tokenController.clear();
    setState(() {
      _cachedTokenStatus = 'Cleared';
      _isReaderReady = false;
      _lastErrorTitle = null;
      _lastErrorDetails = null;
    });
    _log('Cleared Keychain token');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Fortis Tap to Pay on iPhone'),
        backgroundColor: const Color(0xFF0F172A),
        foregroundColor: Colors.white,
      ),
      backgroundColor: const Color(0xFFF8FAFC),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // Status Card
            Card(
              elevation: 0,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(12),
                side: BorderSide(
                  color: _isReaderReady
                      ? Colors.green.shade300
                      : Colors.grey.shade300,
                ),
              ),
              color: Colors.white,
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Icon(
                          _isSupported ? Icons.check_circle : Icons.error,
                          color: _isSupported ? Colors.green : Colors.red,
                        ),
                        const SizedBox(width: 8),
                        Text(
                          _isSupported
                              ? 'Supported Device'
                              : 'Unsupported Device',
                          style: const TextStyle(
                            fontWeight: FontWeight.bold,
                            fontSize: 16,
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 8),
                    Text(
                      _statusMessage,
                      style: TextStyle(color: Colors.grey.shade700),
                    ),
                    const Divider(height: 24),
                    Text(
                      'Keychain Token: $_cachedTokenStatus',
                      style: const TextStyle(
                        fontSize: 13,
                        color: Colors.blueGrey,
                      ),
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 16),

            // ERROR DIAGNOSTICS CARD (Shows when any error occurs)
            if (_lastErrorDetails != null) ...[
              Card(
                elevation: 0,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12),
                  side: const BorderSide(color: Colors.red, width: 1.5),
                ),
                color: const Color(0xFFFFF1F2),
                child: Padding(
                  padding: const EdgeInsets.all(14.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          const Icon(Icons.error_outline, color: Colors.red),
                          const SizedBox(width: 8),
                          Expanded(
                            child: Text(
                              _lastErrorTitle ?? 'Error Diagnostics',
                              style: const TextStyle(
                                fontWeight: FontWeight.bold,
                                color: Colors.red,
                                fontSize: 15,
                              ),
                            ),
                          ),
                          IconButton(
                            icon: const Icon(Icons.close, size: 20, color: Colors.red),
                            onPressed: () {
                              setState(() {
                                _lastErrorTitle = null;
                                _lastErrorDetails = null;
                              });
                            },
                          ),
                        ],
                      ),
                      const SizedBox(height: 8),
                      Container(
                        width: double.infinity,
                        padding: const EdgeInsets.all(10.0),
                        decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(8),
                          border: Border.all(color: Colors.red.shade200),
                        ),
                        child: SelectableText(
                          _lastErrorDetails!,
                          style: const TextStyle(
                            fontFamily: 'monospace',
                            fontSize: 12,
                            color: Color(0xFF991B1B),
                          ),
                        ),
                      ),
                      const SizedBox(height: 10),
                      ElevatedButton.icon(
                        onPressed: () {
                          Clipboard.setData(ClipboardData(text: _lastErrorDetails!));
                          ScaffoldMessenger.of(context).showSnackBar(
                            const SnackBar(
                              content: Text('Error diagnostics copied to clipboard!'),
                              backgroundColor: Colors.black87,
                            ),
                          );
                        },
                        icon: const Icon(Icons.copy, size: 16),
                        label: const Text('Copy Diagnostics'),
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.red.shade700,
                          foregroundColor: Colors.white,
                          padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              const SizedBox(height: 16),
            ],

            // Step 1: Fortis Credentials & Token Generator
            Card(
              elevation: 0,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(12),
                side: BorderSide(color: Colors.grey.shade300),
              ),
              color: Colors.white,
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Container(
                          padding: const EdgeInsets.symmetric(
                            horizontal: 8,
                            vertical: 4,
                          ),
                          decoration: BoxDecoration(
                            color: const Color(0xFF2563EB),
                            borderRadius: BorderRadius.circular(6),
                          ),
                          child: const Text(
                            'Step 1',
                            style: TextStyle(
                              color: Colors.white,
                              fontWeight: FontWeight.bold,
                              fontSize: 11,
                            ),
                          ),
                        ),
                        const SizedBox(width: 8),
                        const Expanded(
                          child: Text(
                            'Fortis Token Generation',
                            style: TextStyle(
                              fontWeight: FontWeight.bold,
                              fontSize: 15,
                            ),
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 4),
                    const Text(
                      'GET /v1/payment-card-reader-token?product_transaction_id={id}',
                      style: TextStyle(
                        fontSize: 11,
                        color: Colors.grey,
                        fontFamily: 'monospace',
                      ),
                    ),
                    const SizedBox(height: 12),

                    // Environment Picker
                    Wrap(
                      spacing: 8,
                      runSpacing: 4,
                      crossAxisAlignment: WrapCrossAlignment.center,
                      children: [
                        const Text(
                          'Environment:',
                          style: TextStyle(
                            fontSize: 13,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                        ChoiceChip(
                          label: const Text('Sandbox'),
                          selected: _environment == FortisEnvironment.sandbox,
                          onSelected: (selected) {
                            if (selected) {
                              setState(
                                () => _environment = FortisEnvironment.sandbox,
                              );
                            }
                          },
                        ),
                        ChoiceChip(
                          label: const Text('Production'),
                          selected:
                              _environment == FortisEnvironment.production,
                          onSelected: (selected) {
                            if (selected) {
                              setState(
                                () =>
                                    _environment = FortisEnvironment.production,
                              );
                            }
                          },
                        ),
                      ],
                    ),
                    const SizedBox(height: 12),

                    TextField(
                      controller: _userIdController,
                      decoration: const InputDecoration(
                        labelText: 'User ID (Header: user-id)',
                        border: OutlineInputBorder(),
                        isDense: true,
                      ),
                    ),
                    const SizedBox(height: 10),
                    TextField(
                      controller: _userApiKeyController,
                      obscureText: true,
                      decoration: const InputDecoration(
                        labelText: 'User API Key (Header: user-api-key)',
                        border: OutlineInputBorder(),
                        isDense: true,
                      ),
                    ),
                    const SizedBox(height: 10),
                    TextField(
                      controller: _locationIdController,
                      decoration: const InputDecoration(
                        labelText: 'Location ID',
                        border: OutlineInputBorder(),
                        isDense: true,
                      ),
                    ),
                    const SizedBox(height: 10),
                    TextField(
                      controller: _productTxIdController,
                      decoration: const InputDecoration(
                        labelText: 'Product Transaction ID',
                        border: OutlineInputBorder(),
                        isDense: true,
                      ),
                    ),
                    const SizedBox(height: 10),
                    TextField(
                      controller: _developerIdController,
                      decoration: const InputDecoration(
                        labelText: 'Developer ID (Header: developer-id)',
                        border: OutlineInputBorder(),
                        isDense: true,
                      ),
                    ),
                    const SizedBox(height: 14),

                    // Actions Column
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                      children: [
                        OutlinedButton.icon(
                          onPressed: _isGeneratingToken ? null : _generateTokenOnly,
                          icon: const Icon(Icons.vpn_key),
                          label: const Text('1. Generate Token from Fortis API'),
                          style: OutlinedButton.styleFrom(
                            padding: const EdgeInsets.symmetric(vertical: 12),
                          ),
                        ),
                        const SizedBox(height: 8),
                        ElevatedButton.icon(
                          onPressed: _isGeneratingToken ? null : _generateTokenAndPrepare,
                          icon: _isGeneratingToken
                              ? const SizedBox(
                                  width: 16,
                                  height: 16,
                                  child: CircularProgressIndicator(
                                    strokeWidth: 2,
                                    color: Colors.white,
                                  ),
                                )
                              : const Icon(Icons.flash_on),
                          label: const Text('Generate Token & Prepare Reader'),
                          style: ElevatedButton.styleFrom(
                            backgroundColor: const Color(0xFF2563EB),
                            foregroundColor: Colors.white,
                            padding: const EdgeInsets.symmetric(vertical: 12),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 16),

            // Token Display & Manual Prepare Section
            Card(
              elevation: 0,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(12),
                side: BorderSide(color: Colors.grey.shade300),
              ),
              color: Colors.white,
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text(
                      'Step 2: Active Token & Reader Initialization',
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 14,
                      ),
                    ),
                    const SizedBox(height: 8),
                    TextField(
                      controller: _tokenController,
                      maxLines: 2,
                      decoration: const InputDecoration(
                        border: OutlineInputBorder(),
                        hintText: 'Token will appear here or paste manual JWT',
                        isDense: true,
                      ),
                    ),
                    const SizedBox(height: 10),
                    SizedBox(
                      width: double.infinity,
                      child: ElevatedButton.icon(
                        onPressed: _isLoading ? null : _linkAccountManually,
                        icon: const Icon(Icons.verified_user),
                        label: const Text('Accept Apple Terms & Conditions'),
                        style: ElevatedButton.styleFrom(
                          backgroundColor: const Color(0xFF0F172A),
                          foregroundColor: Colors.white,
                          padding: const EdgeInsets.symmetric(vertical: 12),
                        ),
                      ),
                    ),
                    const SizedBox(height: 8),
                    Row(
                      children: [
                        Expanded(
                          child: OutlinedButton.icon(
                            onPressed: _isLoading ? null : _prepareReaderManually,
                            icon: _isLoading
                                ? const SizedBox(
                                    width: 16,
                                    height: 16,
                                    child: CircularProgressIndicator(
                                      strokeWidth: 2,
                                      color: Colors.blue,
                                    ),
                                  )
                                : const Icon(Icons.nfc),
                            label: const Text('2. Prepare Reader'),
                            style: OutlinedButton.styleFrom(
                              padding: const EdgeInsets.symmetric(vertical: 12),
                            ),
                          ),
                        ),
                        const SizedBox(width: 8),
                        OutlinedButton(
                          onPressed: _clearCachedToken,
                          child: const Text('Clear'),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 16),

            // Step 3: Payment Read Section
            Card(
              elevation: 0,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(12),
                side: BorderSide(color: Colors.grey.shade300),
              ),
              color: Colors.white,
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text(
                      'Step 3: Collect Contactless Payment',
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 15,
                      ),
                    ),
                    const SizedBox(height: 12),
                    TextField(
                      controller: _amountController,
                      keyboardType: const TextInputType.numberWithOptions(
                        decimal: true,
                      ),
                      decoration: const InputDecoration(
                        labelText: 'Transaction Amount (\$ USD)',
                        border: OutlineInputBorder(),
                        prefixText: '\$ ',
                        isDense: true,
                      ),
                    ),
                    const SizedBox(height: 14),
                    SizedBox(
                      width: double.infinity,
                      child: ElevatedButton.icon(
                        onPressed: (_isReaderReady && !_isLoading)
                            ? _startContactlessPayment
                            : null,
                        icon: const Icon(Icons.contactless),
                        label: Text(
                          _isReaderReady
                              ? 'Tap to Pay (\$${_amountController.text})'
                              : 'Prepare Reader First',
                        ),
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.green.shade600,
                          foregroundColor: Colors.white,
                          padding: const EdgeInsets.symmetric(vertical: 14),
                        ),
                      ),
                    ),
                    if (_lastReadResult != null) ...[
                      const Divider(height: 24),
                      const Row(
                        children: [
                          Icon(Icons.check_circle, color: Colors.green),
                          SizedBox(width: 8),
                          Text(
                            'Card Read Captured!',
                            style: TextStyle(fontWeight: FontWeight.bold),
                          ),
                        ],
                      ),
                      const SizedBox(height: 8),
                      Text(
                        'Transaction ID: ${_lastReadResult!.id}',
                        style: const TextStyle(fontSize: 13),
                      ),
                      const SizedBox(height: 4),
                      Text(
                        'Outcome: ${_lastReadResult!.outcome}',
                        style: const TextStyle(fontSize: 13),
                      ),
                      const SizedBox(height: 8),
                      const Text(
                        'Encrypted Cryptogram (First 40 chars):',
                        style: TextStyle(
                          fontSize: 12,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      SelectableText(
                        _lastReadResult!.cardDataCryptogram.length > 40
                            ? '${_lastReadResult!.cardDataCryptogram.substring(0, 40)}...'
                            : _lastReadResult!.cardDataCryptogram,
                        style: const TextStyle(
                          fontFamily: 'monospace',
                          fontSize: 12,
                        ),
                      ),
                    ],
                  ],
                ),
              ),
            ),
            const SizedBox(height: 16),

            // Live Event Log Card
            Card(
              elevation: 0,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(12),
                side: BorderSide(color: Colors.grey.shade300),
              ),
              color: Colors.white,
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        const Text(
                          'Live Diagnostic Logs',
                          style: TextStyle(
                            fontWeight: FontWeight.bold,
                            fontSize: 14,
                          ),
                        ),
                        Row(
                          children: [
                            TextButton.icon(
                              onPressed: _eventLogs.isEmpty
                                  ? null
                                  : () {
                                      Clipboard.setData(
                                        ClipboardData(
                                          text: _eventLogs.join('\n'),
                                        ),
                                      );
                                      ScaffoldMessenger.of(context).showSnackBar(
                                        const SnackBar(
                                          content: Text('All logs copied to clipboard!'),
                                        ),
                                      );
                                    },
                              icon: const Icon(Icons.copy, size: 14),
                              label: const Text('Copy All', style: TextStyle(fontSize: 12)),
                            ),
                            TextButton(
                              onPressed: () {
                                setState(() {
                                  _eventLogs.clear();
                                });
                              },
                              child: const Text('Clear', style: TextStyle(fontSize: 12)),
                            ),
                          ],
                        ),
                      ],
                    ),
                    const SizedBox(height: 4),
                    Container(
                      height: 180,
                      decoration: BoxDecoration(
                        color: const Color(0xFF0F172A),
                        borderRadius: BorderRadius.circular(8),
                      ),
                      padding: const EdgeInsets.all(8.0),
                      child: _eventLogs.isEmpty
                          ? const Center(
                              child: Text(
                                'No logs yet',
                                style: TextStyle(
                                  color: Colors.grey,
                                  fontSize: 12,
                                ),
                              ),
                            )
                          : ListView.builder(
                              itemCount: _eventLogs.length,
                              itemBuilder: (context, index) {
                                final logItem = _eventLogs[index];
                                final isError = logItem.contains('ERROR');
                                return Padding(
                                  padding: const EdgeInsets.symmetric(vertical: 2.0),
                                  child: SelectableText(
                                    logItem,
                                    style: TextStyle(
                                      color: isError
                                          ? const Color(0xFFF87171)
                                          : const Color(0xFF38BDF8),
                                      fontSize: 11,
                                      fontFamily: 'monospace',
                                    ),
                                  ),
                                );
                              },
                            ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
0
likes
160
points
23
downloads

Documentation

API reference

Publisher

verified publisherkarsmiths.com

Weekly Downloads

Flutter plugin for Fortis Tap to Pay on iPhone (Apple ProximityReader) with automatic token management, keychain caching, and REST API integration.

Repository (GitHub)
View/report issues

License

MIT (license)

Dependencies

flutter, plugin_platform_interface

More

Packages that depend on tap_to_pay_fortis

Packages that implement tap_to_pay_fortis