Skip to content

A payments mailbox ​

The usual integration: a mailbox (or a mail forward) receives the notifications of every bank you use, and a job reads the new mails, finds the bank, and pairs each payment with an open order. BankMailsParser does the detection. This recipe reads a folder of .eml files: four bank mails, a newsletter, and a Tatra banka notification sent from a look-alike domain.

Source: examples/mailbox

The mailbox ​

FileFromContent
01-tatra-banka.emlb-mail@tatrabanka.skb-mail notification, 12.31 EUR
02-cardpay.emlcardpay@tatrabanka.skCardPay result, 33.99 EUR
03-vub.emlnotifikacie@vub.skVÚB payment, 13.37 EUR
04-csob-sk.emlinfo24@csob.skČSOB SK SEPA payment, 1150.00 EUR
05-newsletter.emlnews@shop.examplenot a bank mail
06-forged-sender.emlb-mail@tatrabanka.sk.evil.examplethe Tatra banka mail again, from another domain

The sender addresses are examples; use the ones your bank really sends from. One of the mails, headers included:

text
From: "Tatra banka" <b-mail@tatrabanka.sk>
To: payments@shop.example
Subject: b-mail notifikacia
Date: Fri, 16 Jan 2015 12:52:03 +0100
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Vazeny klient,

16.1.2015 12:51 bol zostatok Vasho uctu SK9812353347235 zvyseny o 12,31 EUR.
uctovny zostatok:                            142,11 EUR
aktualny zostatok:                           142,11 EUR
disponibilny zostatok:                       142,11 EUR

Popis transakcie: CCINT 1100/000000-261426464
Referencia platitela: /VS1234056789/SS/KS
Informacia pre prijemcu: test-sprava

S pozdravom

TATRA BANKA, a.s.

http://www.tatrabanka.sk

Poznamka: Vase pripomienky alebo otazky tykajuce sa tejto spravy alebo inej nasej sluzby nam poslite, prosim, pouzitim kontaktneho formulara na nasej Web stranke.

Odporucame Vam mazat si po precitani prichadzajuce bmail notifikacie. Historiu uctu najdete v ucelenom tvare v pohyboch cez internet banking a nemusite ju pracne skladat zo starych bmailov.

The code ​

php
<?php

declare(strict_types=1);

// Read every mail of a payments mailbox, let BankMailsParser pick the bank parser from the sender
// and the body, and match each transaction to an open order by its variable symbol and amount.

require __DIR__ . '/vendor/autoload.php';

use Tomaj\BankMailsParser\BankMailsParser;
use Tomaj\BankMailsParser\Exception\ParseException;
use Tomaj\BankMailsParser\Exception\UnsupportedBankException;

/**
 * The sender address, the subject and the body of a plain-text RFC 5322 message.
 *
 * @return array{string, string, string}
 */
function readMail(string $path): array
{
    [$head, $body] = explode("\n\n", str_replace("\r\n", "\n", (string) file_get_contents($path)), 2);
    $headers = iconv_mime_decode_headers($head, ICONV_MIME_DECODE_CONTINUE_ON_ERROR, 'UTF-8');
    $from = (string) ($headers['From'] ?? '');
    $address = preg_match('/<([^>]+)>/', $from, $match) === 1 ? $match[1] : $from;

    return [$address, (string) ($headers['Subject'] ?? ''), $body];
}

// Open orders by variable symbol, with the amount the customer has to pay
$orders = [
    '1234056789' => '12.31 EUR',
    '5000001234' => '33.99 EUR',
    '9999999999' => '13.37 EUR',
    '212049000' => '1200.00 EUR',
];

$parser = new BankMailsParser();

foreach (glob(__DIR__ . '/mailbox/*.eml') ?: [] as $path) {
    [$sender, $subject, $body] = readMail($path);
    echo basename($path), " from {$sender}\n";

    try {
        // the sender restricts the choice to the parsers of that bank's domain
        $transactions = $parser->parseAll($body, $sender, $subject);
    } catch (UnsupportedBankException $e) {
        echo "  skipped: {$e->getMessage()}\n";
        continue;
    } catch (ParseException $e) {
        // a bank mail that could not be read: keep it for a human, never guess
        echo '  needs review: ', $e::class, ": {$e->getMessage()}\n";
        continue;
    }

    foreach ($transactions as $transaction) {
        $amount = $transaction->money?->format() ?? 'no amount';
        $vs = $transaction->vs ?? '-';
        $expected = $orders[$vs] ?? null;

        $verdict = match (true) {
            $transaction->res !== null && $transaction->res !== 'OK' => "card payment result {$transaction->res}",
            $expected === null => 'no open order with this variable symbol',
            $expected !== $amount => "amount differs, the order expects {$expected}",
            default => 'order paid',
        };
        echo "  VS {$vs}, {$amount}: {$verdict}\n";
    }
}

The output ​

text
01-tatra-banka.eml from b-mail@tatrabanka.sk
  VS 1234056789, 12.31 EUR: order paid
02-cardpay.eml from cardpay@tatrabanka.sk
  VS 5000001234, 33.99 EUR: order paid
03-vub.eml from notifikacie@vub.sk
  VS 9999999999, 13.37 EUR: order paid
04-csob-sk.eml from info24@csob.sk
  VS 212049000, 1150.00 EUR: amount differs, the order expects 1200.00 EUR
05-newsletter.eml from news@shop.example
  skipped: No parser found for the supplied sender.
06-forged-sender.eml from b-mail@tatrabanka.sk.evil.example
  skipped: No parser found for the supplied sender.

How the facade decides ​

  1. The sender limits the candidates. Every parser lists its bank's domains (bankDomains()). With a sender, only parsers whose domain matches the sender's host (the domain itself or a subdomain) are asked. b-mail@tatrabanka.sk.evil.example matches no bank, so the forged mail is UnsupportedBankException even though its body is a perfect Tatra banka notification.
  2. The body picks the parser. Each remaining parser's supports() checks the bank's own header lines. tatrabanka.sk has three parsers (b-mail, CardPay, statements); the body decides between them.
  3. Exactly one must match. No match is UnsupportedBankException, more than one is AmbiguousBankException. The facade never takes "the first that fits".
Flow of BankMailsParser: filter parsers by sender domain, ask each supports(), throw UnsupportedBankException for none and AmbiguousBankException for more than one, otherwise return the parser's parseAll() resultFlow of BankMailsParser: filter parsers by sender domain, ask each supports(), throw UnsupportedBankException for none and AmbiguousBankException for more than one, otherwise return the parser's parseAll() result

Matching payments to orders ​

The recipe pairs a transaction with an order only when both the variable symbol and the amount match, and treats a CardPay result other than OK as unpaid. The ČSOB payment above has the right symbol but the wrong amount, so it is reported instead of booked. That is deliberate:

  • The variable symbol can come from a message the payer wrote. Any payer can type your order's symbol.
  • The From header is not authenticated by this library. Check the mail's DKIM/SPF result (your mail server adds it as Authentication-Results) before you trust a sender, and verify CardPay signatures. See Security.
  • parseAll(), not tryParse(), in a mailbox loop: a ČSOB mail with two transactions makes parse() throw and tryParse() return null, and you would silently skip two payments.
  • Keep a mail that throws InvalidEmailFormatException for a human. It is a bank mail the parser could not read completely, and the library does not guess.

Reading real mail: the readMail() function above only handles plain-text messages. For MIME mails (base64 or quoted-printable bodies, HTML parts) use a mail library such as php-mime-mail-parser or zbateson/mail-mime-parser, or tomaj/imap-mail-downloader for IMAP, and pass the decoded text/plain part.

Released under the MIT License.