mirror of
https://github.com/itflow-org/itflow
synced 2026-12-02 09:09:01 +00:00
Autopay offered to clients: database 4.3.7 adds settings.config_invoice_offer_autopay and recurring_invoices.recurring_invoice_offer_autopay, an invoice from a recurring invoice with no autopay offers Set up autopay in its email and on its guest and portal pages, guest/guest_autopay.php sets it up with no sign-in through a Stripe Checkout Session in setup mode (name, email and agreement kept in its metadata and the recurring invoice's history), the card is saved and autopay turned on when Stripe sends them back, agents are told and the client gets a confirmation, the portal turns it on with a saved card, Settings > Invoices and each recurring invoice's Autopay card can turn the offer off; 26.12.3 changelog
This commit is contained in:
@@ -470,6 +470,299 @@ function invoiceAutopayStatus(array $invoice, array $state, $autopay) {
|
||||
'detail' => "$done on its due date, $due - for what is still owed then."];
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------- Offering autopay */
|
||||
|
||||
/*
|
||||
* An invoice from a recurring invoice with no autopay offers it - a Set up
|
||||
* autopay button in its email and on its page that opens
|
||||
* guest/guest_autopay.php from the invoice's own link, so no sign-in is
|
||||
* needed: the client agrees, adds a card through Stripe's form, and autopay
|
||||
* is on for that recurring invoice. Settings > Invoices turns the offer off
|
||||
* for everyone, and a recurring invoice's page for one.
|
||||
*/
|
||||
|
||||
/** Whether invoices offer autopay - Settings > Invoices > Paid online (DB 4.3.7). */
|
||||
function autopayOfferOn() {
|
||||
global $mysqli;
|
||||
static $on = null;
|
||||
if ($on === null) {
|
||||
$on = settingsColumnExists($mysqli, 'config_invoice_offer_autopay')
|
||||
&& intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT config_invoice_offer_autopay FROM settings WHERE company_id = 1"))[0] ?? 0) === 1;
|
||||
}
|
||||
return $on;
|
||||
}
|
||||
|
||||
/**
|
||||
* Why a recurring invoice's client isn't offered autopay - '' when they are,
|
||||
* or would be once an invoice from it is sent. Its autopay is already on,
|
||||
* cards are off, the offer is off here or in Settings > Invoices, it is
|
||||
* paused or archived, or it bills more than a card can take. $recurring is
|
||||
* billingRow('recurring').
|
||||
*/
|
||||
function autopayOfferBlocked(array $recurring) {
|
||||
if (intval($recurring['recurring_payment_id'] ?? 0) > 0) {
|
||||
return 'Autopay is on';
|
||||
}
|
||||
if (!billingStripeProvider()) {
|
||||
return "Card payments are off - Stripe isn't set up in Payment Providers";
|
||||
}
|
||||
if (!autopayOfferOn()) {
|
||||
return 'Offering autopay is off in Settings > Invoices';
|
||||
}
|
||||
if (intval($recurring['recurring_invoice_offer_autopay'] ?? 1) !== 1) {
|
||||
return 'Turned off for this recurring invoice';
|
||||
}
|
||||
if (intval($recurring['recurring_invoice_status']) !== 1 || !empty($recurring['recurring_invoice_archived_at'])) {
|
||||
return "It isn't active";
|
||||
}
|
||||
if (!billingOnlinePayAllowed($recurring['recurring_invoice_amount'])) {
|
||||
return 'It bills more than the card limit in Payment Providers';
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* The autopay an invoice offers for the recurring invoice it came from - or
|
||||
* null when it offers none (autopayOfferBlocked(), or the invoice is
|
||||
* cancelled or not billed). autopayOfferDetails() says what is in it.
|
||||
*/
|
||||
function autopayOffer(array $invoice) {
|
||||
$recurring_id = intval($invoice['invoice_recurring_invoice_id'] ?? 0);
|
||||
if ($recurring_id <= 0 || in_array((string) $invoice['invoice_status'], ['Cancelled', 'Non-Billable'], true) || (string) ($invoice['invoice_url_key'] ?? '') === '') {
|
||||
return null;
|
||||
}
|
||||
$recurring = billingRow('recurring', $recurring_id, false);
|
||||
if (!$recurring || intval($recurring['recurring_invoice_client_id']) !== intval($invoice['invoice_client_id']) || autopayOfferBlocked($recurring) !== '') {
|
||||
return null;
|
||||
}
|
||||
return autopayOfferDetails($invoice, $recurring);
|
||||
}
|
||||
|
||||
/**
|
||||
* What autopay for $recurring, offered from $invoice, comes to - ['recurring'
|
||||
* => its row, 'number', 'title' => its scope, else its number, 'amount',
|
||||
* 'currency', 'period' => month, quarter or year, 'fee' => the card fee's
|
||||
* terms, or '', 'this_invoice' => whether $invoice is charged too - still
|
||||
* owed, and due after today, 'url' => the setup page].
|
||||
*/
|
||||
function autopayOfferDetails(array $invoice, array $recurring) {
|
||||
$currency = (string) $recurring['recurring_invoice_currency_code'];
|
||||
$owed = in_array((string) $invoice['invoice_status'], ['Draft', 'Sent', 'Viewed', 'Partial'], true)
|
||||
&& round(floatval($invoice['invoice_amount']) - invoicePaid($invoice['invoice_id']), 2) > 0;
|
||||
$number = billingNumber('recurring', $recurring);
|
||||
return [
|
||||
'recurring' => $recurring,
|
||||
'number' => $number,
|
||||
'title' => trim((string) $recurring['recurring_invoice_scope']) !== '' ? trim((string) $recurring['recurring_invoice_scope']) : $number,
|
||||
'amount' => floatval($recurring['recurring_invoice_amount']),
|
||||
'currency' => $currency,
|
||||
'period' => recurringInvoicePeriodWord($recurring['recurring_invoice_frequency']),
|
||||
'fee' => billingCardFeeTerms(billingCardFeeFor($invoice['invoice_client_id']), $currency),
|
||||
'this_invoice' => $owed && (string) $invoice['invoice_due'] > date('Y-m-d'),
|
||||
'url' => autopayOfferUrl($invoice),
|
||||
];
|
||||
}
|
||||
|
||||
/** The page that sets autopay up from an invoice's link. */
|
||||
function autopayOfferUrl(array $invoice) {
|
||||
global $config_base_url;
|
||||
return "https://$config_base_url/guest/guest_autopay.php?invoice_id=" . intval($invoice['invoice_id']) . '&url_key=' . rawurlencode((string) $invoice['invoice_url_key']);
|
||||
}
|
||||
|
||||
/**
|
||||
* What the client agrees to, raw - the charges, the card fee when they pay
|
||||
* one, and until when. Kept in the recurring invoice's history.
|
||||
*/
|
||||
function autopayConsentText(array $offer) {
|
||||
$company = billingCompany();
|
||||
return 'I authorize ' . ($company['company_name'] ?? 'you') . " to charge the card I add for each invoice from recurring invoice {$offer['number']}"
|
||||
. ($offer['title'] !== $offer['number'] ? " ({$offer['title']})" : '') . ' on its due date'
|
||||
. ($offer['fee'] !== '' ? ", plus a card fee of {$offer['fee']}" : '') . ', until autopay is turned off.';
|
||||
}
|
||||
|
||||
/**
|
||||
* Start setting autopay up from an invoice's link: the client's Stripe
|
||||
* customer, made now when they have none, and a Checkout Session that saves
|
||||
* a card to it - Stripe's own form, on the page. Who agreed and to what goes
|
||||
* in its metadata, for autopayCheckoutFinish() when Stripe sends them back.
|
||||
* Its client secret, or '' with $error for the client. $name and $email raw.
|
||||
*/
|
||||
function autopayCheckoutStart(array $invoice, $name, $email, &$error = '') {
|
||||
global $mysqli, $config_base_url;
|
||||
$offer = autopayOffer($invoice);
|
||||
$name = trim(mb_substr(preg_replace('/\s+/u', ' ', (string) $name) ?? '', 0, 80));
|
||||
$email = trim(mb_substr((string) $email, 0, 120));
|
||||
if (!$offer) {
|
||||
$error = "Autopay can't be set up from this invoice 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 '';
|
||||
}
|
||||
$provider = billingStripeProvider();
|
||||
$stripe = billingStripeClient();
|
||||
$client_id = intval($invoice['invoice_client_id']);
|
||||
$provider_id = intval($provider['payment_provider_id']);
|
||||
$invoice_id = intval($invoice['invoice_id']);
|
||||
$invoice_number = billingNumber('invoice', $invoice);
|
||||
$recurring_id = intval($offer['recurring']['recurring_invoice_id']);
|
||||
$ids = ['itflow_autopay_invoice_id' => $invoice_id, 'itflow_recurring_invoice_id' => $recurring_id, 'itflow_client_id' => $client_id];
|
||||
|
||||
for ($try = 0; $try < 2; $try++) {
|
||||
$customer = billingStripeCustomer($client_id);
|
||||
try {
|
||||
if ($customer === '') {
|
||||
// One customer a client - two setups at once take turns here
|
||||
$lock = "itflow_stripe_customer_$client_id";
|
||||
mysqli_query($mysqli, "SELECT GET_LOCK('$lock', 15)");
|
||||
try {
|
||||
$customer = billingStripeCustomer($client_id);
|
||||
if ($customer === '') {
|
||||
$made = $stripe->customers->create([
|
||||
'name' => (string) $offer['recurring']['client_name'],
|
||||
'email' => $email,
|
||||
'metadata' => ['itflow_client_id' => $client_id, 'consent_by' => $name],
|
||||
]);
|
||||
$customer = (string) $made->id;
|
||||
mysqli_query($mysqli, "INSERT INTO client_payment_provider SET client_id = $client_id, payment_provider_id = $provider_id,
|
||||
payment_provider_client = '" . escapeSql($customer) . "', client_payment_provider_created_at = NOW()");
|
||||
logAudit("Stripe", "Create", "Guest $name ($email) created Stripe customer for {$offer['recurring']['client_name']} as $customer, setting up autopay from invoice $invoice_number", $client_id);
|
||||
}
|
||||
} finally {
|
||||
mysqli_query($mysqli, "SELECT RELEASE_LOCK('$lock')");
|
||||
}
|
||||
}
|
||||
$session = $stripe->checkout->sessions->create([
|
||||
'mode' => 'setup',
|
||||
'ui_mode' => 'embedded_page',
|
||||
'currency' => strtolower($offer['currency']),
|
||||
'customer' => $customer,
|
||||
'payment_method_types' => ['card'],
|
||||
'return_url' => "https://$config_base_url/guest/guest_post.php?guest_autopay_done=1&invoice_id=$invoice_id&url_key=" . rawurlencode((string) $invoice['invoice_url_key']) . '&session_id={CHECKOUT_SESSION_ID}',
|
||||
'metadata' => $ids + [
|
||||
'itflow_consent_name' => $name,
|
||||
'itflow_consent_email' => $email,
|
||||
'itflow_consent' => mb_substr(autopayConsentText($offer), 0, 500),
|
||||
],
|
||||
'setup_intent_data' => ['description' => "Autopay for recurring invoice {$offer['number']}", 'metadata' => $ids],
|
||||
]);
|
||||
return (string) $session->client_secret;
|
||||
} catch (\Throwable $e) {
|
||||
// A customer Stripe no longer has - forgotten, and made again once
|
||||
if ($try === 0 && $customer !== '' && billingStripeCustomerGone($e)) {
|
||||
billingStripeCustomerForget($client_id, $customer);
|
||||
continue;
|
||||
}
|
||||
logApp("Stripe", "error", "Setting up autopay from invoice $invoice_number couldn't start: " . $e->getMessage());
|
||||
break;
|
||||
}
|
||||
}
|
||||
$error = "Card details can't be taken just now - try again in a few minutes.";
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Finish setting autopay up once Stripe sends the client back from
|
||||
* autopayCheckoutStart()'s form: the session checked with Stripe - complete,
|
||||
* and for this invoice, its recurring invoice and the client's customer -
|
||||
* the card saved, and autopay on for the recurring invoice with it, in place
|
||||
* of any it had. Kept in its history with what they agreed to, logged, the
|
||||
* agents told and the client sent a confirmation. Coming back to the same
|
||||
* address again changes nothing. ['ok' => bool, 'again' => true when it was
|
||||
* done already, 'card' => "Visa •••• 4242", 'emailed' => whether the
|
||||
* confirmation went, 'error' => for the client].
|
||||
*/
|
||||
function autopayCheckoutFinish(array $invoice, $session_id) {
|
||||
global $mysqli;
|
||||
$fail = function ($error) {
|
||||
return ['ok' => false, 'again' => false, 'emailed' => false, 'card' => '', 'error' => $error];
|
||||
};
|
||||
$session_id = (string) $session_id;
|
||||
$provider = billingStripeProvider();
|
||||
$stripe = billingStripeClient();
|
||||
$recurring = intval($invoice['invoice_recurring_invoice_id'] ?? 0) ? billingRow('recurring', $invoice['invoice_recurring_invoice_id'], false) : null;
|
||||
$client_id = intval($invoice['invoice_client_id']);
|
||||
if (!$provider || !$stripe || !$recurring || intval($recurring['recurring_invoice_client_id']) !== $client_id || !preg_match('/^cs_[A-Za-z0-9_]{8,250}$/', $session_id)) {
|
||||
return $fail("Autopay couldn't be set up from that link - get in touch and we'll help.");
|
||||
}
|
||||
$recurring_id = intval($recurring['recurring_invoice_id']);
|
||||
$invoice_id = intval($invoice['invoice_id']);
|
||||
$invoice_number = billingNumber('invoice', $invoice);
|
||||
|
||||
// The same return twice at once - a double click, a reload - takes turns, and the second finds it done
|
||||
$lock = "itflow_autopay_$recurring_id";
|
||||
mysqli_query($mysqli, "SELECT GET_LOCK('$lock', 15)");
|
||||
try {
|
||||
$done = mysqli_fetch_row(mysqli_query($mysqli, "SELECT history_description FROM history WHERE history_recurring_invoice_id = $recurring_id
|
||||
AND history_status = 'Autopay' AND history_description LIKE '%" . escapeSql(addcslashes($session_id, '%_\\')) . "%' LIMIT 1"));
|
||||
if ($done) {
|
||||
return ['ok' => true, 'again' => true, 'emailed' => false, 'card' => preg_match('/ with (.+?) by /u', (string) $done[0], $m) ? $m[1] : '', 'error' => ''];
|
||||
}
|
||||
if (intval($recurring['recurring_invoice_status']) !== 1 || !empty($recurring['recurring_invoice_archived_at'])) {
|
||||
return $fail("This recurring invoice has ended, so autopay wasn't set up. Nothing will be charged.");
|
||||
}
|
||||
$offer = autopayOfferDetails($invoice, $recurring);
|
||||
$customer = billingStripeCustomer($client_id);
|
||||
try {
|
||||
$session = $stripe->checkout->sessions->retrieve($session_id, []);
|
||||
$meta = $session->metadata ? $session->metadata->toArray() : [];
|
||||
if ((string) $session->mode !== 'setup' || intval($meta['itflow_autopay_invoice_id'] ?? 0) !== $invoice_id
|
||||
|| intval($meta['itflow_recurring_invoice_id'] ?? 0) !== $recurring_id || $customer === '' || (string) $session->customer !== $customer) {
|
||||
return $fail("That card setup isn't for this invoice - nothing has changed.");
|
||||
}
|
||||
if ((string) $session->status !== 'complete' || empty($session->setup_intent)) {
|
||||
return $fail("Your card wasn't added, so autopay isn't on yet - 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 card wasn't added, so autopay isn't on yet - try again.");
|
||||
}
|
||||
$pm = $stripe->paymentMethods->retrieve($pm_id, []);
|
||||
} catch (\Throwable $e) {
|
||||
logApp("Stripe", "error", "Setting up autopay from invoice $invoice_number 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.");
|
||||
}
|
||||
|
||||
$provider_id = intval($provider['payment_provider_id']);
|
||||
$pm_sql = escapeSql($pm_id);
|
||||
$description = !empty($pm->card)
|
||||
? "{$pm->card->brand} - {$pm->card->last4} | Exp " . intval($pm->card->exp_month) . '/' . intval($pm->card->exp_year)
|
||||
: 'Card';
|
||||
// The card - saved once, however often it comes back
|
||||
$saved_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 (!$saved_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_id = intval(mysqli_insert_id($mysqli));
|
||||
}
|
||||
$currency = escapeSql($recurring['recurring_invoice_currency_code']);
|
||||
mysqli_query($mysqli, "DELETE FROM recurring_payments WHERE recurring_payment_recurring_invoice_id = $recurring_id");
|
||||
mysqli_query($mysqli, "INSERT INTO recurring_payments SET recurring_payment_currency_code = '$currency', recurring_payment_account_id = " . intval($provider['payment_provider_account']) . ",
|
||||
recurring_payment_method = 'Credit Card', recurring_payment_recurring_invoice_id = $recurring_id, recurring_payment_saved_payment_id = $saved_id");
|
||||
|
||||
$card = 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'] ?? ''));
|
||||
billingLog('recurring', $recurring_id, 'Autopay', "Autopay turned on with $card by $who from invoice $invoice_number's link" . ($consent !== '' ? ", agreeing: \"$consent\"" : '') . " - Stripe $session_id");
|
||||
logAudit("Recurring Invoice", "Auto Payment", "Guest $who turned on Auto Pay with $card for Recurring Invoice {$offer['number']} from invoice $invoice_number's link", $client_id, $recurring_id);
|
||||
appNotify("Autopay", "$name set up autopay for {$recurring['client_name']}'s recurring invoice {$offer['number']} with $card, from invoice $invoice_number's link",
|
||||
"/agent/recurring_invoice.php?recurring_invoice_id=$recurring_id", $client_id, $recurring_id);
|
||||
$emailed = $email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL) && billingEmailReady() && billingMailAutopayOn($email, $name, $offer, $card, $invoice);
|
||||
return ['ok' => true, 'again' => false, 'card' => $card, 'emailed' => $emailed, 'error' => ''];
|
||||
} finally {
|
||||
mysqli_query($mysqli, "SELECT RELEASE_LOCK('$lock')");
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------- Choosing and paying */
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user