Files
itflow/functions/card_expiry.php

440 lines
25 KiB
PHP

<?php
/*
* Saved cards running out (DB 4.3.8). Each night cardExpiryNightly() (cron/nightly_tasks.php):
*
* - Reads back from Stripe the saved cards that run out next month or ran out lately. Stripe
* updates a saved card when the bank issues a new one - a new expiry, often a new number - and
* ITFlow only had the card as it was saved, so it called a card expired that Stripe still
* charges. The new expiry is kept, and nobody is asked about a card the bank replaced.
* - Tells the client and the team about each card on autopay for an active recurring invoice
* that is running out: a month before its month, again in it - or once, just after, when it ran
* out without a word. The client's primary and billing contacts get an email with a link to add
* the new card with no sign-in (guest/guest_card_update.php), when Settings > Invoices says so
* and the client isn't left out of reminders; the team gets a notification each time.
*
* The link adds the new card through Stripe's form and puts it in place of the old one on every
* recurring invoice the old one paid (cardUpdateFinish()). It works while the card still pays one.
*/
const CARD_EXPIRY_CHECK_LIMIT = 200; // cards read back from Stripe a night, at most - the ones running out soonest first
const CARD_EXPIRY_CHECK_MONTHS = 6; // a card that ran out longer ago than this isn't read back any more
const CARD_EXPIRY_LATE_DAYS = 60; // a card on autopay that ran out within this long, unannounced, still gets its client emailed
/** Whether the 4.3.8 database update is in. */
function cardExpiryReady(): bool
{
return smsColumnExists('client_saved_payment_methods', 'saved_payment_update_key');
}
/** Whether clients are emailed about their autopay card running out - Settings > Invoices > Paid online. */
function cardExpiryEmailOn(): bool
{
global $mysqli;
return settingsColumnExists($mysqli, 'config_invoice_card_expiry_reminders')
&& intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT config_invoice_card_expiry_reminders FROM settings WHERE company_id = 1"))[0] ?? 0) === 1;
}
/** A card as saved_payment_description keeps it, from Stripe's card - "visa - 4242 | Exp 9/2028" (billingCardParts() reads it). */
function cardDescription($card): string
{
return $card ? "{$card->brand} - {$card->last4} | Exp " . intval($card->exp_month) . '/' . intval($card->exp_year) : 'Card';
}
/** The month a card is good to the end of, in words - "January 2027". */
function cardExpiryMonth(int $yyyymm): string
{
return $yyyymm ? date('F Y', mktime(0, 0, 0, $yyyymm % 100, 1, intdiv($yyyymm, 100))) : '';
}
/*
* Read a saved card back from Stripe and keep what Stripe has now - its expiry and last four digits
* change when the bank replaces the card. $row has saved_payment_id, saved_payment_client_id,
* saved_payment_provider_method and saved_payment_description. The description it has now, or null
* when Stripe couldn't say (it is left as it was).
*/
function cardRefresh(array $row, $stripe = null): ?string
{
global $mysqli;
$stripe = $stripe ?: billingStripeClient();
$id = intval($row['saved_payment_id']);
if (!$stripe || !$id) {
return null;
}
$checked = cardExpiryReady() ? ", saved_payment_checked_at = NOW()" : '';
try {
$pm = $stripe->paymentMethods->retrieve((string) $row['saved_payment_provider_method'], []);
} catch (\Throwable $e) {
logApp("Stripe", "warning", "Saved card $id couldn't be read back from Stripe: " . $e->getMessage());
if ($checked !== '') {
mysqli_query($mysqli, "UPDATE client_saved_payment_methods SET saved_payment_checked_at = NOW() WHERE saved_payment_id = $id");
}
return null;
}
if (empty($pm->card)) {
return (string) $row['saved_payment_description'];
}
$now = cardDescription($pm->card);
$was = (string) $row['saved_payment_description'];
if ($now === $was) {
if ($checked !== '') {
mysqli_query($mysqli, "UPDATE client_saved_payment_methods SET saved_payment_checked_at = NOW() WHERE saved_payment_id = $id");
}
return $now;
}
// A new expiry is a fresh start for the reminders - and the link the old ones sent stops
$restart = cardExpiryReady() && billingCardParts($now)['expires'] !== billingCardParts($was)['expires'] ? ", saved_payment_update_key = NULL" : '';
mysqli_query($mysqli, "UPDATE client_saved_payment_methods SET saved_payment_description = '" . escapeSql($now) . "'$checked$restart WHERE saved_payment_id = $id");
$old = billingCardParts($was);
$new = billingCardParts($now);
$client_id = intval($row['saved_payment_client_id']);
logAudit("Client", "Edit", escapeSql("Stripe has the card the bank replaced: " . $old['label'] . ($old['exp'] !== '' ? " (exp {$old['exp']})" : '') . " is now " . $new['label'] . ($new['exp'] !== '' ? " (exp {$new['exp']})" : '')), $client_id);
return $now;
}
/*
* The cards on autopay for active recurring invoices, with their clients and the recurring invoices
* they pay - saved id => ['card' => its row with client_name and client_reminders, 'recurring' =>
* [['id', 'number', 'title', 'amount', 'currency', 'period', 'next'], ...]]. $card_id for one card.
*/
function cardAutopayCards(int $card_id = 0): array
{
global $mysqli;
$provider = billingStripeProvider();
if (!$provider) {
return [];
}
$cards = [];
$sql = mysqli_query($mysqli, "SELECT saved_payment_id, saved_payment_client_id, saved_payment_provider_method, saved_payment_description,
saved_payment_reminded_expiry, saved_payment_reminded, saved_payment_update_key, client_name, client_reminders,
recurring_invoice_id, recurring_invoice_prefix, recurring_invoice_number, recurring_invoice_scope, recurring_invoice_amount,
recurring_invoice_currency_code, recurring_invoice_frequency, recurring_invoice_next_date
FROM client_saved_payment_methods
JOIN clients ON client_id = saved_payment_client_id AND client_archived_at IS NULL
JOIN recurring_payments ON recurring_payment_saved_payment_id = saved_payment_id
JOIN recurring_invoices ON recurring_invoice_id = recurring_payment_recurring_invoice_id AND recurring_invoice_client_id = saved_payment_client_id
AND recurring_invoice_status = 1 AND recurring_invoice_archived_at IS NULL
WHERE saved_payment_provider_id = " . intval($provider['payment_provider_id']) . ($card_id ? " AND saved_payment_id = $card_id" : '') . "
ORDER BY saved_payment_id, recurring_invoice_number");
while ($row = mysqli_fetch_assoc($sql)) {
$id = intval($row['saved_payment_id']);
$cards[$id]['card'] = $cards[$id]['card'] ?? $row;
$number = billingNumber('recurring', $row);
$cards[$id]['recurring'][] = [
'id' => intval($row['recurring_invoice_id']),
'number' => $number,
'title' => trim((string) $row['recurring_invoice_scope']) !== '' ? trim((string) $row['recurring_invoice_scope']) : $number,
'amount' => floatval($row['recurring_invoice_amount']),
'currency' => (string) $row['recurring_invoice_currency_code'],
'period' => recurringInvoicePeriodWord($row['recurring_invoice_frequency']),
'next' => (string) $row['recurring_invoice_next_date'],
];
}
return $cards;
}
/* The recurring invoices a card pays, in a few words - "REC-12 and REC-14". */
function cardRecurringNumbers(array $recurring): string
{
$numbers = array_column($recurring, 'number');
return count($numbers) > 1 ? implode(', ', array_slice($numbers, 0, -1)) . ' and ' . end($numbers) : (string) ($numbers[0] ?? '');
}
/** The no-sign-in page to put a new card in place of saved card $card_id, with its key. */
function cardUpdateUrl(int $card_id, string $key): string
{
global $config_base_url;
return "https://$config_base_url/guest/guest_card_update.php?card=$card_id&key=" . rawurlencode($key);
}
/*
* The night's work (cron/nightly_tasks.php): cards read back from Stripe, then clients and the team
* told about the cards on autopay running out. $now is the time to go by - now, unless a test says.
* ['checked', 'updated', 'emailed', 'notified'].
*/
function cardExpiryNightly(?int $now = null): array
{
$now = $now ?? time();
global $mysqli;
$done = ['checked' => 0, 'updated' => 0, 'emailed' => 0, 'notified' => 0];
$provider = billingStripeProvider();
if (!$provider || !cardExpiryReady() || devModeOn()) {
return $done;
}
$stripe = billingStripeClient();
// Read back the cards that run out next month or ran out lately - soonest first, once a day
$expiry = paymentCardExpirySql();
$from = intval(date('Ym', strtotime('first day of -' . CARD_EXPIRY_CHECK_MONTHS . ' months', $now)));
$to = intval(date('Ym', strtotime('first day of next month', $now)));
$sql = mysqli_query($mysqli, "SELECT saved_payment_id, saved_payment_client_id, saved_payment_provider_method, saved_payment_description
FROM client_saved_payment_methods
WHERE saved_payment_provider_id = " . intval($provider['payment_provider_id']) . " AND $expiry BETWEEN $from AND $to
AND (saved_payment_checked_at IS NULL OR saved_payment_checked_at < NOW() - INTERVAL 20 HOUR)
ORDER BY $expiry ASC, saved_payment_id ASC LIMIT " . CARD_EXPIRY_CHECK_LIMIT);
while ($row = mysqli_fetch_assoc($sql)) {
$fresh = cardRefresh($row, $stripe);
$done['checked']++;
if ($fresh !== null && $fresh !== (string) $row['saved_payment_description']) {
$done['updated']++;
}
}
// Tell the client and the team about each card on autopay running out
$this_month = intval(date('Ym', $now));
$soon = intval(date('Ym', strtotime('+30 days', $now)));
$email_on = cardExpiryEmailOn() && billingEmailReady();
foreach (cardAutopayCards() as $card_id => $entry) {
$card = $entry['card'];
$parts = billingCardParts($card['saved_payment_description']);
$exp = intval($parts['expires']);
if (!$exp || $exp > $soon) {
continue;
}
$stage = $exp > $this_month ? 1 : 2;
$same = intval($card['saved_payment_reminded_expiry']) === $exp;
if ($same && intval($card['saved_payment_reminded']) >= $stage) {
continue;
}
// A card that ran out long ago, never mentioned - the team hears, the client isn't emailed out of the blue
$ended = mktime(0, 0, 0, $exp % 100 + 1, 1, intdiv($exp, 100));
$stale = $exp < $this_month && $ended < $now - CARD_EXPIRY_LATE_DAYS * 86400;
$key = $same && (string) $card['saved_payment_update_key'] !== '' ? (string) $card['saved_payment_update_key'] : bin2hex(random_bytes(24));
$why = '';
$sent = [];
if (!$email_on) {
$why = cardExpiryEmailOn() ? "email isn't set up" : "emailing clients about it is off in Settings > Invoices";
} elseif (!intval($card['client_reminders'])) {
$why = 'the client is left out of reminders';
} elseif ($stale) {
$why = 'it ran out more than ' . CARD_EXPIRY_LATE_DAYS . ' days ago';
} else {
$sent = billingMailCardExpiring($entry, $exp, $stage === 2 && $exp < $this_month ? 'expired' : ($stage === 2 ? 'this_month' : 'soon'), cardUpdateUrl($card_id, $key));
$why = $sent ? '' : 'it has no primary or billing contact with an email address';
}
if ($sent) {
$done['emailed']++;
}
$client = (string) $card['client_name'];
$what = "$client's {$parts['label']} on autopay";
$when = $exp < $this_month ? 'ran out at the end of ' . cardExpiryMonth($exp) : ($exp === $this_month ? 'runs out at the end of this month' : 'runs out at the end of ' . cardExpiryMonth($exp));
$pays = count($entry['recurring']) > 1 ? 'it pays recurring invoices ' . cardRecurringNumbers($entry['recurring']) : 'it pays recurring invoice ' . cardRecurringNumbers($entry['recurring']);
$told = $sent ? "$client was emailed a link to add their new card" . ($same ? ' again' : '') : "$client wasn't emailed - $why";
$first = $entry['recurring'][0]['id'];
appNotify("Card Expiring", escapeSql("$what $when ({$parts['exp']}) - $pays" . ($exp < $this_month ? ', and its charges will fail until the card is replaced' : '') . ". $told."),
count($entry['recurring']) > 1 ? "/agent/recurring_invoices.php?client_id=" . intval($card['saved_payment_client_id']) : "/agent/recurring_invoice.php?recurring_invoice_id=$first",
intval($card['saved_payment_client_id']), count($entry['recurring']) > 1 ? 0 : $first);
$done['notified']++;
mysqli_query($mysqli, "UPDATE client_saved_payment_methods SET saved_payment_reminded_expiry = $exp, saved_payment_reminded = $stage, saved_payment_update_key = '" . escapeSql($key) . "'
WHERE saved_payment_id = $card_id");
foreach ($entry['recurring'] as $recurring) {
billingLog('recurring', $recurring['id'], 'Autopay', "Its autopay card, {$parts['label']}, $when" . ($sent ? ' - ' . $client . "'s contacts were emailed a link to add their new card: " . implode(', ', $sent) : " - $client wasn't emailed: $why"));
}
}
return $done;
}
/* ------------------------------------------------------- The link: a new card */
/*
* The saved card a link is for - $card_id and its key - with its client: the card's row, client_name,
* client_currency_code. Null when the key is wrong, or the card has none (replaced, or never reminded).
*/
function cardUpdateRow($card_id, $key): ?array
{
global $mysqli;
$card_id = intval($card_id);
if (!$card_id || !is_string($key) || strlen($key) < 32 || !cardExpiryReady()) {
return null;
}
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT saved_payment_id, saved_payment_client_id, saved_payment_provider_id, saved_payment_provider_method, saved_payment_description,
saved_payment_update_key, client_name, client_currency_code
FROM client_saved_payment_methods JOIN clients ON client_id = saved_payment_client_id
WHERE saved_payment_id = $card_id LIMIT 1"));
if (!$row || (string) $row['saved_payment_update_key'] === '' || !hash_equals((string) $row['saved_payment_update_key'], $key)) {
return null;
}
return $row;
}
/** What the client agrees to with the new card, raw - the recurring invoices, the card fee when they pay one, and until when. */
function cardUpdateConsentText(array $card, array $recurring): string
{
$company = billingCompany();
$fee = billingCardFeeTerms(billingCardFeeFor($card['saved_payment_client_id']), (string) ($recurring[0]['currency'] ?? ''));
return 'I authorize ' . ($company['company_name'] ?? 'you') . ' to charge the card I add, in place of ' . billingCardParts($card['saved_payment_description'])['label']
. ', for each invoice from recurring invoice' . (count($recurring) > 1 ? 's ' : ' ') . cardRecurringNumbers($recurring) . ' on its due date'
. ($fee !== '' ? ", plus a card fee of $fee" : '') . ', until autopay is turned off.';
}
/*
* Start adding the new card from the link: a Checkout Session that saves a card to the client's Stripe
* customer - the one the old card is on. Who agreed and to what goes in its metadata, for
* cardUpdateFinish(). Its client secret, or '' with $error for the client. $name and $email raw.
*/
function cardUpdateCheckoutStart(array $card, $name, $email, &$error = ''): string
{
global $config_base_url;
$card_id = intval($card['saved_payment_id']);
$client_id = intval($card['saved_payment_client_id']);
$entry = cardAutopayCards($card_id)[$card_id] ?? null;
$name = trim(mb_substr(preg_replace('/\s+/u', ' ', (string) $name) ?? '', 0, 80));
$email = trim(mb_substr((string) $email, 0, 120));
$customer = billingStripeCustomer($client_id);
$stripe = billingStripeClient();
if (!$entry || !$stripe || $customer === '') {
$error = "The card can't be changed from this link just now - get in touch and we'll help.";
return '';
}
if ($name === '') {
$error = 'Enter your name.';
return '';
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error = 'Enter your email address, for the confirmation.';
return '';
}
$ids = ['itflow_card_update_id' => $card_id, 'itflow_client_id' => $client_id];
try {
$session = $stripe->checkout->sessions->create([
'mode' => 'setup',
'ui_mode' => 'embedded_page',
'currency' => strtolower($entry['recurring'][0]['currency'] ?: ($card['client_currency_code'] ?: 'usd')),
'customer' => $customer,
'payment_method_types' => ['card'],
'return_url' => "https://$config_base_url/guest/guest_post.php?guest_card_update_done=1&card=$card_id&key=" . rawurlencode((string) $card['saved_payment_update_key']) . '&session_id={CHECKOUT_SESSION_ID}',
'metadata' => $ids + [
'itflow_consent_name' => $name,
'itflow_consent_email' => $email,
'itflow_consent' => mb_substr(cardUpdateConsentText($card, $entry['recurring']), 0, 500),
],
'setup_intent_data' => ['description' => 'New card for autopay on recurring invoice' . (count($entry['recurring']) > 1 ? 's ' : ' ') . cardRecurringNumbers($entry['recurring']), 'metadata' => $ids],
]);
return (string) $session->client_secret;
} catch (\Throwable $e) {
if (billingStripeCustomerGone($e)) {
billingStripeCustomerForget($client_id, $customer);
$error = "The card can't be changed from this link any more - get in touch and we'll help.";
return '';
}
logApp("Stripe", "error", "Adding a new card for saved card $card_id couldn't start: " . $e->getMessage());
}
$error = "Card details can't be taken just now - try again in a few minutes.";
return '';
}
/** The new card a Stripe session put in place, when it has been already ("Visa •••• 4242"), or null. */
function cardUpdateDone(string $session_id): ?string
{
global $mysqli;
if (!preg_match('/^cs_[A-Za-z0-9_]{8,250}$/', $session_id)) {
return null;
}
$done = mysqli_fetch_row(mysqli_query($mysqli, "SELECT history_description FROM history WHERE history_status = 'Autopay' AND history_description LIKE 'Autopay card changed from %'
AND history_description LIKE '%" . escapeSql(addcslashes($session_id, '%_\\')) . "' LIMIT 1"));
return $done ? (preg_match('/ to (.+?) by /u', (string) $done[0], $m) ? $m[1] : '') : null;
}
/*
* Finish once Stripe sends the client back from cardUpdateCheckoutStart()'s form: the session checked
* with Stripe - complete, for this card and the client's customer - the new card saved, and put in
* place of the old one on every recurring invoice the old one paid. Kept in each one's history with
* what they agreed to, logged, the team told and the client sent a confirmation. The link stops
* working; coming back to the same address again changes nothing. ['ok', 'again' => done already,
* 'card' => "Visa •••• 4242", 'emailed', 'error' => for the client].
*/
function cardUpdateFinish(array $card, $session_id): array
{
global $mysqli;
$fail = function ($error) {
return ['ok' => false, 'again' => false, 'emailed' => false, 'card' => '', 'error' => $error];
};
$session_id = (string) $session_id;
$provider = billingStripeProvider();
$stripe = billingStripeClient();
$card_id = intval($card['saved_payment_id']);
$client_id = intval($card['saved_payment_client_id']);
$customer = billingStripeCustomer($client_id);
if (!$provider || !$stripe || $customer === '' || !preg_match('/^cs_[A-Za-z0-9_]{8,250}$/', $session_id)) {
return $fail("The card couldn't be changed from that link - get in touch and we'll help.");
}
// The same return twice at once - a double click, a reload - takes turns, and the second finds it done
$lock = "itflow_card_update_$card_id";
mysqli_query($mysqli, "SELECT GET_LOCK('$lock', 15)");
try {
try {
$session = $stripe->checkout->sessions->retrieve($session_id, []);
} catch (\Throwable $e) {
logApp("Stripe", "error", "A new card for saved card $card_id couldn't be confirmed ($session_id): " . $e->getMessage());
return $fail("We couldn't confirm your card with Stripe just now - reload this page in a minute, or get in touch.");
}
$meta = $session->metadata ? $session->metadata->toArray() : [];
if ((string) $session->mode !== 'setup' || intval($meta['itflow_card_update_id'] ?? 0) !== $card_id || (string) $session->customer !== $customer) {
return $fail("That card isn't for this link - nothing has changed.");
}
$done = cardUpdateDone($session_id);
if ($done !== null) {
return ['ok' => true, 'again' => true, 'emailed' => false, 'card' => $done, 'error' => ''];
}
$entry = cardAutopayCards($card_id)[$card_id] ?? null;
if (!$entry) {
return $fail("This card doesn't pay any invoices automatically now, so nothing was changed.");
}
try {
if ((string) $session->status !== 'complete' || empty($session->setup_intent)) {
return $fail("Your new card wasn't added - try again.");
}
$setup_intent = $stripe->setupIntents->retrieve(is_string($session->setup_intent) ? $session->setup_intent : $session->setup_intent->id, []);
$pm_id = is_string($setup_intent->payment_method) ? $setup_intent->payment_method : (string) ($setup_intent->payment_method->id ?? '');
if ((string) $setup_intent->status !== 'succeeded' || $pm_id === '') {
return $fail("Your new card wasn't added - try again.");
}
$pm = $stripe->paymentMethods->retrieve($pm_id, []);
} catch (\Throwable $e) {
logApp("Stripe", "error", "A new card for saved card $card_id couldn't be confirmed ($session_id): " . $e->getMessage());
return $fail("We couldn't confirm your card with Stripe just now - reload this page in a minute, or get in touch.");
}
// The new card - saved once, however often it comes back
$provider_id = intval($provider['payment_provider_id']);
$pm_sql = escapeSql($pm_id);
$description = cardDescription($pm->card ?? null);
$new_id = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT saved_payment_id FROM client_saved_payment_methods
WHERE saved_payment_client_id = $client_id AND saved_payment_provider_id = $provider_id AND saved_payment_provider_method = '$pm_sql' LIMIT 1"))[0] ?? 0);
if (!$new_id) {
mysqli_query($mysqli, "INSERT INTO client_saved_payment_methods SET saved_payment_provider_method = '$pm_sql', saved_payment_description = '" . escapeSql($description) . "',
saved_payment_client_id = $client_id, saved_payment_provider_id = $provider_id, saved_payment_created_at = NOW(), saved_payment_checked_at = NOW()");
$new_id = intval(mysqli_insert_id($mysqli));
}
// Every recurring invoice of the client's the old card paid - paused ones too, which would fail on it
mysqli_query($mysqli, "UPDATE recurring_payments JOIN recurring_invoices ON recurring_invoice_id = recurring_payment_recurring_invoice_id
SET recurring_payment_saved_payment_id = $new_id
WHERE recurring_payment_saved_payment_id = $card_id AND recurring_invoice_client_id = $client_id");
mysqli_query($mysqli, "UPDATE client_saved_payment_methods SET saved_payment_update_key = NULL WHERE saved_payment_id = $card_id");
$old = billingCardParts($card['saved_payment_description'])['label'];
$new = billingCardParts($description)['label'];
$name = trim((string) ($meta['itflow_consent_name'] ?? '')) ?: 'The client';
$email = trim((string) ($meta['itflow_consent_email'] ?? ''));
$who = $email !== '' ? "$name ($email)" : $name;
$consent = trim((string) ($meta['itflow_consent'] ?? ''));
foreach ($entry['recurring'] as $recurring) {
billingLog('recurring', $recurring['id'], 'Autopay', "Autopay card changed from $old to $new by $who from the card reminder's link" . ($consent !== '' ? ", agreeing: \"$consent\"" : '') . " - Stripe $session_id");
}
$numbers = cardRecurringNumbers($entry['recurring']);
logAudit("Recurring Invoice", "Auto Payment", escapeSql("Guest $who put $new in place of $old for autopay on $numbers from the card reminder's link"), $client_id, $entry['recurring'][0]['id']);
appNotify("Autopay", escapeSql("$name put $new in place of $old for {$card['client_name']}'s autopay on $numbers"),
count($entry['recurring']) > 1 ? "/agent/recurring_invoices.php?client_id=$client_id" : "/agent/recurring_invoice.php?recurring_invoice_id=" . $entry['recurring'][0]['id'],
$client_id, count($entry['recurring']) > 1 ? 0 : $entry['recurring'][0]['id']);
$emailed = $email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL) && billingEmailReady() && billingMailCardUpdated($email, $name, $entry, $old, $new);
return ['ok' => true, 'again' => false, 'card' => $new, 'emailed' => (bool) $emailed, 'error' => ''];
} finally {
mysqli_query($mysqli, "SELECT RELEASE_LOCK('$lock')");
}
}