diff --git a/CHANGELOG.md b/CHANGELOG.md index e8cfc4b32..dd8c78af8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -195,6 +195,7 @@ Update from Maintenance > Update — Queue Update hands the job to cron, which u - Across clients: as All Client Docs, it listed assets, credentials and the rest of the IT documentation with IT documentation switched off in Admin > Settings > Modules. It now has only Contacts, Locations and Vendors then, as each client's menu does. - Email sent with Microsoft 365 or Google sign-in: when the mail server turned down ITFlow's sign-in, the email failed on its From address with "Authentication required" in Maintenance > Mail Queue, as if the address were the problem. It now fails saying the sign-in didn't work. - Assets: a MAC address field holding a note rather than an address ("see label", say) was cut down to the letters in it that pass for hex - "EE:AB:E" - as soon as the asset was opened for editing, and saved like that. It's now left as it is, as the IP address field already was. +- Card payments: once a client's Stripe customer was deleted in Stripe - or the Stripe keys were changed to another Stripe account, or between test and live - every card payment for that client failed, and only an edit to the database put it right. The portal's card form never loaded, the invoice pay page showed Stripe's error, Charge Saved Card failed, and autopay failed every night. Now when Stripe says the customer isn't there, ITFlow forgets it along with the cards saved on it, which Stripe dropped too. A payment with a new card, from an invoice's pay link or the portal, still goes through. The client is asked to add their card again to save one, agents get a notification, and each recurring invoice whose autopay stopped says why. Reported on the forum. ### Developer Updates @@ -307,6 +308,7 @@ Update from Maintenance > Update — Queue Update hands the job to cron, which u - Libraries: directorytree/imapengine v1.25.6 to v1.25.12 (Composer - `libs/composer.lock`, `libs/vendor/composer/installed.json` and `installed.php` updated to match, `libs/composer.json` still asks for `^1.24`); PHPMailer 7.1.1 to 7.2.0; TinyMCE 8.9.2 to 8.10.2; HTMLPurifier 4.15.0 to 4.19.1; stripe-php 21.3.2 to 21.3.3; Bootstrap 5.3.8 to 5.3.9; AdminLTE 4.9.1 to 4.10.2; Chart.js 4.5.1 to 4.6.1; DataTables 3.1.2 to 3.1.5; intl-tel-input 29.2.3 to 29.5.11; FullCalendar 7.1.0 to 7.1.5. The files are each release's own, in the layout already in `libs/`: ImapEngine, PHPMailer and stripe-php as `git archive` of the tag (as Composer's dist zip), the rest from npm, TinyMCE keeping its `license.md` and `langs/README.md`. HTMLPurifier's standalone build is made with the release's `maintenance/generate-standalone.php`, and the three 4.15.0 definition cache files that had been committed are gone - `.gitignore` named the old `plugins/htmlpurifier/` path, and now names `libs/htmlpurifier/`. The DataTables files are the download builder's `bs5/dt-3.1.5` build, put together from the `datatables.net` and `datatables.net-bs5` packages the way the builder does (the 3.1.2 files rebuilt this way match the old ones byte for byte). ImapEngine 1.25.12 disconnects when STARTTLS fails rather than carrying on over plain TCP (the parser maps a mailbox's `tls` to `starttls`), and checks sequence sets and flags in new `Support\Assert`. PHPMailer 7.2.0 reports a rejected XOAUTH2 token sent after a 334 (any long token, so every Microsoft 365 one) as failed rather than accepted; it deprecates `parseAddresses()` and the `pcre8` validator, which ITFlow doesn't use. TinyMCE's advisory GHSA-mf2p-h6hf-fcwm is in the `media` plugin, which neither `js/app.js` nor `js/portal.js` loads. HTMLPurifier gives the same output as 4.15.0 on all 4,503 ticket replies, ticket details, articles and documents in the demo data and a set of hostile samples, with the settings ITFlow uses. Left as they are: TCPDF 6.11.3 (6.11.4 only adds a deprecation notice ahead of 7.x, a different library underneath), stripe-php 22 and 23 (major versions) and Font Awesome 5.15.4. - Libraries removed, about 390 KB, and about 200 KB less script and stylesheet loaded on every agent page: DataTables (no table has used `.dataTables` for a while - `itflowStep('datatables')` in `js/app.js`, `js/portal_datatables.js` and the portal's never-set `$portal_load_datatables` went with it, and CONTRIBUTING no longer says lists use it); zapcal (unused since ticket visit files stopped using it); clipboard.js (only `agent/user/mfa_enforcement.php` still loaded it - it now carries a cut-down copy of `js/app.js`'s copy code, the clipboard API with the selected-textarea fallback); `libs/barcode`, as QR codes now come from new `qrCodeSvg($text, $attributes)` in `functions/format.php`, drawn from TCPDF's own `tcpdf_barcodes_2d.php` as one `` in a viewBox with a four-module quiet zone, and `userMfaQrSvg()`, `portalMfaQrSvg()` and `shareQrSvg()` use it and lose their `extension_loaded('gd')` checks; and IMask, replaced by new `itflowInputMask()` in `js/app.js` on the same `data-mask` / `data-inputmask` markup, which also leaves alone a MAC field that opens holding anything but hex digits and separators. - `libs/tinymce` trimmed to what ITFlow loads, 5.3 MB to 2.6 MB: the 10 plugins in `js/app.js` and `js/portal.js` (autolink, autoresize, autosave, code, codesample, fullscreen, image, link, lists, table), the `oxide` and `oxide-dark` skins and the `default` and `dark` content styles. The 19 other plugins are gone - `media`, where TinyMCE's GHSA-mf2p-h6hf-fcwm was, among them - with the `tinymce-5` skins and the `document`, `writer` and `tinymce-5` content styles. `libs/fontawesome-free/webfonts` keeps only its `.woff2` and `.woff` fonts, 2.8 MB to 0.4 MB, as browsers take the first format they can read and every one ITFlow supports reads `.woff2`; the `.eot`, `.svg` and `.ttf` copies were for Internet Explorer and very old Safari. CONTRIBUTING's `libs/` row now says an update replaces only the files already there. +- Stripe customers Stripe no longer has: new `billingStripeCustomerGone($e)` in `functions/billing_pay.php` - an `InvalidRequestException` with code `resource_missing` on the `customer` parameter ("No such customer: 'cus_...'") - and `billingStripeCustomerForget($client_id, $customer_id)`, which deletes the `client_payment_provider` row only while it still holds that customer, removes the client's saved cards through `paymentCardRemove()` (so the autopay on them goes with each recurring invoice's history saying why), and logs, audits and `appNotify()`s it. Used where the stored customer goes to Stripe: `billingStripeCheckoutIntent()` and the guest pay page's PaymentIntent (`guest/guest_ajax.php`) retry once without a customer; `billingStripeChargeSaved()` returns a message for the client; the portal's `create_stripe_checkout` answers `{reload: true}` with a flash, and `js/portal_stripe.js` reloads into the Add a card step; `stripe_save_card`, Charge Saved Card (`agent/post/payment.php`) and the nightly autopay (`cron/nightly_tasks.php`) record what happened. Any other Stripe error is handled as before. `js/autopay_setup_stripe.js` is gone - nothing has loaded it since `js/portal_stripe.js` took over the portal's card form, and it was the version that never checked the server's answer. ## [26.11.8] diff --git a/agent/post/payment.php b/agent/post/payment.php index 23c305f3c..df7aa1161 100644 --- a/agent/post/payment.php +++ b/agent/post/payment.php @@ -374,6 +374,15 @@ if (isset($_POST['add_payment_stripe'])) { $pi_livemode = $payment_intent->livemode; } catch (Exception $e) { + // The client's Stripe customer is gone from Stripe - forgotten with its cards, so the client adds a card again + if (billingStripeCustomerGone($e)) { + mysqli_query($mysqli, "SELECT RELEASE_LOCK('$pay_lock')"); + billingStripeCustomerForget($client_id, $payment_provider_client); + mysqli_query($mysqli, "INSERT INTO history SET history_status = 'Payment failed', history_description = 'Stripe pay failed - the client\\'s Stripe customer is no longer in Stripe', history_invoice_id = $invoice_id"); + logAudit("Invoice", "Payment", "Failed online payment of invoice $invoice_prefix$invoice_number - the client's Stripe customer is no longer in Stripe", $client_id, $invoice_id); + flashAlert("Nothing was charged - this client's Stripe customer is no longer in Stripe (deleted there, or made under other Stripe keys). Their saved cards are removed; they need to add a card again from the client portal or the invoice's pay link.", 'error'); + redirect(); + } $error = $e->getMessage(); error_log("Stripe payment error - encountered exception during payment intent for invoice ID $invoice_id / $invoice_prefix$invoice_number: $error"); logApp("Stripe", "error", "Exception during PI for invoice ID $invoice_id: $error"); diff --git a/client/post.php b/client/post.php index 34f11b3b8..75eae1898 100644 --- a/client/post.php +++ b/client/post.php @@ -1283,7 +1283,7 @@ if (isset($_GET['create_stripe_checkout'])) { //validateCSRFToken(); - // This page is called by autopay_setup_stripe.js, returns a Checkout Session client_secret + // This page is called by js/portal_stripe.js, returns a Checkout Session client_secret enforceContactCan('accounting'); @@ -1357,6 +1357,13 @@ if (isset($_GET['create_stripe_checkout'])) { echo json_encode(['clientSecret' => $checkout_session->client_secret]); } catch (Exception $e) { + // A customer Stripe no longer has - forgotten, and the page reloads to set them up again + if ($stripe_customer_id && billingStripeCustomerGone($e)) { + billingStripeCustomerForget($session_client_id, $stripe_customer_id); + flashAlert("Your card details are no longer with Stripe - add your card again to save it.", 'warning'); + echo json_encode(['error' => 'Set up again', 'reload' => true]); + exit; + } $error = $e->getMessage(); error_log("Stripe error creating checkout session: $error"); logApp("Stripe", "error", "Exception creating checkout session: $error"); @@ -1459,6 +1466,12 @@ if (isset($_GET['stripe_save_card'])) { "); } catch (Exception $e) { + // Its customer went from Stripe while the card was being entered + if (billingStripeCustomerGone($e)) { + billingStripeCustomerForget($session_client_id, $stripe_customer_id); + flashAlert("Your card details are no longer with Stripe - add your card again to save it.", 'warning'); + redirect("saved_payment_methods.php"); + } $error = $e->getMessage(); error_log("Stripe error while saving payment method: $error"); logApp("Stripe", "error", "Exception saving payment method: $error"); diff --git a/cron/nightly_tasks.php b/cron/nightly_tasks.php index 959a14bcf..514f8655a 100644 --- a/cron/nightly_tasks.php +++ b/cron/nightly_tasks.php @@ -740,6 +740,13 @@ while ($row = mysqli_fetch_assoc($sql_recurring_payments)) { $pi_livemode = $payment_intent->livemode; } catch (Exception $e) { + // The client's Stripe customer is gone from Stripe - forgotten with its cards, so the client adds a card again + if (billingStripeCustomerGone($e)) { + billingStripeCustomerForget($client_id, $stripe_customer_id); + mysqli_query($mysqli, "INSERT INTO history SET history_status = 'Payment failed', history_description = 'Stripe autopay failed - the client\\'s Stripe customer is no longer in Stripe, so its card was removed', history_invoice_id = $invoice_id"); + logAudit("Invoice", "Payment", "Failed auto Payment of invoice $invoice_prefix$invoice_number - the client's Stripe customer is no longer in Stripe", $client_id, $invoice_id); + continue; + } $error = $e->getMessage(); error_log("Stripe payment error - encountered exception during payment intent for invoice ID $invoice_id / $invoice_prefix$invoice_number: $error"); logApp("Stripe", "error", "Exception during PI for invoice ID $invoice_id: $error"); diff --git a/functions/billing_pay.php b/functions/billing_pay.php index fff08ddf8..df5ad4949 100644 --- a/functions/billing_pay.php +++ b/functions/billing_pay.php @@ -60,6 +60,56 @@ function billingStripeCustomer($client_id) { return (string) ($row[0] ?? ''); } +/** + * Whether Stripe turned a call down because the customer it named isn't there - + * deleted in Stripe's dashboard, or made under other keys (test and live mode, + * and each Stripe account, keep customers of their own). Stripe answers + * resource_missing on the customer parameter, "No such customer: 'cus_...'". + */ +function billingStripeCustomerGone(\Throwable $e) { + return $e instanceof \Stripe\Exception\InvalidRequestException + && $e->getStripeCode() === 'resource_missing' + && ($e->getStripeParam() === 'customer' || stripos($e->getMessage(), 'No such customer') !== false); +} + +/** + * Forget a client's Stripe customer that Stripe no longer has, so the next + * card payment or saved card starts by setting them up again - as a client + * with no customer does - rather than every one failing on it. The cards + * saved on it go too, as Stripe dropped them with the customer, and so does + * the autopay on them, each recurring invoice saying why (paymentCardRemove(), + * functions/payment_provider.php). Only while the client still has + * $customer_id, so a customer made since stays. Logged, and agents are told. + * True when it was forgotten here. + */ +function billingStripeCustomerForget($client_id, $customer_id) { + global $mysqli; + $provider = billingStripeProvider(); + $customer_id = stripslashes((string) $customer_id); + if (!$provider || !preg_match('/^cus_[A-Za-z0-9]+$/', $customer_id)) { + return false; + } + $client_id = intval($client_id); + $provider_id = intval($provider['payment_provider_id']); + mysqli_query($mysqli, "DELETE FROM client_payment_provider WHERE client_id = $client_id AND payment_provider_id = $provider_id AND payment_provider_client = '$customer_id'"); + if (mysqli_affected_rows($mysqli) < 1) { + return false; + } + $cards = 0; + $sql = 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"); + while ($row = mysqli_fetch_row($sql)) { + if (paymentCardRemove($row[0], "ITFlow - the client's Stripe customer is no longer in Stripe")) { + $cards++; + } + } + $client_name = (string) (mysqli_fetch_row(mysqli_query($mysqli, "SELECT client_name FROM clients WHERE client_id = $client_id"))[0] ?? ''); + $cards_text = $cards ? " and the $cards saved " . ($cards === 1 ? 'card' : 'cards') . ' on it' : ''; + logApp("Stripe", "warning", "Stripe has no customer $customer_id for client $client_id - forgotten$cards_text"); + logAudit("Stripe", "Delete", "Stripe customer $customer_id for $client_name is no longer in Stripe - ITFlow forgot it$cards_text, so card payments are set up again next time", $client_id); + appNotify("Stripe", "$client_name's Stripe customer is no longer in Stripe - deleted there, or made under other Stripe keys. ITFlow forgot it$cards_text; card payments and autopay need a card added again.", "/agent/recurring_invoices.php?client_id=$client_id", $client_id); + return true; +} + /** * Whether an amount can be paid by card - Stripe's threshold (Admin > Payment * Providers) caps what is offered at checkout; none set means no cap. @@ -572,6 +622,10 @@ function billingStripeChargeSaved(array $selection, $client_id, $saved_payment_i ? 'Your bank wants to confirm this payment - choose A new card and enter the card details to approve it' : 'Your card was declined: ' . rtrim($e->getMessage(), '.') . '. Try another card']; } catch (\Throwable $e) { + if (billingStripeCustomerGone($e)) { + billingStripeCustomerForget($client_id, $customer); + return ['ok' => false, 'error' => 'Your saved cards are no longer with Stripe - nothing was charged. Pay with a new card, and save it again if you want one on file']; + } logApp("Stripe", "error", "Saved card payment failed for client $client_id: " . $e->getMessage()); return ['ok' => false, 'error' => 'The payment could not be made just now - nothing was charged. Try again in a moment']; } @@ -609,7 +663,17 @@ function billingStripeCheckoutIntent(array $selection, $client_id, array $by = [ // Gone or not cancellable - a new one is made below either way } } - return $stripe->paymentIntents->create($params); + try { + return $stripe->paymentIntents->create($params); + } catch (\Stripe\Exception\InvalidRequestException $e) { + // A customer Stripe no longer has - forgotten, and this payment goes ahead without one + if (!isset($params['customer']) || !billingStripeCustomerGone($e)) { + throw $e; + } + billingStripeCustomerForget($client_id, $params['customer']); + unset($params['customer']); + return $stripe->paymentIntents->create($params); + } } /* ------------------------------------------------------------------ Booking */ diff --git a/guest/guest_ajax.php b/guest/guest_ajax.php index 8985206b2..e145587e5 100644 --- a/guest/guest_ajax.php +++ b/guest/guest_ajax.php @@ -105,14 +105,25 @@ if (isset($_GET['stripe_create_pi'])) { try { \Stripe\Stripe::setApiKey($stripe_secret_key); - $paymentIntent = \Stripe\PaymentIntent::create([ + $pi_params = [ 'amount' => $balance_cents + $fee_cents, // Stripe expects cents 'currency' => $invoice_currency_code, 'description' => $pi_description, 'metadata' => $pi_metadata, 'payment_method_types' => ['card'], 'customer' => $stripe_customer_id, - ]); + ]; + try { + $paymentIntent = \Stripe\PaymentIntent::create($pi_params); + } catch (\Stripe\Exception\InvalidRequestException $e) { + // A customer Stripe no longer has - forgotten (next time they are set up again), and this payment goes ahead without one + if (!$stripe_customer_id || !billingStripeCustomerGone($e)) { + throw $e; + } + billingStripeCustomerForget($client_id, $stripe_customer_id); + unset($pi_params['customer']); + $paymentIntent = \Stripe\PaymentIntent::create($pi_params); + } $output = [ 'clientSecret' => $paymentIntent->client_secret, diff --git a/js/autopay_setup_stripe.js b/js/autopay_setup_stripe.js deleted file mode 100644 index 0119616c8..000000000 --- a/js/autopay_setup_stripe.js +++ /dev/null @@ -1,23 +0,0 @@ -// Initialize Stripe.js -const stripe = Stripe(document.getElementById("stripe_publishable_key").value); - -initialize(); - -// Fetch Checkout Session and retrieve the client secret -async function initialize() { - const fetchClientSecret = async () => { - const response = await fetch("/client/post.php?create_stripe_checkout", { - method: "POST", - }); - const { clientSecret } = await response.json(); - return clientSecret; - }; - - // Initialize Checkout - const checkout = await stripe.initEmbeddedCheckout({ - fetchClientSecret, - }); - - // Mount Checkout - checkout.mount('#checkout'); -} diff --git a/js/portal_stripe.js b/js/portal_stripe.js index 965ec0f64..b1e85f206 100644 --- a/js/portal_stripe.js +++ b/js/portal_stripe.js @@ -105,6 +105,12 @@ return fetch('/client/post.php?create_stripe_checkout', {method: 'POST', credentials: 'same-origin'}) .then(function (response) { return response.json(); }) .then(function (data) { + // Their Stripe customer was gone and has been forgotten - the page + // comes back with the Add a card step that sets them up again + if (data.reload) { + window.location.reload(); + return new Promise(function () {}); + } if (!data.clientSecret) { throw new Error(data.error || 'No checkout'); }