From 8b2426c841660010b6ee9cb52a4f1cf6fa7a059d Mon Sep 17 00:00:00 2001 From: johnnyq Date: Tue, 1 Dec 2026 21:22:51 -0500 Subject: [PATCH] Saved cards expiring: each night cards expiring next month or lately are read back from Stripe so a card the bank replaced keeps its new expiry, and for each card on autopay for an active recurring invoice the client's primary and billing contacts are emailed a month before the month it expires and again in it (once just after, within 60 days, for one that ran out unannounced) with an Add your new card link that needs no sign-in and puts the new card in place of the old on every recurring invoice it paid, the team gets a Card Expiring notification each time and an Autopay Failed notification with Stripe's reason when an autopay charge doesn't go through, the portal no longer turns away a card Stripe has renewed, Settings > Invoices > Paid online can turn the client emails off and Saved Cards shows when each card was checked and when the team was told (DB 4.3.8, functions/card_expiry.php, guest/guest_card_update.php); 26.12.4 changelog --- CHANGELOG.md | 7 +- admin/database_updates/4.3.8.php | 38 +++ admin/post/settings_invoice.php | 5 + admin/saved_payment_methods.php | 12 +- admin/settings_invoice.php | 4 + cron/nightly_tasks.php | 9 + db.sql | 5 + functions.php | 1 + functions/billing_email.php | 62 +++++ functions/billing_pay.php | 21 +- functions/card_expiry.php | 439 +++++++++++++++++++++++++++++++ functions/settings.php | 1 + guest/guest_ajax.php | 33 +++ guest/guest_card_update.php | 169 ++++++++++++ guest/guest_post.php | 21 ++ js/guest_autopay_stripe.js | 11 +- 16 files changed, 828 insertions(+), 10 deletions(-) create mode 100644 admin/database_updates/4.3.8.php create mode 100644 functions/card_expiry.php create mode 100644 guest/guest_card_update.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 31c949327..919822e9d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,14 +6,18 @@ This file documents all notable changes made to ITFlow. ### Upgrading to 26.12.4 -Update from Maintenance > Update as usual. There are no database changes. +Update from Maintenance > Update as usual. This release has one database change, 4.3.8, which lets ITFlow remind clients before their autopay card expires: a setting for it, and on each saved card when it was last checked with Stripe, which reminders went out and the key in their link. ### New Features & Updates - Texts: tick texts and use Bulk Action - dismiss or mark as spam in Unmatched, clear in Codes, Not Spam or delete in Spam - or empty a tab with Dismiss All, Clear All or Delete All, which say how many first. A code can also be cleared on its own, which wipes it and its words straight away. While codes are ticked, the Codes list waits to refresh so they stay ticked. +- Cards on autopay that are about to expire: a month before the month a card expires, and again in that month, the client's primary and billing contacts get an email with an Add your new card button that needs no sign-in. The new card takes the old one's place on every recurring invoice it paid, with who changed it and what they agreed to in each one's history. Your team gets a Card Expiring notification each time, and one when a client adds their new card. A card that already ran out in the last 60 days gets one email saying so. Turn the emails off with Email clients before their autopay card expires in Settings > Invoices > Paid online; a client left out of reminders isn't emailed either, and the team is still told. +- Saved cards are checked with Stripe each night when they expire soon or have lately, so a card the bank replaced shows its new expiry and nobody is asked about it. Admin > Payment Providers > Saved Cards says when each card was checked, and when the team was told it is running out. +- Autopay that doesn't go through - a declined or expired card, or a card that's gone - sends your team an Autopay Failed notification with Stripe's reason. Before, it was only in the invoice's history. ### Bug Fixes +- Paying in the client portal with a saved card that ITFlow had as expired works when Stripe has the renewed card, instead of turning it away. - Two-step sign-in no longer says "Your MFA session expired" right after the code is typed. The code boxes send the code on its sixth digit, so pressing Enter out of habit - or a password manager or phone keyboard sending it too, or a double click on Verify & Sign In - sent it a second time, and that second copy signed you out. Each form on the sign-in page now goes once, a second copy that still gets through takes you into ITFlow, and a wrong code sent twice says the code is wrong. - The two-step code can be typed up to five minutes after the password, up from two - time to find the phone and the right account in the authenticator app. - A password manager or phone that fills in the two-step code and sends the form itself signs you in, instead of going back to the email and password. @@ -23,6 +27,7 @@ Update from Maintenance > Update as usual. There are no database changes. - `signInNewSession()` in `functions/sign_in.php` replaces `session_regenerate_id(true)` at both sign-ins in `login.php`. After the role choice, the code or a passkey, the old session id is kept for `SIGN_IN_MOVED_SECONDS` (60) holding only the new id and a SHA-256 of that step's pending token; `signInMovedSession()` takes a request with the old id and the same token on to the signed-in session and sends its cookie, so a second copy of the form posted before the first answer came back isn't left with an empty session. An id planted before the sign-in has no token and gets nothing. A password-only or provider sign-in renews the id as before. - `login.php`: the role, code and passkey steps call `signInMovedOn()` when their pending sign-in is gone - into the app for a second copy or a browser already signed in, otherwise "expired" as before. The code step is recognized by `pending_mfa_token` as well as the `mfa_login` button, a retried code keeps its pending token, and `SIGN_IN_CODE_SECONDS` (300) is the code step's window. - `js/login_prevent_resubmit.js` lets each form on the sign-in page submit once (until the page comes back from history, or 10 seconds), and `js/otp_input.js` does the same for any form with a `data-otp-submit` code field - turning on MFA, the client portal's two-step setup and shared-link codes. +- Saved cards expiring (DB 4.3.8): new `functions/card_expiry.php`. `cardExpiryNightly($now = null)`, called from `cron/nightly_tasks.php` before autopay, reads back from Stripe (`cardRefresh()`, PaymentMethods retrieve) up to `CARD_EXPIRY_CHECK_LIMIT` (200) cards a night whose expiry is from 6 months ago to next month and that weren't checked in 20 hours, keeping Stripe's brand, last four and expiry in `saved_payment_description` and stamping `saved_payment_checked_at`. It then finds cards on autopay for active recurring invoices (`cardAutopayCards()`) and, for an expiry within 30 days of its month starting (stage 1) or in or past its month (stage 2), emails the billing recipients (`billingMailCardExpiring()`), notifies the team (`Card Expiring`) and logs each recurring invoice's history, recording `saved_payment_reminded_expiry`, `saved_payment_reminded` and a random `saved_payment_update_key` that both stages' links share. `settings.config_invoice_card_expiry_reminders` (default 1) and `client_reminders` gate the email only. `guest/guest_card_update.php?card=&key=` reuses `js/guest_autopay_stripe.js` (its form's `data-checkout-url` now picks the endpoint): `guest_ajax.php?guest_card_update_checkout` starts a setup-mode Checkout Session on the client's Stripe customer (`cardUpdateCheckoutStart()`), and `guest_post.php?guest_card_update_done` runs `cardUpdateFinish()`, which checks the session's mode, card and customer first, saves the new card, repoints every `recurring_payments` row of the client's that used the old card, clears the key, and sends `billingMailCardUpdated()`. `billingCardParts()` gains `expires` (yyyymm), `billingStripeChargeSaved()` reads an expired-looking card back from Stripe before refusing it, and `autopayFailedNotify()` in `functions/billing_pay.php` sends the `Autopay Failed` notification from the nightly autopay's failure branches. - Texts: `smsInboxBulk($action, $ids, $user_id)` in `functions/sms.php` runs an action from `SMS_INBOX_BULK` (dismiss, spam, clear, not_spam, delete => the status it takes texts from and the permission it needs) on the ticked inbound texts, or with `$ids` null on the whole tab, inside `clientScopeSql()`. Spam and not spam block or unblock the numbers and move every text from them, as the single actions do. Clearing a code sets it to dismissed with its body, code and media wiped, so the text log's search can't find its words. `agent/post/texts.php` takes `bulk_texts` (with `sms_message_ids[]`) and `bulk_texts_all`, plus `sms_clear_code` for one code. `agent/texts.php` uses the standard `js/bulk_actions.js` select-all and Bulk Action button. ## [26.12.3] diff --git a/admin/database_updates/4.3.8.php b/admin/database_updates/4.3.8.php new file mode 100644 index 000000000..1237d5b58 --- /dev/null +++ b/admin/database_updates/4.3.8.php @@ -0,0 +1,38 @@ + Invoices > Paid online). The team is notified either way (functions/card_expiry.php). + * client_saved_payment_methods.saved_payment_checked_at - when the card was last read back from Stripe, which + * keeps a card the bank replaced up to date. + * client_saved_payment_methods.saved_payment_reminded_expiry and saved_payment_reminded - the expiry (yyyymm) + * the reminders went out for, and which: 1 a month before, 2 in the month it runs out. A new expiry starts again. + * client_saved_payment_methods.saved_payment_update_key - the key in the link the reminder sends, which opens + * guest/guest_card_update.php for that card. Cleared once the card is replaced. + * + * Re-runnable: each column is made only where it isn't there. + */ + +defined('FROM_DB_UPDATER') || die("Direct file access is not allowed"); + + $itflow_card_columns = [ + ['settings', 'config_invoice_card_expiry_reminders', "tinyint(1) NOT NULL DEFAULT 1", 'config_invoice_offer_autopay'], + ['client_saved_payment_methods', 'saved_payment_checked_at', "datetime DEFAULT NULL", 'saved_payment_updated_at'], + ['client_saved_payment_methods', 'saved_payment_reminded_expiry', "int(11) DEFAULT NULL", 'saved_payment_checked_at'], + ['client_saved_payment_methods', 'saved_payment_reminded', "tinyint(1) NOT NULL DEFAULT 0", 'saved_payment_reminded_expiry'], + ['client_saved_payment_methods', 'saved_payment_update_key', "varchar(64) DEFAULT NULL", 'saved_payment_reminded'], + ]; + foreach ($itflow_card_columns as [$itflow_table, $itflow_column, $itflow_type, $itflow_after]) { + $itflow_exists = mysqli_query($mysqli, "SELECT 1 FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = '$itflow_table' AND COLUMN_NAME = '$itflow_column' LIMIT 1"); + if (!$itflow_exists || mysqli_num_rows($itflow_exists) === 0) { + $itflow_after_exists = mysqli_query($mysqli, "SELECT 1 FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = '$itflow_table' AND COLUMN_NAME = '$itflow_after' LIMIT 1"); + $itflow_place = $itflow_after_exists && mysqli_num_rows($itflow_after_exists) > 0 ? " AFTER `$itflow_after`" : ''; + mysqli_query($mysqli, "ALTER TABLE `$itflow_table` ADD `$itflow_column` $itflow_type$itflow_place"); + } + } diff --git a/admin/post/settings_invoice.php b/admin/post/settings_invoice.php index 4932a8e64..a7c7b48cd 100644 --- a/admin/post/settings_invoice.php +++ b/admin/post/settings_invoice.php @@ -56,6 +56,11 @@ if (isset($_POST['edit_invoice_settings'])) { $before += settingsCurrent(['config_invoice_offer_autopay']); $after['config_invoice_offer_autopay'] = empty($_POST['config_invoice_offer_autopay']) ? 0 : 1; } + // From 4.3.8 - clients are emailed before their autopay card expires (cardExpiryNightly()) + if (settingsColumnExists($mysqli, 'config_invoice_card_expiry_reminders')) { + $before += settingsCurrent(['config_invoice_card_expiry_reminders']); + $after['config_invoice_card_expiry_reminders'] = empty($_POST['config_invoice_card_expiry_reminders']) ? 0 : 1; + } // Late fees - a percent of what is owed $late_fee = billingNumberInput(str_replace('%', '', (string) $in['config_invoice_late_fee_percent'])); diff --git a/admin/saved_payment_methods.php b/admin/saved_payment_methods.php index d27d85179..2e22a68be 100644 --- a/admin/saved_payment_methods.php +++ b/admin/saved_payment_methods.php @@ -7,7 +7,10 @@ * with it and when each next does, and when it was saved. The tabs pick out * the cards on autopay and the ones that have run out - an expired card on * autopay is flagged, as its next autopay will be declined. Filtered by - * provider (the Payment Providers list links here so) and by client. Remove + * provider (the Payment Providers list links here so) and by client. A card + * running out on autopay says when the team was told (and its client emailed, + * as cardExpiryNightly() could), and when it was last read back from Stripe + * (functions/card_expiry.php). Remove * takes a card off at the provider and in ITFlow, its autopay with it * (paymentCardRemove(), functions/payment_provider.php, * admin/post/saved_payment_method.php). @@ -55,6 +58,7 @@ $from = "FROM client_saved_payment_methods $sql = mysqli_query($mysqli, "SELECT SQL_CALC_FOUND_ROWS saved_payment_id, saved_payment_client_id, saved_payment_provider_id, saved_payment_provider_method, saved_payment_description, saved_payment_created_at, payment_provider_name, payment_provider_active, client_name, client_archived_at, payment_provider_client, + " . (cardExpiryReady() ? 'saved_payment_checked_at, saved_payment_reminded_expiry, saved_payment_reminded,' : '') . " $expiry_sql AS expires, $autopay_sql AS autopay $from WHERE $filters AND $show_where @@ -194,6 +198,12 @@ $page_title = 'Saved Cards'; Soon + 0) { ?> +
Notified 1 ? 'in its month' : 'a month before' ?>
+ + +
Checked
+ diff --git a/admin/settings_invoice.php b/admin/settings_invoice.php index 9d44d62c2..645804fb5 100644 --- a/admin/settings_invoice.php +++ b/admin/settings_invoice.php @@ -81,6 +81,10 @@ echo settingsPageStart('invoice'); 'An invoice from a recurring invoice without autopay gets a Set up autopay button, in its email and on its page. The client agrees, adds a card through Stripe with no sign-in, and each invoice after that is charged on its due date. Turn it off for one recurring invoice on its page.']) ?> + + 'A month before a card on autopay runs out, and again in the month it does, its client\'s primary and billing contacts are emailed a link to add their new card - no sign-in. Cards are checked with Stripe first, so one the bank has already replaced isn\'t asked about. Your team gets a notification either way. A client left out of reminders isn\'t emailed.']) ?> + diff --git a/cron/nightly_tasks.php b/cron/nightly_tasks.php index 1be309b8f..51616bbc7 100644 --- a/cron/nightly_tasks.php +++ b/cron/nightly_tasks.php @@ -744,6 +744,12 @@ while ($row = mysqli_fetch_assoc($sql_quotes_expiring)) { +// Saved cards running out - read back from Stripe, and the client and the team told about the ones on autopay (functions/card_expiry.php) +$card_expiry = cardExpiryNightly(); +if ($card_expiry['checked'] || $card_expiry['notified']) { + echo "Saved cards: {$card_expiry['checked']} checked with Stripe ({$card_expiry['updated']} updated), {$card_expiry['notified']} running out on autopay, {$card_expiry['emailed']} client(s) emailed\n"; +} + // Start Recurring Payments $sql_recurring_payments = mysqli_query($mysqli, " SELECT client_id, client_name, contact_email, contact_name, invoice_amount, invoice_currency_code, @@ -813,6 +819,7 @@ while ($row = mysqli_fetch_assoc($sql_recurring_payments)) { if (!$saved_payment) { logAudit("Invoice", "Payment", "Failed auto Payment for invoice $invoice_prefix$invoice_number: Saved payment method not found or provider inactive", $client_id, $invoice_id); + autopayFailedNotify($invoice_id, "$invoice_prefix$invoice_number", $client_id, $row['client_name'], "its saved card isn't there any more, or its payment provider is turned off"); continue; } @@ -886,6 +893,7 @@ while ($row = mysqli_fetch_assoc($sql_recurring_payments)) { logApp("Stripe", "error", "Exception during PI for invoice ID $invoice_id: $error"); mysqli_query($mysqli, "INSERT INTO history SET history_status = 'Payment failed', history_description = 'Stripe autopay failed due to payment error', history_invoice_id = $invoice_id"); logAudit("Invoice", "Payment", "Failed auto Payment amount of invoice $invoice_prefix$invoice_number due to Stripe payment error: $error", $client_id, $invoice_id); + autopayFailedNotify($invoice_id, "$invoice_prefix$invoice_number", $client_id, $row['client_name'], $e instanceof \Stripe\Exception\CardException ? 'Stripe declined it: ' . rtrim($e->getMessage(), '.') : "Stripe couldn't take it: " . rtrim($e->getMessage(), '.')); continue; } @@ -916,6 +924,7 @@ while ($row = mysqli_fetch_assoc($sql_recurring_payments)) { } else { mysqli_query($mysqli, "INSERT INTO history SET history_status = 'Payment failed', history_description = 'Stripe autopay failed: Status {$payment_intent->status}', history_invoice_id = $invoice_id"); logAudit("Invoice", "Payment", "Failed auto Payment for invoice $invoice_prefix$invoice_number. Stripe PI status: {$payment_intent->status}", $client_id, $invoice_id); + autopayFailedNotify($invoice_id, "$invoice_prefix$invoice_number", $client_id, $row['client_name'], $payment_intent->status === 'requires_action' ? 'the bank wants the client to approve it' : "Stripe left it {$payment_intent->status}"); } } // End if Stripe creds and IDs } // End if Stripe provider diff --git a/db.sql b/db.sql index bcf67a4e1..3da81043e 100644 --- a/db.sql +++ b/db.sql @@ -933,6 +933,10 @@ CREATE TABLE `client_saved_payment_methods` ( `saved_payment_provider_id` int(11) NOT NULL, `saved_payment_created_at` datetime NOT NULL DEFAULT current_timestamp(), `saved_payment_updated_at` datetime DEFAULT NULL ON UPDATE current_timestamp(), + `saved_payment_checked_at` datetime DEFAULT NULL, + `saved_payment_reminded_expiry` int(11) DEFAULT NULL, + `saved_payment_reminded` tinyint(1) NOT NULL DEFAULT 0, + `saved_payment_update_key` varchar(64) DEFAULT NULL, PRIMARY KEY (`saved_payment_id`), KEY `saved_payment_client_id` (`saved_payment_client_id`), KEY `saved_payment_provider_id` (`saved_payment_provider_id`), @@ -4163,6 +4167,7 @@ CREATE TABLE `settings` ( `config_invoice_paid_notification_email` varchar(200) DEFAULT NULL, `config_invoice_paid_lead_to_client` tinyint(1) NOT NULL DEFAULT 1, `config_invoice_offer_autopay` tinyint(1) NOT NULL DEFAULT 1, + `config_invoice_card_expiry_reminders` tinyint(1) NOT NULL DEFAULT 1, `config_invoice_show_tax_id` tinyint(1) NOT NULL DEFAULT 0, `config_tax_default_id` int(11) NOT NULL DEFAULT 0, `config_tax_time` tinyint(1) NOT NULL DEFAULT 0, diff --git a/functions.php b/functions.php index 7b924c77a..c2ba2488e 100644 --- a/functions.php +++ b/functions.php @@ -120,6 +120,7 @@ require_once __DIR__ . '/functions/billing_email.php'; require_once __DIR__ . '/functions/billing_pay.php'; require_once __DIR__ . '/functions/invoice_actions.php'; require_once __DIR__ . '/functions/payment_provider.php'; +require_once __DIR__ . '/functions/card_expiry.php'; require_once __DIR__ . '/functions/tax.php'; require_once __DIR__ . '/functions/expenses.php'; require_once __DIR__ . '/functions/expense_import.php'; diff --git a/functions/billing_email.php b/functions/billing_email.php index 10a95d9de..2d1fea068 100644 --- a/functions/billing_email.php +++ b/functions/billing_email.php @@ -593,6 +593,68 @@ function billingMailCardSaved($email, $name, $client_name, $brand, $last4, $exp_ ]); } +/** + * Tell a client their card on autopay is running out (cardExpiryNightly(), functions/card_expiry.php) - + * to their primary and billing contacts, with a link to add the new card with no sign-in. $entry is + * cardAutopayCards()'s, $exp the month it runs out (yyyymm), $kind soon, this_month or expired. Who it + * went to. + */ +function billingMailCardExpiring(array $entry, int $exp, string $kind, string $url) { + $card = $entry['card']; + $parts = billingCardParts($card['saved_payment_description']); + $month = cardExpiryMonth($exp); + $recipients = billingEmailRecipients($card['saved_payment_client_id']); + if (!$recipients) { + return []; + } + $count = count($entry['recurring']); + // "your REC-1 and REC-50 invoices", or by what the one is for - "your "Managed services" invoices" + $what = 'your ' . ($count > 1 ? cardRecurringNumbers($entry['recurring']) : ($entry['recurring'][0]['title'] !== $entry['recurring'][0]['number'] ? '"' . $entry['recurring'][0]['title'] . '"' : $entry['recurring'][0]['number'])) . ' invoices'; + [$subject, $title, $when] = [ + 'soon' => ["Your card on file expires at the end of $month", 'Your card on file expires soon', "expires at the end of $month"], + 'this_month' => ['Your card on file expires this month', 'Your card on file expires this month', 'expires at the end of this month'], + 'expired' => ['Your card on file has expired', 'Your card on file has expired', "expired at the end of $month"], + ][$kind] ?? ['Your card on file expires soon', 'Your card on file expires soon', "expires at the end of $month"]; + $summary = ['Card' => $parts['label'], 'Expires' => $parts['exp']]; + foreach ($entry['recurring'] as $recurring) { + $summary[$count > 1 ? $recurring['number'] : 'Pays'] = billingMoney($recurring['amount'], $recurring['currency']) . ' each ' . $recurring['period'] . ($count > 1 || $recurring['title'] === $recurring['number'] ? '' : ' - ' . $recurring['title']); + } + $next = min(array_column($entry['recurring'], 'next')); + if ($next !== '') { + $summary['Next invoice'] = billingEmailDate($next); + } + return billingEmailQueue($recipients, $subject, [ + 'kind' => 'Autopay', 'tone' => $kind === 'soon' ? 'warning' : 'danger', 'preview' => "Add your new card so autopay keeps paying $what", + 'title' => $title, + 'intro' => ["The {$parts['label']} that autopay charges for $what $when. " + . ($kind === 'expired' ? 'Autopay can\'t charge it now, so add the card you use today' : 'Add your new card before then and autopay carries on as it is') + . " - it takes a minute, with no sign-in."], + 'summary' => $summary, + 'button' => ['label' => 'Add your new card', 'url' => $url], + 'after' => [ + 'Your card goes straight to Stripe, our payment processor - we never see its number. If your bank has sent you a new card, it may update it with Stripe for you, and you won\'t hear about it from us again.', + autopayChangeText(), + ], + 'footnote' => billingEmailFootnote((string) $card['client_name']), + ]); +} + +/** Confirm a new card put in place of one running out (cardUpdateFinish()) to whoever added it. $entry is cardAutopayCards()'s. Who it went to. */ +function billingMailCardUpdated($email, $name, array $entry, $old_label, $new_label) { + $summary = ['New card' => $new_label, 'In place of' => $old_label]; + foreach ($entry['recurring'] as $recurring) { + $summary[$recurring['number']] = billingMoney($recurring['amount'], $recurring['currency']) . ' each ' . $recurring['period']; + } + return billingEmailQueue([['email' => (string) $email, 'name' => (string) $name]], 'Your card for autopay is updated', [ + 'kind' => 'Autopay', 'tone' => 'success', 'preview' => "Autopay now charges $new_label", + 'title' => 'Your card is updated', + 'intro' => ["Thank you - from now on, autopay charges $new_label for each invoice from " . cardRecurringNumbers($entry['recurring']) . ' on its due date, and a receipt is emailed each time.'], + 'summary' => $summary, + 'after' => ['Your card details are kept by Stripe, our payment processor - not by us. ' . autopayChangeText()], + 'footnote' => 'You received this email because you updated the card ' . $entry['card']['client_name'] . ' pays ' . (billingCompany()['company_name'] ?? 'us') . ' with.', + ]); +} + /** An email to one of our own addresses - no greeting, from the invoice or quote address. Who it went to. */ function billingNotifyEmail($to, $subject, array $email, $from = 'invoice') { $to = trim((string) $to); diff --git a/functions/billing_pay.php b/functions/billing_pay.php index f6f3c93b5..b4ef33885 100644 --- a/functions/billing_pay.php +++ b/functions/billing_pay.php @@ -324,8 +324,9 @@ function billingCardFeeSplit($metadata) { /** * A saved card's description ("visa - 4242 | Exp 9/2028", as saved) in - * parts: brand, last4, exp ("09/28"), expired, icon and label ("Visa •••• - * 4242"). One saved some other way keeps its description as the label. + * parts: brand, last4, exp ("09/28"), expires (202809, 0 when it doesn't + * say), expired, icon and label ("Visa •••• 4242"). One saved some other + * way keeps its description as the label. */ function billingCardParts($description) { $description = trim((string) $description); @@ -340,7 +341,7 @@ function billingCardParts($description) { 'unionpay' => ['UnionPay', 'fas fa-credit-card'], ]; if (!preg_match('/^(.+?)\s*-\s*(\d{4})\s*\|\s*Exp\s*(\d{1,2})\/(\d{2,4})$/i', $description, $m)) { - return ['brand' => '', 'last4' => '', 'exp' => '', 'expired' => false, 'icon' => 'fas fa-credit-card', 'label' => $description !== '' ? $description : 'Card']; + return ['brand' => '', 'last4' => '', 'exp' => '', 'expires' => 0, 'expired' => false, 'icon' => 'fas fa-credit-card', 'label' => $description !== '' ? $description : 'Card']; } $key = strtolower(trim($m[1])); [$brand, $icon] = $brands[$key] ?? [ucwords($key), 'fas fa-credit-card']; @@ -353,6 +354,7 @@ function billingCardParts($description) { 'brand' => $brand, 'last4' => $m[2], 'exp' => sprintf('%02d/%02d', $month, $year % 100), + 'expires' => $year * 100 + $month, 'expired' => $expired, 'icon' => $icon, 'label' => "$brand •••• {$m[2]}", @@ -763,6 +765,15 @@ function autopayCheckoutFinish(array $invoice, $session_id) { } } +/* + * Tell the team an autopay charge didn't go through (cron/nightly_tasks.php) - the invoice, the client and why, + * in words. The invoice stays owed, and its reminders carry on as for any other. + */ +function autopayFailedNotify($invoice_id, $number, $client_id, $client_name, $why) { + appNotify("Autopay Failed", escapeSql("Autopay didn't go through for invoice $number ($client_name) - $why. The invoice is still owed."), + "/agent/invoice.php?invoice_id=" . intval($invoice_id), intval($client_id), intval($invoice_id)); +} + /* ------------------------------------------------------- Choosing and paying */ /** @@ -897,7 +908,9 @@ function billingStripeChargeSaved(array $selection, $client_id, $saved_payment_i if (!$provider || !$card || $customer === '') { return ['ok' => false, 'error' => 'That card is no longer saved - choose another']; } - if (billingCardParts($card['saved_payment_description'])['expired']) { + // Expired as it was saved - Stripe may have the card the bank sent in its place (cardRefresh()) + if (billingCardParts($card['saved_payment_description'])['expired'] + && billingCardParts(cardRefresh(['saved_payment_id' => $saved_payment_id, 'saved_payment_client_id' => $client_id] + $card) ?? $card['saved_payment_description'])['expired']) { return ['ok' => false, 'error' => 'That card has expired - choose another or pay with a new card']; } $params = billingStripeIntentParams($selection, $client_id, $by) + [ diff --git a/functions/card_expiry.php b/functions/card_expiry.php new file mode 100644 index 000000000..f29230ba5 --- /dev/null +++ b/functions/card_expiry.php @@ -0,0 +1,439 @@ + 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')"); + } +} diff --git a/functions/settings.php b/functions/settings.php index 4aab56711..99d772861 100644 --- a/functions/settings.php +++ b/functions/settings.php @@ -339,6 +339,7 @@ function settingsFields() { 'config_invoice_paid_notification_email' => ['page' => 'invoice', 'section' => 'Paid online', 'label' => 'Email invoices paid online to', 'words' => 'paid notification email stripe payment'], 'config_invoice_paid_lead_to_client' => ['page' => 'invoice', 'section' => 'Paid online', 'label' => 'A lead that pays an invoice becomes a client', 'words' => 'lead client convert paid payment'] + $on_off, 'config_invoice_offer_autopay' => ['page' => 'invoice', 'section' => 'Paid online', 'label' => 'Offer autopay on recurring invoices', 'words' => 'autopay automatic payment recurring card offer set up'] + $on_off, + 'config_invoice_card_expiry_reminders' => ['page' => 'invoice', 'section' => 'Paid online', 'label' => 'Email clients before their autopay card expires', 'words' => 'card expiry expires expiring autopay reminder saved card update'] + $on_off, 'config_send_invoice_reminders' => ['page' => 'invoice', 'section' => 'Reminders and statements', 'label' => 'Email payment reminders', 'words' => 'overdue reminder dunning past due'] + $on_off, 'reminder_before' => ['page' => 'invoice', 'section' => 'Reminders and statements', 'label' => 'Remind before it is due', 'words' => 'reminder days before due'], 'reminder_after' => ['page' => 'invoice', 'section' => 'Reminders and statements', 'label' => 'Remind after it is due', 'words' => 'reminder days late overdue'], diff --git a/guest/guest_ajax.php b/guest/guest_ajax.php index 5fa524c12..cd7a76c7e 100644 --- a/guest/guest_ajax.php +++ b/guest/guest_ajax.php @@ -147,6 +147,39 @@ if (isset($_GET['stripe_create_pi'])) { * invoice_id, url_key, name, email and agree. The invoice's link key is the * only proof, matched exactly. */ +// A new card in place of one on autopay running out - from the reminder's link (guest/guest_card_update.php, cardUpdateCheckoutStart()) +if (isset($_GET['guest_card_update_checkout'])) { + + header('Content-Type: application/json'); + header('Cache-Control: no-store'); + + // logAudit() reads these globals - without them guest audit rows have no IP + $session_ip = escapeSql(getIP()); + $session_user_agent = escapeSql(mb_substr((string) ($_SERVER['HTTP_USER_AGENT'] ?? ''), 0, 250)); + + $card = cardUpdateRow($_POST['card'] ?? 0, is_string($_POST['key'] ?? null) ? $_POST['key'] : ''); + if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST' || !$card) { + http_response_code(404); + echo json_encode(['error' => "This link isn't working - open it again from the email."]); + exit; + } + if (empty($_POST['agree'])) { + http_response_code(400); + echo json_encode(['error' => 'Tick the box to agree to autopay first.']); + exit; + } + + $error = ''; + $secret = cardUpdateCheckoutStart($card, is_string($_POST['name'] ?? null) ? $_POST['name'] : '', is_string($_POST['email'] ?? null) ? $_POST['email'] : '', $error); + if ($secret === '') { + http_response_code(400); + echo json_encode(['error' => $error]); + exit; + } + echo json_encode(['clientSecret' => $secret]); + exit; +} + if (isset($_GET['guest_autopay_checkout'])) { header('Content-Type: application/json'); diff --git a/guest/guest_card_update.php b/guest/guest_card_update.php new file mode 100644 index 000000000..3dcbf9cb1 --- /dev/null +++ b/guest/guest_card_update.php @@ -0,0 +1,169 @@ + +
+ +

Your card is updated

+

Autopay charges your new card from now on - nothing else to do.

+

+
+ + +
+
+ +
+
+ +
+ +
+

Update your card

+
+
+
+ +

+ The card that pays 1 ? 'these invoices' : 'this invoice' ?> automatically + + has expired, so autopay can't charge it. Add the card you use now and autopay carries on. + + expires . Add your new card and autopay carries on as it is. + +

+ +
    +
  • + Card on file + + + +
  • + +
  • + () + each +
  • + +
  • + Next invoice +
  • + +
  • + Card fee, added to each charge +
  • + +
+ +
+ + + +
+ +
+ + +
+
+ +
+ +
+ + +
+
For the confirmation.
+
+ +
+ + +
+ + + + +
+ + + + + +

Your card goes straight to Stripe, our payment processor - we never see its number.

+ +
+
+ +
+
+ + + + +' . escapeHtml($result['card']) . '.' . ($result['emailed'] ? ' A confirmation is on its way by email.' : '')); + } + redirect($back . ($result['ok'] ? '&done=1' : '')); +} + if (isset($_POST['create_stripe_customer'])) { $invoice_url_key = escapeSql($_POST['url_key']); diff --git a/js/guest_autopay_stripe.js b/js/guest_autopay_stripe.js index f189adb82..d0c920d07 100644 --- a/js/guest_autopay_stripe.js +++ b/js/guest_autopay_stripe.js @@ -1,7 +1,10 @@ /* - * Setting up autopay from an invoice's link (guest/guest_autopay.php). Their - * name, email and agreement go to guest_ajax.php (guest_autopay_checkout), - * which answers with a Checkout Session's client secret; Stripe's card form + * Setting up autopay from an invoice's link (guest/guest_autopay.php), or + * adding a new card in place of one running out (guest/guest_card_update.php, + * whose form names its own address in data-checkout-url). Their name, email + * and agreement go to guest_ajax.php (guest_autopay_checkout or + * guest_card_update_checkout), which answers with a Checkout Session's client + * secret; Stripe's card form * then takes the place of the form, and sends them on to the return address * once the card is added. Anything that stops it is said on the page. */ @@ -57,7 +60,7 @@ var stripe = window.Stripe(form.getAttribute('data-stripe-key')); stripe.initEmbeddedCheckout({ fetchClientSecret: function () { - return fetch('guest_ajax.php?guest_autopay_checkout=1', {method: 'POST', body: new FormData(form), credentials: 'same-origin'}) + return fetch(form.getAttribute('data-checkout-url') || 'guest_ajax.php?guest_autopay_checkout=1', {method: 'POST', body: new FormData(form), credentials: 'same-origin'}) .then(function (response) { return response.json().catch(function () { return {};