fints
A pure Dart FinTS client for German banks, for any Flutter app (iOS, Android, desktop). It reads accounts, balances,
transactions and depot holdings over FinTS 3.0 (HBCI segment syntax) and FinTS 4.1 (XML, namespaces 4.1.1 and
4.1).
Features
- PIN/TAN security, the procedure German banks offer consumers:
- One-step (
999) and two-step TAN methods of process variant 2 (HKTANprocess 4, then 2 orS), which every bank offers for PSD2; a bank with only variant 1 raisesFinTsTanSetupException. - Strong customer authentication (SCA) at dialog start (
HKTANprocess 4; in 4.1SCARequestedandDistSigsSign) and per transaction where asked, with exemptions (3076). - App approval (decoupled: pushTAN, SecureGo plus, …) where the bank's answer asks for it (
3955), with status requests (HKTAN#7 processS) timed by the bank's parameters, a FinTS 3.0 feature (see FinTS 4.1). Without3955a challenge asks for a TAN, also with an app's TAN method. - TAN media lookup and selection (
HKTAB/DisplayTanGeneratorList). - chipTAN flicker codes (HHD 1.3 and 1.4, rendered to frames) and photoTAN/QR images (PNG, JPEG, GIF, WebP or BMP), also the chipTAN-QR image of Sparkassen and DKB in the challenge text.
- Customer system ID synchronisation and the user's allowed TAN methods (
3920).
- One-step (
- Suspend and resume: a FinTS 3.0 call waiting for a TAN or app approval can stop there and go on in another request
or process (
TanAnswer.suspended,client.resume), without the PIN in what is stored (see Suspending a call). - Bank messages and warnings for the app to show (
onBankMessage,onWarning); new login data (3072) passed on. - Balances (
HKSAL5–8 /AcctBal1–2). - Transactions as camt.052 (
HKCAZ/AcctMvmtsSpecifiedPeriodCamt) or MT940/MT942 (HKKAZ5–7 /AcctMvmtsSpecifiedPeriod1–2), with automatic paging. - Credit card accounts (bookings by
DKKKU2 orHKKKU1, balance byDKKKS3 orHKKKS1, FinTS 3.0) throughgetTransactionsandgetBalance, for the banks that serve card accounts so (Sparkassen, BW-Bank, comdirect, Deutsche Bank, Postbank); others serve them by the regular queries (see Credit card accounts). - Depot holdings (
HKWPD5–6 /PortfList1): the securities of a depot account from its MT535 statement, with ISIN, WKN, quantity, price, market value, acquisition price and the depot total where the bank states them. - Bank and user parameter data (BPD/UPD), taken only from dialog-opening answers, cached in an exportable state string; the BPD are asked for anew a week after they came, since banks change them without a new version.
- Only what the parameter data permit is sent: a transaction the UPD or
HIPINSrule out fails withFinTsUnsupportedException, though the login delivering them and the SEPA account list may have gone out. - The FinTS 3.0 account extension of the UPD: BIC and complete balance without extra queries, and the bank's notes on
new data (
Account.dataStatus). - SEPA account details (
HKSPA/SEPAAcctInq): IBAN, BIC, and which account a stored one stands for (see Accounts the app stores). - Parsers for MT940 (German structured
:86:fields and SEPA keywords) and camt.052/053/054, as statements with their account (Mt940.parse,Camt.parse) or one transaction list (parseTransactions).
Prerequisites
- FinTS product registration. Since August 2019 German banks accept only registered client products. Register for
free with the Deutsche Kreditwirtschaft at www.fints.org/de/hersteller/produktregistrierung (the ID takes
10–15 business days) and pass it as
productId. - Your bank's FinTS URL and bank code (BLZ).
Usage
import 'package:fints/fints.dart';
// FinTs4Client for the few banks running FinTS 4.1.
final client = FinTs3Client(
config: FinTsConfig(
url: Uri.parse('https://fints.example-bank.de/fints'),
bankCode: '12345678',
userId: 'my-login',
productId: 'YOUR_REGISTRATION_ID',
productVersion: '1.0',
),
pin: pin,
options: FinTsClientOptions(
state: savedState, // from a previous session, or null
tanMethodSelector: (methods) => showMethodPicker(methods),
tanMediumSelector: (media) => showMediumPicker(media),
onBankMessage: (message) => showNotice(message.subject, message.text),
onWarning: (warning) => showNotice(warning.code, warning.text),
tanCallback: (challenge) async {
if (challenge.isDecoupled) {
// Close once challenge.resolved completes; offer "approved" only if challenge.manualConfirmation.
final confirmed = await showApprovalDialog(challenge);
return confirmed ? TanAnswer.approved : TanAnswer.cancelled;
}
// Show challenge.plainMessage, image or flickerCode; accept at most method.maxTanLength chars, digits only if
// method.numericTan.
final tan = await askUserForTan(challenge);
return tan == null ? TanAnswer.cancelled : TanAnswer.tan(tan);
},
),
);
try {
final accounts = await client.getAccounts();
final balance = await client.getBalance(accounts.first);
final transactions = await client.getTransactions(
accounts.first,
from: DateTime.now().subtract(const Duration(days: 90)),
);
final depot = accounts.where((a) => a.category == AccountCategory.securities).firstOrNull;
if (depot != null) {
final HoldingsStatement(:holdings, :total) = await client.getHoldings(depot);
}
} on FinTsLoginDataChangedException catch (e) {
// Store e.userId, e.customerId or e.loginName and build a new client with them.
} on FinTsLoginRefusedException catch (e) {
// The bank's errors, or why the client stopped by itself. A FinTsPinException is a wrong or blocked PIN, or an
// access the bank has locked for now (3931, 3938), which the user lifts as the bank's text tells.
showNotice('Login refused', e.message);
// Then ask for the PIN anew and call client.clearLoginRefusal(pin).
} on FinTsTanException {
// A rejected or expired TAN, or one the TAN method rules out.
} on FinTsBankException catch (e) {
// e.feedback holds all bank return codes.
} finally {
try {
await client.close();
} finally {
savedState = client.state; // persist after close, whose answers may change it
}
}
One dialog per client
All calls on one client share one bank dialog, so strong authentication happens once per session.
- An idle dialog is given up after the bank's maximum timeout (
BankInfo.maxTimeout, else five minutes). - A dialog the bank ends otherwise (as with
9800) fails the running call withFinTsDialogAbortedException. - So does the bank's dialog abort message (Formals B.7.6), even one naming dialog and message unknown, with the bank's text; no dialog end follows.
- An answer naming dialog or message unknown (dialog ID
unbekannt, message number 9999) with nothing but return codes, an error among them, as ING sends, fails the call with aFinTsBankExceptionholding the bank's text, and ends the dialog too. Unless it names the message sent, as a first answer does with its number, it may answer another message, so to a login it is a refused login that no other login of the call follows.
The client does not repeat the call, as a new login may cost another approval and the bank's answer cannot tell whether an order went through, but for a query refused for want of strong authentication (below), which only reads; the next call logs in anew. A login answered by ending the dialog counts as refused (see Protection against a locked access).
Strong authentication for a query. A query asks for it (HKTAN; in 4.1 inside a signature submission,
DistSigsSubmit) where the bank's parameter data say it needs it (HIPINS; in 4.1 OTPTransactions), or where the
option tanRequiredFor names its business transaction, such as {'HKKAZ'}. A bank may refuse one without all the same
(9075, 9370, or 9210 "Zwei-Schritt-TAN inkonsistent"), as Consorsbank does with transactions: the call then sends
it once more with the request, in a new dialog, which may cost another login approval, and client.state keeps its
business transaction, so later calls send the request at once. This holds for the SEPA account list too, which
getAccounts, getBalance and getTransactions fetch, so getAccounts may ask for a TAN or app approval.
Calls run one at a time, so a callback (TAN, selector, bank message or warning) must not await another call of its client:
- One from inside the callback fails with a
StateError. - One from elsewhere, like a button in the callback's dialog, waits for the current call.
close()works from anywhere.
Protection against a locked access
Banks lock the access after a few failed PIN attempts. Once the bank has refused a login, every later call that would
send the PIN fails with the same FinTsLoginRefusedException without contacting the bank, also in a client restored
from client.state, until client.clearLoginRefusal takes a newly entered PIN.
Refused logins. A login counts as refused for:
- a rejected PIN (
FinTsPinException), wherever the bank reports it, even in answer to a dialog end; - a warning that the bank has locked the access for now (
3931,3938), wherever it comes, also beside a success or a TAN request: aFinTsPinExceptionwhose message holds the bank's text, which tells the user how to lift the lock;onWarningdoes not get it; - any other error in answer to the login (
FinTsLoginRefusedException), even where the bank ends the dialog, as the PIN may be the cause.
In answer to a login, 9941 and 9951 mean an invalid signature, in PIN/TAN the PIN. The client does not even end a
refused dialog, as that message would carry the PIN.
Not refused (the next call logs in anew) are:
- a wrong or expired TAN (
FinTsTanException) or a rejected approval at login, since the bank checks the PIN first; - an order the bank rejects in an open dialog, like a TAN media list it does not offer the user.
Lost answers. A login whose answer is lost, times out or cannot be read (FinTsTransportException,
FinTsProtocolException) may still count as a failed attempt.
- The next call may log in once more. If that answer is lost too, the call fails with the loss and the client refuses
later logins itself (
FinTsLoginRefusedExceptionwith emptyfeedback). - As it cannot tell a login that never reached the bank (offline) from a lost answer, two failed connections in a row
stop it too; lift the refusal with
clearLoginRefusalonce the connection is back. - A login the bank takes clears the count of lost answers, which
client.statekeeps.
Logins the client repeats. It logs in once more, once per reason and call, so a call sends at most five logins the bank refuses, after:
- a refusal of the TAN media lookup, which runs before the medium is known and names none, with
9955and no errors but9050or9800besides, and without asking for an app approval (3955): banks such as Taunussparkasse refuse the placeholder medium namenorefthe specification gives with these, others may want it. The lookup goes out with it then, as do the client's later lookups; - a refusal of nothing but the login's
HKTAN(9010or9050for it, no other error than9050or9800for the whole message), as of anHKTANversion the bank no longer takes: banks change their BPD without a new version. The login goes out with the BPD the refusal brought, else those of an anonymous dialog, reporting version 0 for any older ones, so the bank sends them anew; not where the refusal brings the same BPD again, or where it reported version 0 already and nothing renews them (FinTS 3.0 only); - a TAN method the user may not use:
3920without the method; after the one-step method, which banks never list, only if the bank names no error but9050,9800or9955(PIN/TAN B.8.2, for a user bound to two-step methods);9075after the one-step method;- where the BPD lack a method the bank last listed (
3920), the user chooses among renewed ones, as above;
- a customer system ID the bank no longer accepts (
9391).
New login data (3072, like a login name in place of user ID and customer ID) end the old ones, even next to an
error, overriding other reasons in the answer.
- The call and all later ones fail with
FinTsLoginDataChangedException, naming the new data for a new client;clearLoginRefusalcannot lift it, and throws it. - Unless the answer refuses the login, the client ends the dialog as the specification asks, before any TAN or app approval; else it sends no dialog end.
- Next to a rejected PIN, the call fails with
FinTsPinExceptioninstead, whosefeedbackalso holds the new data;clearLoginRefusallifts it like any other.
Lifting the refusal. client.loginRefusal tells the refusal before any call:
final refusal = client.loginRefusal;
if (refusal is FinTsLoginDataChangedException) {
// Build a new client with refusal.loginName as userId, or its userId and customerId.
} else if (refusal != null) {
showNotice('Login refused', refusal.message); // the bank's errors, or why the client stopped by itself
await client.clearLoginRefusal(await askForPin());
}
Never pass clearLoginRefusal a stored PIN without asking: that is how a retrying app locks the access. It also:
- ends the open dialog, so the next call logs in with the new PIN;
- forgets the TAN medium, which the bank may have refused instead (like a replaced phone's), so the next call looks the
media up anew. Where the bank does not list them, pass the medium to
selectTanMethodagain.
Bank messages and warnings
onBankMessage receives the bank's free-text messages, onWarning its warnings (codes 3000 to 3999), like 3951
when the user must switch TAN method. The specification asks apps to show both, warnings with code and text. onWarning
skips those the client handles itself:
3040: more data follow, which fails the query withFinTsIncompleteResultExceptionwhere it names no position to continue at3060: some warnings3072: new login data3076: no strong authentication needed3920: allowed TAN methods3931,3938: access locked for now, which fails the call withFinTsPinException3955to3957: steps of an app approval
A query whose last page has a 3040 naming no position to continue at, as Sparkassen send with too many pending
bookings, fails with FinTsIncompleteResultException, a FinTsProtocolException, so that a short list never passes for
all there is. To show what came, take its partialResult, of the call's result type, such as the transactions of the
pages received, but null for a balance or holdings, and tell the user why the rest is missing with its feedback:
try {
transactions = await client.getTransactions(account, from: from);
} on FinTsIncompleteResultException<List<Transaction>> catch (e) {
// null where the SEPA account list, which the call may look up first, came in part.
transactions = e.partialResult ?? const [];
showNotice('Incomplete', e.feedback.map((f) => '${f.code}: ${f.text}').join('\n'));
}
Closing
close() also stops a running call, even one waiting for a TAN, an app approval or a selection; that call and all later
ones throw a StateError. It sends no dialog end for the dialog of a suspended call, which resume continues (see
Suspending a call).
- A request in flight gets five seconds for its answer, which the logger and the saved state take as any other.
- Then the client stops waiting, whatever the transport, and aborts the request if the transport takes
FinTsTransport.post'sabortTrigger, asHttpTransportdoes. - After the request, the call sends only its dialog ends, and none where the transport failed, as by the abort (Formals C.6).
- These get five seconds from the end of the request, then are aborted the same way; none goes out later.
- If that request fails, as with a rejected PIN or the abort, the call throws its error instead of the
StateError.
Errors
All errors from the bank or the connection are FinTsExceptions.
Suspended calls. A call the app suspends at a challenge (TanAnswer.suspended) throws a FinTsSuspendedException,
which is no failure and no FinTsException; its suspension goes to resume (see
Suspending a call). resume throws, sending nothing, a FinTsDialogAbortedException without
return codes for a suspension past its expiresAt, and a StateError for one the state does not hold or a damaged one.
Transport errors. Any other error of a transport, even another FinTsException or an Error, counts as a failed
connection, which ends the dialog for the bank (Formals C.6): the client sends no dialog end, also while closing, and
the next call logs in anew. It becomes a FinTsTransportException that keeps:
- its message, for types the package knows (such as
FormatException,StateError,TimeoutExceptionor package:http'sClientException) and a thrownString; - only its type for others, even an app's own
Exceptionclass with amessage, as inInstance of 'RelayError', sincetoStringmay print the request. Throw aFinTsTransportExceptionto pass a message on.
Bank data. Incomplete or malformed bank data raise FinTsProtocolException; a refused order never reads as an empty
result. The client never fills in:
- zeros;
- a currency other than the account's, for MT940 statements stating none (see Accounts the app stores);
- dates, but a camt entry without value date gets its booking date, and a booked balance without date the bank's today, as DKB sent one.
Such data include:
- an answer cut short, broken in its framing or run together with another;
- an answer to another message (number, dialog ID or referenced message differ), as from a relay or proxy mixing up answers, but for the bank's error answers that name them unknown (see One dialog per client);
- a balance or camt transactions for another account than requested (MT940 transactions go unchecked, as banks write their account line in many ways), and a card answer naming another card account, or none;
- a TAN or approval request without a challenge;
- an answer to a TAN or app approval asking for another approval;
- more data announced without the position to continue at, which raise
FinTsIncompleteResultExceptionwith what came (see Bank messages and warnings); - a camt document with no report, statement or notification;
- XML that XML 1.0 does not allow, like a document type declaration, unknown entity, unquoted attribute or second XML declaration;
- a query asking approval for over 3 further pages besides its first, or whose pages exceed 128 MiB (each data element or XML node counted as 512 bytes, last page included) or 200,000 statements and transactions, or statements and holdings; ask for a shorter period then.
Size limits. So a broken or hostile server cannot block the app for long, exhaust the stack or take unbounded memory, the client also rejects:
- a FinTS 3.0 message of over 1,000,000 data elements and segments;
- an XML document (FinTS 4.1 message, camt report) nested over 100 deep, or with over 500,000 nodes besides text or one per 16 characters, whichever is more;
- an MT940 or MT535 field of over 65,536 characters;
- a card booking's text, card number or reference of over 65,536 characters;
- MT535 blocks nested over 8 deep;
- an amount of over 64 characters.
Depot holdings. A holding's detail that the bank leaves out, or that the client cannot read, is null, never
guessed or computed: no market value from price and quantity, no total summed, and no price whose meaning the statement
leaves open, such as an acquisition price without currency of a security quoted per piece. A statement whose structure,
or a holding whose security or quantity, the client cannot read fails getHoldings with FinTsProtocolException, as
does an answer without statement where the bank does not report an empty depot: a statement saying it holds nothing, or
return code 3010 "Es liegen keine Einträge vor". A 3010 of another text, such as "Information wird zurzeit nicht
angeboten", which banks also send for what they do not offer now, fails the call, its text going to onWarning.
A depot's total, as the bank states it, includes accrued interest, which the holdings' marketValue leaves out. It is
null where the bank states none, as for a depot it does not value, as DKB's seem to be since November 2024, and where
the statement comes in several MT535 messages, each with the total of its own holdings. Show names, which come from the
bank, as text, never as markup.
MT940 balances. Statements must balance: where a bank wraps a purpose at a fixed width, a payer could start a line
like a field, such as :61: or -:61:, to add a transaction. getTransactions then fails with
FinTsProtocolException, Mt940.parse with FormatException. The check misses such lines that add up to nothing, and
statements without balances, like pending transactions (MT942).
SEPA keywords. A SEPA keyword like CRED+ in text the payer or payee writes (SVWZ+, ABWA+, ABWE+) is part of
that text, and a repeated one has no value, so the payer cannot replace the creditor ID, mandate reference or IBAN the
bank stated.
Rejected TANs and lists. A TAN the bank rejects always fails the call with FinTsTanException, even in the lookups
that only complete data (SEPA account list, TAN media). A bank rejecting those lists leaves out:
- IBAN and BIC;
- which account a stored one stands for, so it may be refused (see Accounts the app stores);
- the medium.
Ending the dialog in answer to the SEPA account list rejects it too: the call goes on without it, and only a new client
asks again. A list refused for want of strong authentication (9075, 9370, or 9210 "Zwei-Schritt-TAN
inkonsistent") goes out once more with the request for it, in a new dialog, which may ask for a TAN or app approval
(see Strong authentication for a query).
Callback errors. An error thrown by onBankMessage, onWarning or logger fails the call only after its exchange
with the bank, so it cannot break off a dialog half-way; an error of the call itself takes precedence.
Invalid input fails before the bank is contacted, with an ArgumentError naming the argument but not its value:
- an empty PIN, or one with leading or trailing blanks, to the constructor or
clearLoginRefusal; - an empty login name, bank code or product ID;
- a country code other than three digits (
280for Germany), or a German bank code (BLZ) other than eight; - a URL that Platform notes rule out;
- a period starting after its end;
- a
tanRequiredForentry that names no business transaction: in FinTS 3.0 four to six capital letters, likeHKKAZ, in FinTS 4.1 letters and digits without version, likeAcctMvmtsSpecifiedPeriod; - in FinTS 3.0, a PIN, login detail or product with characters outside ISO 8859-1 (like
€), a bank code, user ID or customer ID over 30 characters, a product ID over 25 or a version over 5; - in FinTS 4.1, a PIN with characters a 4.1 value cannot hold: control characters below
U+0020(TAB, CR and LF included),U+FFFE,U+FFFFor half a surrogate pair.
FinTsConfig drops blanks around the login details and the product, as FinTS sends them without.
PIN length. A PIN the bank's parameters rule out by length fails with an ArgumentError before any login, after an
anonymous dialog without PIN refreshed the parameters, as saved ones may be outdated.
- Of new parameters of another version the client takes only the PIN lengths, if stated, and the maximum message size, until the next login brings the user's own, which may differ.
- Where the bank does not answer anonymously, drop
client.stateto refresh them; the count of lost login answers (see Protection against a locked access) then starts anew.
A TAN the TAN method rules out fails with a FinTsTanException instead (see The TAN callback).
The TAN callback
The callback returns a TanAnswer, synchronously or as a Future:
TanAnswer.tan(tan): the TAN the user entered; an empty one cancels.TanAnswer.approved: the user reports approval in the banking app (isDecoupled).TanAnswer.cancelled: the user cancels.TanAnswer.suspended: the app answers later, maybe in another process, wherechallenge.suspendable(see Suspending a call).
These fail the call, and the client ends the bank dialog:
- an answer not fitting the challenge (a TAN for an app approval or vice versa,
TanAnswer.suspendedto one that is not suspendable):ArgumentError; - a TAN the TAN method rules out:
FinTsTanExceptionwithout return codes, naming the rule but not the TAN; - a cancel:
FinTsTanCancelledException.
The client checks the TAN before sending it, since the bank would count a ruled-out one as a failed attempt. Ruled out is a TAN:
- longer than
TanMethod.maxTanLength; - with anything but the digits 0 to 9, where
TanMethod.numericTanis set; - with characters the protocol cannot send: in FinTS 3.0 those outside ISO 8859-1, in FinTS 4.1 those a PIN may not hold (see Errors).
Blanks around the TAN do not count; full-width characters count as their ASCII counterparts.
TanChallenge exposes:
message: instruction text as the bank sent it.plainMessage: that text as the user reads it, the specification's formatting tags of structured challenges applied, other angle brackets kept.image: photoTAN / QR-TAN image with lower-casemimeType,bytes, andtoDataUrl()for an<img>src. PNG, JPEG, GIF, WebP or BMP only; an SVG, which may carry scripts, is refused. Also the chipTAN-QR image, a PNG, that Sparkassen and DKB put into the challenge text;plainMessageis then the text after it.flickerCode: chipTAN optical code;frames()gives the 5-bar sequence to animate. A code that would not render as sent is refused, not shown altered on the TAN generator.isDecoupled: approval happens on another device, as the bank's answer says (3955), whatever the method: one the bank namesDecoupled(TanMethod.decoupled) may ask for a TAN, as Consorsbank's app does at login.manualConfirmation:falseif the bank does not let the user report it; offer no confirm button then.resolved: set while the client polls. Completes when the approval succeeds or fails, or a prompt with new instructions replaces this one; then close the prompt.suspendable: whether the app may answerTanAnswer.suspended.validUntil(an exact moment, see Dates and times),tanMediumNameandmethod: context.
App approvals. The bank's parameters decide who triggers the status requests:
- Normally the client polls itself while the callback shows the instructions.
- A user report (
TanAnswer.approved) makes the client ask at once; if not yet confirmed, the callback is called again with the bank's latest instructions. - On a status answer with new instructions it is called again too, with the next
attempt; the earlier prompt'sresolvedcompletes first, and its answer no longer counts. Close only the prompt whoseresolvedcompleted.
- A user report (
- If the bank forbids automatic status requests or announces a push message (
3957, which a client without push channel cannot receive), the client asks after each user report. - If the user cannot report the approval (
manualConfirmationisfalse), the client polls in any case, as nothing else can complete it; any answer butTanAnswer.cancelledor an empty TAN, which cancel, andTanAnswer.suspendedis ignored.
The client follows the bank's timing, bounded against faulty parameters:
- requests 1 second to 1 minute apart;
- no more than the bank allows (any number for
0); - at most 10 minutes of waiting in all.
Suspending a call
A server app need not keep the client alive while the user enters a TAN or approves in the app. A tanCallback
answering TanAnswer.suspended stops the call with a FinTsSuspendedException, leaving the bank dialog open, and
resume(suspension, answer) continues it from another client, also in another request or process, in the same dialog
with its next message. It returns what the call returns:
// Both requests: suspend what can be suspended, cancel the rest (or answer it in-process).
TanAnswer tanCallback(TanChallenge challenge) =>
challenge.suspendable ? TanAnswer.suspended : TanAnswer.cancelled;
Future<Object> startSync(String? state) async {
final client = FinTs3Client(
config: config,
pin: pin,
options: FinTsClientOptions(state: state, tanCallback: tanCallback),
);
FinTsSuspendedException? suspended;
try {
return await client.getTransactions(account, from: from);
} on FinTsSuspendedException catch (e) {
suspended = e;
return (challenge: e.challenge, expiresAt: e.expiresAt);
} finally {
await client.close(); // no dialog end for the suspended dialog
// One write: the state holds the suspension's digest, so either one alone cannot resume.
await saveEncrypted(state: client.state, suspension: suspended?.suspension);
}
}
Future<List<Transaction>> answerTan(String tan) async {
final saved = await claimEncrypted(); // reads and removes the suspension in one transaction
final client = FinTs3Client(
config: config,
pin: pin,
options: FinTsClientOptions(state: saved.state, tanCallback: tanCallback),
);
String? suspension;
try {
return await client.resume(saved.suspension, TanAnswer.tan(tan)) as List<Transaction>;
} on FinTsSuspendedException catch (e) {
suspension = e.suspension; // the bank asks once more
rethrow;
} on Object catch (e) {
if (sentNothing(e)) suspension = saved.suspension; // the user may correct the TAN
rethrow;
} finally {
await client.close();
await saveEncrypted(state: client.state, suspension: suspension);
}
}
bool sentNothing(Object error) => error is ArgumentError || (error is FinTsTanException && error.feedback.isEmpty);
- What can be suspended (
challenge.suspendable): TANs and app approvals of FinTS 3.0 logins, the synchronization's and the TAN media lookup's among them, and of the orders ofgetAccounts,getBalance,getTransactions,getHoldingsandgetTanMedia, card queries among them, on any page while the pages received so far and the answer asking for the approval total 4 MiB at most. Not the TAN media list asked after its own login, and nothing in FinTS 4.1. Answeringsuspendedto any other challenge fails the call with anArgumentError. - Used once:
resumetakes the suspension out of the state before anything goes out, so restore its client from the state saved after the call stopped, with the PIN again. Resumed again, or from an older state, it fails with aStateErrorand sends nothing. - Expires with the bank dialog: five minutes after the bank's last answer where the bank states no timeout
(
BankInfo.maxTimeout), at most ten, an app approval ten minutes after its first prompt at the latest (expiresAt). Later,resumefails with aFinTsDialogAbortedExceptionwithout return codes and sends nothing, but for an app approval past its ten minutes in a dialog still open, which it ends, with aFinTsDecoupledTimeoutException. Machines that share suspensions keep their clocks in sync. - Queries go on at the page they stopped at, with the pages received before. One stopped before midnight builds its order as of then, as a continuation must repeat it.
- App approvals:
TanAnswer.approvedasks the bank once, a second after the last status request at least; still pending, the callback gets the next attempt and may suspend again. The bank's maximum of status requests (decoupledMaxPolls, 10 at TARGOBANK) and the ten minutes since the first prompt hold across all resumes: resume after the user reports, or no faster thanchallenge.method.decoupledPollInterval. - Answers
resumecannot take fail before anything goes out and leave the suspension usable: a TAN the method rules out (FinTsTanExceptionwithout return codes), an answer of the other kind, or a PIN the bank's lengths rule out (ArgumentError). A cancel ends it, as does a TAN the bank rejects. - Dropped by
selectTanMethod,clearLoginRefusal, a refused login and any call that logs in: run other calls before suspending or after resuming. - Your store: save
client.stateand the suspension in one write, after the suspending call and afterresume, also when it fails. Claim a stored suspension beforeresume(read and remove it in one transaction) and put it back only after an error that sent nothing, so that two requests never both resume it; the bank would refuse the second. Keep it encrypted on the server, as the state: it holds no PIN or TAN, but the dialog's IDs, the challenge's text and, of a query, the account and the pages received so far.
Choosing the TAN method
On the first login the client asks tanMethodSelector, and tanMediumSelector if the method needs a medium.
client.selectedTanMethodandclient.selectedTanMediumtell the current choice.await client.selectTanMethod('946')switches; the next call logs in again with it.- Methods the client cannot run are not offered: process variant 1, and methods needing an SMS charge account. A method that asks for the HHD_UC answer is offered, as banks take the TAN without it.
Missing TAN medium. The call fails with FinTsTanSetupException before the login, which the bank would refuse, if:
- a method needs a TAN medium and the bank lists none active for the user;
- the bank refuses the one-step method for synchronizing a new client, and every method the user may use needs a medium, which can be looked up only afterwards.
Pass the medium with selectTanMethod('942', tanMedium: …), or choose another method. Until selectTanMethod or
clearLoginRefusal, getTanMedia then returns the list that tells why without asking the bank; otherwise it fetches
the current list, unless the same call just did to choose the medium.
Asking only for what has changed
FinTS 3.0 banks may describe each account in a UPD extension:
- The client takes the BIC from it, sparing the SEPA account list.
getBalanceanswers from it without a query where the bank marks the balance complete, also from the saved state: the bank must raise the UPD version on any change (Formals F.2).Balance.bookedAsOftells the day the balance states.Account.dataStatuspasses on the rest: when the app may fetch transactions or the balance again. Its rules (listed withAccountDataStatus) bind an app that stores transactions (Formals, chapter F); banks may refuse apps that ignore them.
Accounts the app stores
An account the app builds itself, like Account(bankCode: '12345678', iban: storedIban), stands for the getAccounts
account it matches by IBAN, else by account number; IBAN and BIC count without blanks and in any case, as printed or
typed. For it, getBalance, getTransactions and getHoldings:
- send the account number, sub-account, IBAN and BIC the bank states for the match;
- take its currency for statements stating none;
- check the query against the transactions the bank permits for it, ignoring
allowedTransactionsandallowedTransactionsCompleteset by the app.
Finding the account. To match it, getBalance, getTransactions and getHoldings fetch the SEPA account list
where getAccounts would (as when the UPD lack an account's IBAN or BIC), even for an account with both:
- once per UPD version, if the bank names accounts in the list, which
client.statekeeps; - in each client, if the bank sends UPD of version 0 or none, rejects the list, ends the dialog in answer to it other than for want of strong authentication, or names no account in it.
Checking the query uses the bank's lists for the account the client links the app's account to.
- An account only the SEPA account list names lists no transactions, so only the bank can tell.
- In FinTS 4.1 this includes an account the UPD name by number and the list by IBAN and BIC without number: a query for one built from that IBAN goes out even if the UPD rule it out for the account they name.
Accounts the bank names nowhere go out with account number, sub-account, IBAN, BIC, bank and country code and
currency only. They fail with FinTsUnsupportedException where the bank's lists of permitted transactions are complete
(UPD-Verwendung 0; UpdUsage 0 in FinTS 4.1) and so permit nothing they leave out. Such an account may be built from:
- its IBAN alone, where the UPD name accounts by number only and the bank does not deliver the SEPA account list that would find it;
- its number alone, where the UPD name accounts by IBAN only, as FinTS 4.1 ones may.
Store the IBAN where you can.
Depots come with the other accounts, as AccountCategory.securities and usually without IBAN. The bank's lists
decide which accounts getHoldings asks for: where allowedTransactionsComplete, a depot is an account whose
allowedTransactions include HKWPD (PortfList in FinTS 4.1), which a fund deposit (AccountCategory.fund) may be
too.
Credit card accounts
A credit card account has no IBAN; the bank names it by the card's number or one of its own, and its category is
AccountCategory.creditCard where the bank states the account type, which not every bank does. Many banks serve card
accounts by FinTS 3.0 queries of their own, which are not in the public specification, and the client takes them where
the account's permitted transactions name them:
getTransactionswithTransactionFormat.autosendsHKKKU(Deutsche Bank, Postbank) orDKKKU(Sparkassen, BW-Bank, comdirect) for an account that lists one and neitherHKCAZnorHKKAZ; an account that lists one of those, as at DKB, the Volksbanken and Targobank, takes it as any other account.mt940andcamtask for those formats alone.getBalancesendsHKSALwhere the account lists it, elseHKKKSorDKKKSwhere it lists one, else the card bookings query, of whose answer only the balance counts: a balance may then cost the approval the bookings need, where the bank asks one for them. The bookings query also stands in for a card balance query the bank does not offer where the account's permitted transactions are complete (allowedTransactionsComplete), which then rule outHKSAL; incomplete ones takeHKSAL.- Where the bank's parameter data offer none of the card queries a call would send, the call sends the regular query,
HKCAZorHKKAZ, orHKSAL, as for any other account.
A card booking is a Transaction:
bookingDatethe day the bank booked it,valueDatethe value date where the bank states one, else the day of the purchase;amountin the account's currency, andoriginalAmountin the currency the card was charged in where that is another, such as-75.00 CADfor-47.53 EUR;purposethe bank's text lines joined by blanks, the merchant usually first,bankReferencethe bank's reference;cardNumberthe card number the bank names, possibly in full: at some banks that of the card used, at others the account's for every card, the card used then showing masked inpurpose;statusTransactionStatus.booked, whatever the bank marks as final or not, as AqBanking and hbci4java read card bookings: what its mark means is not known.
Without from, the query starts as many days back as the bank keeps card bookings, such as 90 at Sparkassen. Banks
may answer longer periods only in part, without telling, so a query of more days fails with
FinTsUnsupportedException before it goes out, as does one without from whose to lies before the first day the
bank keeps, and any from or to where the bank's parameter data say it takes no period for card bookings. To fetch
older bookings, ask for periods of at most those days, each with its from and to.
Persisting state
client.state is a JSON string with:
- BPD and UPD as the bank sent them, and when the BPD came;
- the customer system ID;
- the chosen TAN method and medium;
- the TAN medium names the bank sent in other bytes than their text tells;
- the SEPA account list;
- the business transactions the bank refused without strong authentication (see One dialog per client);
- a refused login, with the count of lost login answers;
- a suspended call's digest and expiry, which bind the suspension to the state (see Suspending a call).
Reusing it spares the synchronization and TAN medium lookup on every start, and keeps a refused PIN unsent. It holds no
PIN or TANs, but account details and the bank's return codes, so store it encrypted (as with flutter_secure_storage).
Which state applies.
- A state saved for another user, customer ID or bank is ignored; blanks around them do not count.
- Of one for another server of the bank or the other protocol version, only the refused login and the count of lost login answers hold.
- A state belongs to one client at a time: restore one user's clients one after another, each from the state the previous saved. If two restore from one state at once, the last save wins and could lift a refused login the other saved.
BPD a week old are asked for anew, as banks change them without raising their version: the next login reports
version 0 in FinTS 3.0 and leaves out BpdVersion in FinTS 4.1, so the bank sends them.
States of older versions. A state from version 0.2.0 or earlier still applies, without a refused login. As it does not tell whether its BPD are the user's, the next login asks for them anew:
- in FinTS 3.0 by reporting version 0, once, so the bank sends them;
- in FinTS 4.1 by leaving out their version (
BpdVersion).
A state from version 0.3.0 or earlier does not tell when its BPD came, so the next login asks for them anew too, once.
Such a state counts as another server's if it writes the host otherwise than FinTsConfig.url now does, like an IPv6
address in long form (see Platform notes).
The PIN. The FinTS conditions of use forbid storing the PIN or TANs electronically, so pass the PIN in per session. The client holds it in memory only, until closed or a refused login outlasts the call that met it. A Dart string cannot be wiped; its memory is freed only when collected.
Dates and times
A value is either a calendar date or an exact moment:
- A date without time of day, like a booking date, is a local
DateTimeat midnight; only year, month and day count. A booking date the bank does not state isnull, not the value date. - A value with a time of day, like
TanChallenge.validUntil, is an exact moment, given as a localDateTimeof the device; banks state it in German time or with a UTC offset.
So Balance.bookedAsOf and Holding.priceDate are calendar dates, and Balance.bookedAsOfTime and
HoldingsStatement.asOfTime the exact moments where the bank also states the time.
getTransactions counts the local calendar days of from and to, both included; a day after the current day in
Germany counts as that day, as banks reject future dates.
getTransactions without from starts on the first day the bank keeps, as many days before its today as its
parameter data state (HIKAZS, HICAZS; AcctMvmtData_Cutoff in FinTS 4.1), such as 360 or 450 at Sparkassen, since
a bank may refuse a query without start date (9010). Where the bank states no such period, or to lies before that
day, the query names no start date. A from goes out as passed, also before that day: the bank decides, and a refusal
fails the call with its error. Banks typically ask for a TAN beyond 90 days ago, so a query without from may need one;
pass a from within the last 90 days to avoid that.
Logging
logger: (direction, message) => ... receives every message, MessageDirection.outgoing or .incoming:
- PIN and TANs become
***, with stated sizes adjusted so the log does not tell their length. - A FinTS 4.1 answer that is not readable XML, where PIN and TAN cannot be found, arrives as a placeholder.
- Messages still hold account data, card numbers among them: log them for diagnosis only, and only where the user agreed.
toString leaves data out:
Account,Balance,TransactionandTanMediumshow only the last four characters of an IBAN, account or card number: no amounts, names or purposes, nor a TAN medium's name, which may hold the user's name.HoldingsStatementshows its account so, the day and the number of holdings,Holdingonly its kind of quantity: no securities, quantities or values. APriceorQuantityalone shows its value, as anAmountdoes, like52.70 EURor16.8211.FinTsFeedbackshows only the return code, likeFinTsFeedback(3072), andBankMessageneither subject nor text. Showcode,textandparameters, orsubjectandtext, to the user.
A FinTsBankException's message holds the bank's error texts and parameters. A FormatException of Mt940, Camt,
Amount.parseDecimal or FlickerCode.parse prints only its message; keep its source, which may hold bank data, out
of logs and crash reports.
FinTS 4.1
FinTs4Client speaks the XML protocol, in namespace 4.1.1 by default; pass namespaces: FinTs4Namespaces.v41 for
plain 4.1. FinTs4Client.queryVersions(...) runs the version inquiry in namespace 0.0.
The generated requests validate against the official XML schemas (release 2021-11-12) for every supported version of
every business transaction, depot holdings (PortfList 1) included, in both namespaces:
test/v4_schema_test.dartchecks this whenxmllintis installed andFINTS4_SCHEMASpoints to the unzipped schemas (4.1.1/and4.1/from www.hbci-zka.de/spec/xmlschema/).FINTS4_DUMP=<dir>writes a whole login's requests for other tools.
The product registration ID goes into ProductName, as into Produktbezeichnung in FinTS 3.0, and base64 encoded into
ProductID.
An answer whose body, or a part like a response list, is encrypted or compressed (XML-Syntax V) fails with
FinTsProtocolException, as the client cannot read it.
The card queries of the Deutsche Kreditwirtschaft are FinTS 3.0 business transactions; the 4.1 schemas define none for card bookings or balances, so a 4.1 card account takes the regular queries, as any other account.
The challenges of FinTs4Client cannot be suspended: TanChallenge.suspendable is always false, and resume fails
with a StateError.
App approval (decoupled) is a FinTS 3.0 feature; the 4.1 documents and schemas define neither it nor polling parameters.
For a 4.1 bank answering 3955, the client uses the same flow with default timing: checks every 2 seconds, the first
after 2, at most 60 times.
Very few banks run FinTS 4.1, so this client is experimental, tested against simulated banks only. Use 3.0 unless your bank says otherwise.
Platform notes
Web. Web builds cannot reach banks directly, as bank servers send no CORS headers. Use a backend proxy or a native/desktop target.
URLs. FinTsConfig.url is the URL as WHATWG URL writes it and a browser sends it:
https://bank.examplebecomeshttps://bank.example/;- an IPv6 address takes its short form, like
[2001:db8::1]; 127.1becomes127.0.0.1;- a
'in the query becomes%27; - a non-ASCII host becomes punycode, like
xn--bcher-kva.exampleforbücher.example.
An ArgumentError rejects:
- a URL that is not
https, except plainhttpto a loopback address (localhost,127.x.x.x,[::1]) underFinTsConfig.allowInsecureUrl, for a local test server; - a URL with a user name or password;
- a URL WHATWG URL refuses, like one with a port above 65535 or the host
bank.123; - a host with characters beyond ASCII and the letters of ISO 8859-1 and Latin Extended-A (like
ä,éorł), or with one of the few such letters a browser maps to others, likeij: the package lacks that mapping (UTS #46), applied by browsers before punycode.
HTTP transport. The default HttpTransport:
- follows no redirects, as the request carries the PIN, and rejects the answer of an HTTP client that follows one anyway or answers from another URL;
- aborts a request after 90 seconds and rejects responses over 16 MiB (constructor parameters that must be positive; the timeout at most 2147483647 milliseconds, the longest a timer waits on the web);
- on native platforms follows
HTTPS_PROXY/NO_PROXYfor https, but sends plainhttpto a loopback address (allowInsecureUrl) directly, never throughHTTP_PROXY.
This holds also inside package:http's runWithClient. A client passed to HttpTransport serves every request and
chooses its proxies itself; for an authenticating proxy (package:http/io_client.dart), pass
HttpTransport(client: IOClient(HttpClient()..findProxy = … ..addProxyCredentials(…))).
In a browser, HttpTransport uses fetch directly, not package:http's BrowserClient, even in place of one that
runWithClient sets, unless it sends credentials (withCredentials) or is of a subclass. The fetch client:
- gives the HTTP status of an answer whose Content-Length is no number, like
8, 8, whereBrowserClientfails before seeing it; - fails a redirect with 'The server redirects the request, which the client does not follow'.
Custom transport. Pass a custom FinTsTransport (post(url, body, contentType: …, abortTrigger: …)) as
FinTsClientOptions.transport for proxies, certificate pinning or test doubles. It should:
- report failures as
FinTsTransportException, withstatusCodewhere the bank answered with an HTTP error; of other errors the client keeps only the message or type (see Errors); - stop the request once
abortTriggercompletes, as package:http'sAbortableRequestdoes with the same trigger, soclose()need not wait for the answer (see Closing).
The client closes its transport when closed, so give each client its own.
Message size. Instead of sending a message over the bank's maximum (BankInfo.maxMessageSize), the client raises
FinTsProtocolException. Where the maximum rules out a login, it first fetches the parameters anew, as for the PIN
length (see Errors).
Text encoding. FinTS 3.0 uses ISO 8859-1, but some banks send UTF-8, as in the TAN medium name Max’s iPhone.
- The client sends ISO 8859-1 wherever text fits, UTF-8 only where it does not, as for
’. - Values the bank issued go back exactly as sent: dialog ID, customer system ID, TAN order reference, position to
continue at, and a TAN medium name from the bank's list, like
Mein Händyin UTF-8. FinTsFeedback.parametersandTanChallenge.referencehold one character per byte sent (ISO 8859-1), so UTF-8 text there reads as ISO 8859-1 shows it.
Testing
The tests use simulated banks (test/support) written from the specification, not recorded real traffic. A bank
deviating from it may fail in ways they do not show; please report such cases.
The specification is not the whole story: banks offer versions it does not define, such as ING's balance in HBCI 2.2's
version 5. test/bank_compatibility_test.dart runs the client against the parameter data of some 30 banks, as other
FinTS libraries and their issue trackers recorded them (test/fixtures/banks/, bank-level data only, with sources).
Add a bank there when its users report a problem; a known gap stays in as a test of the current outcome, which fails
once the gap is closed.
Scope
This package reads data: no payments or securities orders, nor HBCI signature procedures (RAH/RDH chip cards and key files), as German consumer banks use PIN/TAN for FinTS.
Example app
example/ is a minimal Flutter app: pick a bank from the FinTS institute list, log in, approve with a TAN,
and browse balances and transactions.
cp fints_secrets.example.json fints_secrets.json # once; put your product ID in it (git-ignored)
cd example
flutter run --dart-define-from-file=../fints_secrets.json
Development
dart pub get
dart test
dart run tool/cli.dart # command-line demo; needs FINTS_URL, FINTS_BLZ, FINTS_USER (product ID from fints_secrets.json)
License
BSD 3-Clause (see LICENSE); commercial use is allowed. Apps shipping this library must reproduce the
copyright notice and license text, such as on their open-source licenses screen; Flutter collects package licenses
automatically, and showLicensePage(context: context) shows them.
Libraries
- fints
- FinTS 3.0 and 4.1 client for German banks: accounts, balances, transactions and depot holdings.