tap_to_pay_fortis 0.0.1
tap_to_pay_fortis: ^0.0.1 copied to clipboard
Flutter plugin for Fortis Tap to Pay on iPhone (Apple ProximityReader) with automatic token management, keychain caching, and REST API integration.
Fortis Tap to Pay on iPhone (Flutter Plugin) #
A Flutter plugin implementing Fortis Tap to Pay on iPhone powered by Apple's ProximityReader framework. It enables physical contactless credit, debit, and digital wallet (Apple Pay, Google Pay) acceptance directly on a supported iPhone with zero external card reader hardware.
Table of Contents #
- Key Features
- Architecture Overview
- Requirements & Prerequisites
- Apple Entitlements Setup
- Installation & iOS Configuration
- Quickstart Guide
- API Reference
- Troubleshooting & Common Native Errors
- License
Key Features #
- Apple ProximityReader Framework Integration: Native Swift implementation targeting iOS 17.0+ on physical devices (iPhone XS or later).
- Direct Fortis REST API Client: Built-in support for generating 24-hour Payment Card Reader Tokens via
GET /v1/payment-card-reader-token?product_transaction_id={id}. - Secure iOS Keychain Token Caching: Tokens are cached in the iOS Keychain and automatically reused within their 24-hour validity window.
- Immediate Read Result (
returnReadResultImmediately): Receives the encrypted card cryptogram immediately before the Apple payment sheet finishes its dismissal animation, reducing latency. - Application Switching Resilience: Automatically captures
UIApplication.willEnterForegroundNotificationto re-initialize reader sessions if the app was sent to the background. - Apple Terms & Conditions Linking: Supports device-level account linking (
linkAccount) and Enterprise Merchant Linking via Apple Business Connect (/v1/merchants/taptopay/enterprise-link-redirect). - Comprehensive Error Diagnostics: Strongly typed error model (
FortisApiException,TapToPayError) with detailed error domains, codes, and underlyinguserInfo.
Architecture Overview #
sequenceDiagram
autonumber
actor Customer as Customer Card / Device
participant App as Flutter Merchant App
participant Plugin as TapToPayFortis Plugin
participant Apple as Apple ProximityReader
participant Fortis as Fortis OneCo REST API
App->>Fortis: 1. GET /v1/payment-card-reader-token?product_transaction_id={id}
Fortis-->>App: Return 24-Hour Reader Token (JWT)
App->>Plugin: 2. prepareReader(token)
Plugin->>Apple: PaymentCardReader.prepare(using: token)
Apple-->>Plugin: Session initialized & ready
Plugin-->>App: Event: ready (Token cached in Keychain)
App->>Plugin: 3. readPaymentCard(amount, currency)
Plugin->>Apple: session.readPaymentCard(request)
Apple-->>Customer: Present Apple System Tap Sheet
Customer-->>Apple: Taps physical card / Apple Pay
Apple-->>Plugin: Return card_data_cryptogram immediately
Plugin-->>App: ReadResult (Cryptogram)
App->>Fortis: 4. POST /v1/transactions/cc/sale/tap-to-pay
Fortis-->>App: Transaction Approved / Captured
Apple-->>App: Event: userInterfaceDismissed (Apple Sheet Dismissed)
App->>App: Safe to update UI / navigate
Requirements & Prerequisites #
| Requirement | Specification |
|---|---|
| Platform | iOS Only (Target: iPhone) |
| Minimum iOS Version | iOS 17.0+ (IPHONEOS_DEPLOYMENT_TARGET = 17.0) |
| Hardware | Physical iPhone XS or later (Apple does not support simulators for NFC card reads) |
| Apple Developer Entitlement | com.apple.developer.proximity-reader.payment.acceptance |
| Fortis Credentials | user-id, user-api-key, developer-id, and product_transaction_id (or location_id) |
Apple Entitlements Setup #
Warning
Build Requirement & Common Xcode Error
If you try to build or run the project on a physical iPhone without configuring your own approved App ID and Provisioning Profile, Xcode will fail with:
Error (Xcode): Entitlement com.apple.developer.proximity-reader.payment.acceptance not found and could not be included in profile.
com.apple.developer.proximity-reader.payment.acceptance is an Apple-restricted capability. You must set up your Bundle ID and Provisioning Profile with Apple before you can compile and deploy to a physical iPhone. Follow the steps below:
Step 1: Request Tap to Pay on iPhone Entitlement from Apple #
- Visit Apple Developer: Tap to Pay on iPhone.
- Submit your entitlement application with your Apple Developer Team ID and select Fortis as your Payment Service Provider.
Step 2: Enable Capability in App ID #
- Go to developer.apple.com → Certificates, Identifiers & Profiles → Identifiers.
- Select your App ID (e.g.,
com.yourcompany.app). - Under Capabilities, check Tap to Pay on iPhone and save.
- Regenerate / download your provisioning profile in Xcode.
Step 3: Configure Xcode & Runner.entitlements #
- Open
ios/Runner.xcworkspacein Xcode. - Under Signing & Capabilities:
- Select your approved Apple Developer Team.
- Set your Bundle Identifier matching your approved App ID.
- In your Flutter iOS project (
ios/Runner/Runner.entitlements), ensure the following entitlement is included:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.developer.proximity-reader.payment.acceptance</key>
<true/>
</dict>
</plist>
In your ios/Runner.xcodeproj/project.pbxproj, verify CODE_SIGN_ENTITLEMENTS points to Runner/Runner.entitlements:
CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements;
Installation & iOS Configuration #
1. Add Dependency to pubspec.yaml #
dependencies:
tap_to_pay_fortis:
path: ../tap_to_pay_fortis # or git / pub source
2. Configure ios/Podfile #
Ensure the platform deployment target is at least 17.0:
platform :ios, '17.0'
Quickstart Guide #
1. Generate Payment Card Reader Token #
Tokens are issued by the Fortis OneCo REST API and remain valid for 24 hours:
import 'package:tap_to_pay_fortis/tap_to_pay_fortis.dart';
final plugin = TapToPayFortis.instance;
// Request token from Fortis REST API
final token = await plugin.generateToken(
productTransactionId: 'your_product_transaction_id',
userId: 'your_user_id',
userApiKey: 'your_user_api_key',
developerId: 'your_developer_id',
environment: FortisEnvironment.sandbox, // or FortisEnvironment.production
);
print('Generated Token: $token');
2. Accept Apple Terms & Conditions (Account Linking) #
The first time a merchant prepares a device, Apple requires them to accept the Tap to Pay on iPhone Terms and Conditions. Call linkAccount:
try {
final linked = await plugin.linkAccount(token: token);
print('Apple Terms & Conditions accepted: $linked');
} on PlatformException catch (e) {
print('Linking failed: [${e.code}] ${e.message}');
}
Enterprise Merchant Linking: Alternatively, merchants can accept terms once per location in Apple Business Connect using
plugin.getEnterpriseLinkRedirect().
3. Prepare the Reader (Keychain Caching) #
Initialize the Apple reader session. The token is automatically saved to the secure iOS Keychain for 24 hours:
// Check if device hardware and iOS version support Tap to Pay
final isSupported = await plugin.isSupported();
if (!isSupported) {
throw UnsupportedError('Tap to Pay requires iPhone XS+ and iOS 17+');
}
// Prepare reader (will automatically store token in Keychain)
final ready = await plugin.prepareReader(token: token);
print('Reader ready: $ready');
4. Listen to Reader Events & Apple HIG #
Apple's Human Interface Guidelines (HIG) require that your application must wait until the Apple system payment sheet has completely dismissed before updating your user interface or navigating:
plugin.events.listen((event) {
switch (event.type) {
case TapToPayEventType.preparing:
print('Reader preparing: ${event.progress}%');
break;
case TapToPayEventType.ready:
print('Reader is ready for card presentation!');
break;
case TapToPayEventType.readyForTap:
print('Apple sheet active: Waiting for customer tap...');
break;
case TapToPayEventType.cardDetected:
print('Card detected, hold still...');
break;
case TapToPayEventType.removeCard:
print('Please remove card');
break;
case TapToPayEventType.readResultReceived:
print('Cryptogram captured!');
break;
case TapToPayEventType.userInterfaceDismissed:
// CRITICAL: Safe to navigate or show success receipt screen
print('Apple sheet dismissed. Safe to update UI.');
break;
case TapToPayEventType.sessionRestored:
print('Reader session automatically restored from Keychain');
break;
case TapToPayEventType.error:
print('Reader Error: [${event.code}] ${event.message} - ${event.details}');
break;
default:
break;
}
});
5. Collect Contactless Payment #
Trigger Apple's contactless card reading sheet:
try {
final readResult = await plugin.readPaymentCard(
amount: 19.99,
currencyCode: 'USD',
);
print('Transaction ID: ${readResult.id}');
print('Encrypted Cryptogram: ${readResult.cardDataCryptogram}');
// Proceed to Step 6 with cryptogram
} on PlatformException catch (e) {
print('Card read failed: [${e.code}] ${e.message} - ${e.details}');
}
6. Authorize / Capture via Fortis REST API #
Send the cryptogram to Fortis to complete the transaction (must be sent within 60 seconds):
final client = plugin.apiClient; // or instantiate FortisTapToPayClient
final response = await client!.processSale(
FortisTapToPaySaleRequest(
productTransactionId: 'your_product_transaction_id',
transactionAmount: 1999, // In cents ($19.99)
cardDataCryptogram: readResult.cardDataCryptogram,
description: 'Order #1042',
),
);
if (response.isSuccess) {
print('Payment Approved! Transaction ID: ${response.id}');
} else {
print('Payment Declined: ${response.statusMessage}');
}
API Reference #
TapToPayFortis (Main SDK) #
| Method | Parameters | Description |
|---|---|---|
isSupported() |
- | Checks if hardware is iPhone XS+ running iOS 17.0+. |
generateToken(...) |
productTransactionId, userId, userApiKey, developerId?, environment |
Fetches a 24-hr JWT token from Fortis API. |
linkAccount(...) |
token |
Displays Apple Terms & Conditions for merchant account. |
relinkAccount(...) |
token |
Re-links merchant account to a new Apple ID. |
prepareReader(...) |
token?, storeInKeychain, expiresAt? |
Prepares Apple reader session with token. |
readPaymentCard(...) |
amount, currencyCode |
Displays Apple contactless tap sheet to capture cryptogram. |
cancelRead() |
- | Cancels an active card read. |
getCachedToken() |
- | Returns cached Keychain token and expiration info. |
clearCachedToken() |
- | Purges token from Keychain. |
events |
Stream<TapToPayEvent> |
Reactive stream of reader lifecycle and hardware events. |
TapToPayEventType #
| Event | Description |
|---|---|
preparing |
Reader is downloading configuration or warming up. |
ready |
Reader is initialized and ready to take payments. |
readyForTap |
Apple system sheet is presented and waiting for card. |
cardDetected |
NFC card or device detected. |
removeCard |
Card read completed; customer should remove card. |
readResultReceived |
Cryptogram generated and returned to Flutter. |
userInterfaceDismissed |
Apple sheet dismissed; safe to update application UI. |
appBackgrounded |
App sent to background (Apple invalidates session). |
sessionRestored |
Session auto-restored upon foregrounding using Keychain token. |
error |
Native error occurred. |
Troubleshooting & Common Native Errors #
1. PaymentCardReaderError.notAllowed (Error 0) #
- Cause: The merchant has not accepted Apple's Tap to Pay on iPhone Terms & Conditions, the token is invalid, or the app lacks the proper entitlement.
- Fix: Call
plugin.linkAccount(token: token). This displays Apple's official system sheet prompting the merchant to accept the Terms & Conditions.
2. Error (Xcode): Entitlement com.apple.developer.proximity-reader.payment.acceptance not found and could not be included in profile. #
- Cause: Apple's
ProximityReaderentitlement is a protected/restricted entitlement. If your Apple Developer Account has not been granted this entitlement by Apple, or if the capability is not enabled on your App ID in the Apple Developer Portal, Xcode's automatic code signing cannot include it in your provisioning profile and will fail to build. - Fix:
- Ensure you have submitted an application to Apple for the Tap to Pay on iPhone entitlement at developer.apple.com/tap-to-pay.
- Once approved, go to Certificates, Identifiers & Profiles → Identifiers, select your App ID, check Tap to Pay on iPhone, and save.
- In Xcode, ensure your project's Bundle Identifier matches this App ID and your Development Team is selected under Signing & Capabilities.
- Xcode will automatically generate a provisioning profile containing the entitlement.
3. Fortis API HTTP 401 Unauthorized #
- Cause: Incorrect
user-id,user-api-key, ordeveloper-id. - Fix: Verify your Fortis Sandbox credentials vs Production credentials. Ensure
developer-idmatches your assigned partner code.
4. Fortis API HTTP 422 Unprocessable Entity #
- Cause: Invalid
product_transaction_id. - Fix: Ensure the
product_transaction_idmatches the 24-character hexadecimal format.
License #
This project is licensed under the MIT License.