Payment Providers stage 1: list rebuilt in the standard pattern showing on or off, live or test mode from the keys, where payments go, the card limit, whether fees are recorded, saved cards with autopay and the last card payment; providers can be turned off and on, and delete states the saved cards, autopay and client links that go with it; Add and Edit share one window that no longer shows the secret key and checks the keys, the live and test mode match, the card limit and the fee vendor and category, and checks new keys with Stripe before anything is saved, showing problems beside each field; fees use a single record-fees switch with vendor and category; changes are logged from old to new value with keys logged only as changed; fixes a rejected Stripe key being saved, the empty provider name and PHP warnings on edit, the ignored enable expense switch, and the stale Online Payment path in the account archive message

This commit is contained in:
johnnyq
2026-10-20 14:16:27 -04:00
parent cd52393138
commit a165189cc3
9 changed files with 827 additions and 438 deletions

View File

@@ -1037,6 +1037,11 @@ If you are coming from 26.08 or earlier, the database update still has to be run
- Why an email failed is kept with it - the mail server's own answer, an address that isn't one, no from address, a domain with no mail server - and shown under its status and searched. Cancelling keeps who cancelled it. The alert for a failed email says why and when it is tried again, and when ITFlow gives up after the last try there is an alert for that too, each opening the Mail Queue on its tab.
- Opening an email shows where it stands and why, who it is to and from, when it was queued, how many tries it has had, when it was sent or last failed, its attachments and calendar file - and the email itself as it will arrive, rather than stripped of its layout. A sent one says what it said was cleared on sending, and why. Retry now, Cancel and Delete are in the window too.
- Without opening it: the Settings overview says when email failed to send in the last day, and when the queue isn't moving, and the Mail tile how many failed this week; the Mail Queue menu item carries the same count; Mail's Tests tab shows when mail was last sent and what is waiting, retrying or failed. The Mail Queue is in the search window (Ctrl K) for admins, and the test email says where to watch it go.
- **Payment Providers** (rebuilt)
- Admin > Payment Providers lists each provider with whether it is on, live or test (as its keys say), the account its payments go into, its card limit, whether its fees are recorded as expenses, its saved cards and the autopay on them, and when a card payment last came through it. Search, sort by any of them, and Saved Cards from the top.
- A provider can be turned off and on again: off, clients can't pay by card and autopay with its cards is skipped, while its cards are kept. Delete says first what goes with it - its saved cards, the autopay on them and its links to clients - and suggests turning it off instead.
- Add and Edit are one window. The secret key is no longer put into it - left empty, it stays as saved. Save checks first: keys that aren't Stripe's, one live and one test, a card limit that isn't money, or fees with no vendor or category are said beside the field, and new keys are checked with Stripe - before anything is saved, and without closing the window or losing what was typed. Fees have one switch, Record its fees as expenses, with who they are paid to and their category. The card limit is shown in your currency.
- The audit log says what changed, from what to what - "Card limit No limit → Under $2,500.00", "Mode test → live" - with the keys only as changed.
### Bug Fixes
@@ -1192,6 +1197,8 @@ If you are coming from 26.08 or earlier, the database update still has to be run
- Settings > Mail: a From address that wasn't an email address was saved blank, and From names lost their punctuation - "PittPC, LLC" was saved as "PittPC LLC".
- Settings > Mail: a password or secret lost a space at either end when saved, and anything from a < up to the next > (or to its end).
- Settings > Mail: pressing Enter on the OAuth tab went off to Microsoft to connect, rather than saving. Changing the OAuth app or its refresh token went on using the old access token until it ran out.
- Payment Providers: a Stripe key that Stripe turned away was saved anyway, with an error after; the Edit window showed the secret key; saving it logged and said an empty provider name, with PHP warnings; the Enable Expense switch did nothing; and there was no way to turn a provider off.
- Accounts: archiving the account online payments go into pointed to Admin > Settings > Online Payment, which no longer exists - it is Admin > Payment Providers.
- Settings > Notifications, and recurring invoices: the note that recurring invoices are made as drafts pointed to the billing settings, but the switch is in Notifications.
- Mail Queue: cancelling an email marked it Failed, and an email to a bad address or with no from address showed Failed with no time.
- Mail Queue: Resend was only offered once all four tries were used up, and the next failure quietly gave a resent email three more.
@@ -1760,6 +1767,7 @@ If you are coming from 26.08 or earlier, the database update still has to be run
- Settings: Tickets, Projects, Quotes, Invoices and billing and Defaults use the frame. New in `functions/settings.php`: `settingsNumbering($kind)`, `settingsNumberInUse()`, `settingsNumberingCheck($kind, $post, $saved)` (prefix and next number checked against the highest in use with that prefix - skipped when both are as saved, so a clash already there doesn't block the rest of the page) and `settingsNumberingFields()` (with `[data-settings-next]` in `js/settings.js`, and `[data-settings-depends-on=name]` to fade fields while a switch is off); `settingsEmailProblem()`; `settingsStartPages()`, `settingsStartPageProblem()` and `settingsNetTerms()`. `settingsSectionStart()` takes the section's element id, so `#reminders`, `#billing-time`, `#billable-expenses` and `#mileage` still work; `settingsSelect()` takes `options_html`, `append` and `search => false`; `settingsSwitch()` takes `id`. `settingsSame()` treats NULL as 0 or empty and ignores Windows line ends; the log names accounts, calendars and categories. Values kept from a refused save are only used for five minutes. These handlers keep a setting that isn't sent (`$_POST + saved`), a switch not sent being off. Defaults' fields are renamed to their columns (`config_start_page`, `config_default_*`). The start page is escaped where it is printed.
- Settings: Notifications, Security, Client portal, Single sign-on (`admin/identity_providers.php`), Mail and Logs use the frame. `settingsSearch($query, $limit)` scores settings as Find a setting does, leaving out pages for a module that is off; `agent/ajax.php?global_search` returns them as `settings` for admins and `js/global_search.js` shows them under Settings. Single sign-on's fields are renamed to their columns (`config_azure_client_id`, `config_azure_client_secret`). A field marked `quiet` in `settingsFields()` is logged as changed without its value (the login key). The Logs handler is unchanged.
- Settings: Mail's Sending, Receiving, OAuth and From addresses tabs use the frame, and every Mail column is in `settingsFields()`. Its handlers save through `settingsSave()` and `settingsWrite()`, logging from -> to; `edit_mail_smtp_settings` and `edit_mail_imap_settings` share one check, and both come back to their tab when refused. A password, secret or refresh token posted empty keeps what is saved; an empty OAuth client ID forgets its secret and refresh token; a changed app or refresh token clears `config_mail_oauth_access_token` and its expiry, so it is fetched again. The access token is no longer a field. `oauth_connect_microsoft_mail` saves the same way before going to Microsoft, and `admin/oauth_microsoft_mail_callback.php` now stores only the tokens. New in `functions/settings.php`: `settingsMailProviders()`, `settingsMailEncryption()` and `settingsEnterSaves($button)` - a hidden Save placed first in a form whose first button would otherwise be another (Mail's OAuth tab, Logs). `settingsRefuse()` takes the page to go back to; `settingsInput()`, `settingsSelect()` and `settingsTextarea()` take `id`; `settingsWrite()` writes a `secret` field exactly as given, rather than through `escapeSql()`, which trims and strips tags.
- Payment Providers: new `functions/payment_provider.php` - `paymentProviderKinds()` (the providers ITFlow takes payments through and what their keys look like), `paymentProviderMode()`, `paymentProviderRow()`, `paymentProviderTies()` and `paymentProviderTiesText()`, `paymentProviderLimitText()`, `paymentProviderCheck($post, $before)`, `paymentProviderKeysChanged()`, `paymentProviderAsk($name, $secret_key)` (Stripe's account, from the secret key), `paymentProviderChangeLines()` and `paymentProviderWrite()`, which saves the keys exactly as given. `check_payment_provider` answers in JSON - `ok`, `errors` by field and the Stripe `account` - and the window asks it before saving; a key it has had taken isn't asked about again on the save, for ten minutes. New handlers `turn_payment_provider_off` and `turn_payment_provider_on` (GET with the CSRF token). `payment_provider_add.php` opens `payment_provider_edit.php` with no id. Field `record_fees` replaces `enable_expense`; `active` and `description` are new. `admin/post/payment_provider_model.php` is gone.
- Removed, as nothing reached them or they couldn't run: `admin/settings_custom_fields.php` (it required a modal that no longer existed) with `admin/post/custom_field.php`, `admin/post/custom_field_model.php` and `admin/modals/custom_field/`; `admin/post/settings_ai.php` and `admin/post/settings_online_payment.php`, which wrote the `config_ai_*` and `config_stripe_*` columns dropped in 2.3.2; `admin/post/settings_online_payment_clients.php`, and `agent/client_autopay.php`, which read the dropped Stripe columns and was linked from nowhere. The `custom_fields` and `custom_values` tables stay as they are, and the client export still includes asset custom field values.
- Mail Queue: new `functions/mail_queue.php` - `MAIL_QUEUE_TRIES` (4), `MAIL_QUEUE_RETRY_MINUTES` (30) and `MAIL_QUEUE_KEEP_DAYS` (90), which `cron/mail_queue.php`'s retry pass and the nightly clean-up now use too; `mailQueueTabs()`, `mailQueueState($row)`, `mailQueueCan($row, $action)`, `mailQueueAct($action, $ids)` and `mailQueueHealth()`. `email_status` 4 is Cancelled - never selected by the worker. Retry now sets status 0, no attempts and no failure time. Handlers: `retry_mail`, `cancel_mail`, `delete_mail` (GET with the CSRF token) and `bulk_retry_emails`, `bulk_cancel_emails`, `bulk_delete_emails`; `send_failed_mail` still works. The worker sets `email_failed_at` on the bad sender, bad recipient and no-MX paths.
- Mail Queue: database 3.3.7 adds `email_queue.email_error` varchar(500) - why it last failed, or "Cancelled by ..."; cleared when sent or retried. The worker writes it on every failure path, through `mailQueueErrorSql()`, which leaves it out until the update has run, so an install between updating its files and its database still sends; `mailQueueErrorColumn()` does the same for reads. The retry pass's bad-recipient path now sets `email_failed_at`, so its backoff counts from that try. An alert (`appNotify`) when the retry pass gives up. The email's window shows the queued HTML in an iframe `srcdoc` with `sandbox="allow-popups allow-popups-to-escape-sandbox"` (no scripts, no same origin) and a `script-src 'none'` policy, instead of HTMLPurifier in the page.

View File

@@ -1,155 +1,9 @@
<?php
require_once '../../includes/modal_header.php';
/*
* Admin > Payment Providers - Add. The same window as Edit
* (payment_provider_edit.php), with no provider yet.
*/
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class="fa fa-fw fa-credit-card me-2"></i>Add Payment Provider</h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form action="post.php" method="post" autocomplete="off">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<div class="modal-body">
<ul class="nav nav-pills nav-justified mb-3">
<li class="nav-item">
<a class="nav-link active" data-bs-toggle="pill" href="#pills-details">Details</a>
</li>
<li class="nav-item">
<a class="nav-link" data-bs-toggle="pill" href="#pills-expense">Expense</a>
</li>
</ul>
<hr>
<div class="tab-content">
<div class="tab-pane fade show active" id="pills-details">
<div class="mb-3">
<label>Provider <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-credit-card"></i></span>
<select class="form-select select2" name="provider">
<option>Stripe</option>
</select>
</div>
</div>
<div class="mb-3">
<label>Publishable key <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-eye"></i></span>
<input type="text" class="form-control" name="public_key" placeholder="Publishable API Key (pk_...)" maxlength="250">
</div>
</div>
<div class="mb-3">
<label>Secret key <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-key"></i></span>
<input type="text" class="form-control" name="private_key" placeholder="Secret API Key (sk_...)" maxlength="250">
</div>
</div>
<div class="mb-3">
<label>Income / Expense Account <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-piggy-bank"></i></span>
<select class="form-select select2" name="account" required>
<option value="">- Select an Account -</option>
<?php
$sql = mysqli_query($mysqli, "SELECT account_id, account_name FROM accounts WHERE account_archived_at IS NULL ORDER BY account_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$account_id = intval($row['account_id']);
$account_name = escapeHtml($row['account_name']);
?>
<option <?php if ($account_name === 'Stripe') { echo "selected"; } ?> value="<?= $account_id ?>"><?= $account_name ?></option>
<?php
}
?>
</select>
</div>
<small class="form-text text-muted">Should have a seperate account created off the payment provider's name e.g. Stripe</small>
</div>
<div class="mb-3">
<label>Threshold</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-shopping-cart"></i></span>
<input type="text" class="form-control" inputmode="decimal" pattern="[0-9]*\.?[0-9]{0,2}" name="threshold" placeholder="1000.00">
</div>
<small class="form-text text-muted">Will not show as an option at Checkout if invoice amount is above this number, 0 disables the threshold check.</small>
</div>
</div>
<div class="tab-pane fade" id="pills-expense">
<div class="alert alert-info text-center">
Payment Processing Fee Expenses get reconciled nighly via the cron
</div>
<div class="mb-3">
<div class="form-check form-switch">
<input type="checkbox" class="form-check-input" name="enable_expense" checked value="1" id="enableExpenseSwitch">
<label class="form-check-label" for="enableExpenseSwitch">Enable Expense</label>
</div>
</div>
<div class="mb-3">
<label>Payment Provider Vendor <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-building"></i></span>
<select class="form-select select2" name="expense_vendor" required>
<option value="0">Expense Disabled</option>
<?php
$sql = mysqli_query($mysqli, "SELECT vendor_id, vendor_name FROM vendors WHERE vendor_client_id = 0 AND vendor_archived_at IS NULL ORDER BY vendor_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$vendor_id = intval($row['vendor_id']);
$vendor_name = escapeHtml($row['vendor_name']);
?>
<option <?php if ($vendor_name === 'Stripe') { echo "selected"; } ?> value="<?= $vendor_id ?>"><?= $vendor_name ?></option>
<?php
}
?>
</select>
</div>
<small class="form-text text-muted">Payment Privider name e.g. Stripe</small>
</div>
<div class="mb-3">
<label>Expense Category <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-list"></i></span>
<select class="form-select select2" name="expense_category" required>
<option value="">- Select a Category -</option>
<?php
// Processing Fee to start with, when there is one
$fee_category = mysqli_fetch_row(mysqli_query($mysqli, "SELECT category_id FROM categories WHERE category_type = 'Expense' AND category_name = 'Processing Fee' AND category_archived_at IS NULL LIMIT 1"));
?>
<?= categoryOptionsHtml('Expense', $fee_category ? intval($fee_category[0]) : null) ?>
</select>
<?= categoryAddButtonHtml('Expense', 'btn btn-secondary') ?>
</div>
<small class="form-text text-muted">Processing Fee, Credit Card Fee etc</small>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" name="add_payment_provider" class="btn btn-primary text-bold"><i class="fa fa-check me-2"></i>Add</button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fa fa-times me-2"></i>Cancel</button>
</div>
</form>
<?php
require_once '../../../includes/modal_footer.php';
$_GET['id'] = 0;
require __DIR__ . '/payment_provider_edit.php';

View File

@@ -1,154 +1,309 @@
<?php
/*
* Admin > Payment Providers - one provider's window: Add (no id, or from
* payment_provider_add.php) or Edit. Its keys - the secret one never put back
* into the page, so left empty it stays - whether it is on, the account its
* payments go into, the card limit, and whether its fees are recorded as
* expenses. Save asks first (check_payment_provider,
* admin/post/payment_provider.php): what is wrong shows beside each field and
* the window stays open; once all is right, it saves.
*/
require_once '../../includes/modal_header.php';
$provider_id = intval($_GET['id']);
$provider_id = intval($_GET['id'] ?? 0);
$row = $provider_id ? paymentProviderRow($provider_id) : null;
if ($provider_id && !$row) {
echo json_encode(['error' => 'That payment provider no longer exists.']);
exit;
}
$sql = mysqli_query($mysqli, "SELECT payment_provider_account, payment_provider_expense_category,
payment_provider_expense_vendor, payment_provider_name, payment_provider_private_key,
payment_provider_public_key, payment_provider_threshold FROM payment_providers WHERE payment_provider_id = $provider_id LIMIT 1");
$kinds = paymentProviderKinds();
$taken = [];
$sql = mysqli_query($mysqli, "SELECT payment_provider_name FROM payment_providers");
while ($taken_row = mysqli_fetch_row($sql)) {
$taken[$taken_row[0]] = true;
}
$free_kinds = array_diff_key($kinds, $taken);
$row = mysqli_fetch_assoc($sql);
$provider_name = escapeHtml($row['payment_provider_name']);
$public_key = escapeHtml($row['payment_provider_public_key']);
$private_key = escapeHtml($row['payment_provider_private_key']);
$account_id = intval($row['payment_provider_account']);
$threshold = floatval($row['payment_provider_threshold']);
$vendor_id = intval($row['payment_provider_expense_vendor']);
$category_id = intval($row['payment_provider_expense_category']);
$name = $row ? (string) $row['payment_provider_name'] : (string) (array_key_first($free_kinds) ?? array_key_first($kinds));
$kind = $kinds[$name] ?? reset($kinds);
$mode = $row ? paymentProviderMode($row['payment_provider_private_key']) : '';
$account_id = intval($row['payment_provider_account'] ?? 0);
$vendor_id = intval($row['payment_provider_expense_vendor'] ?? 0);
$category_id = intval($row['payment_provider_expense_category'] ?? 0);
$threshold = round(floatval($row['payment_provider_threshold'] ?? 0), 2);
$records_fees = $row ? ($vendor_id > 0 && $category_id > 0) : true;
// A new one starts on an account and a vendor named for it, and Processing Fee, where there are those
if (!$row) {
$starts = mysqli_fetch_row(mysqli_query($mysqli, "SELECT
(SELECT account_id FROM accounts WHERE account_name = '" . escapeSql($name) . "' AND account_archived_at IS NULL LIMIT 1),
(SELECT vendor_id FROM vendors WHERE vendor_name = '" . escapeSql($name) . "' AND vendor_client_id = 0 AND vendor_archived_at IS NULL LIMIT 1),
(SELECT category_id FROM categories WHERE category_type = 'Expense' AND category_name = 'Processing Fee' AND category_archived_at IS NULL LIMIT 1)"));
$account_id = intval($starts[0] ?? 0);
$vendor_id = intval($starts[1] ?? 0);
$category_id = intval($starts[2] ?? 0);
}
$accounts = mysqli_query($mysqli, "SELECT account_id, account_name, account_archived_at FROM accounts WHERE account_archived_at IS NULL OR account_id = $account_id ORDER BY account_name ASC");
$vendors = mysqli_query($mysqli, "SELECT vendor_id, vendor_name, vendor_archived_at FROM vendors WHERE vendor_client_id = 0 AND (vendor_archived_at IS NULL OR vendor_id = $vendor_id) ORDER BY vendor_name ASC");
$currency = (string) ($session_company_currency ?? '');
// Where what is wrong with a field shows
$error_for = function ($field) {
return '<div class="invalid-feedback" data-error-for="' . $field . '"></div>';
};
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class="fa fa-fw fa-credit-card me-2"></i>Editing: <strong><?= $provider_name ?></strong></h5>
<h5 class="modal-title">
<i class="fa fa-fw fa-credit-card me-2"></i><?= $row ? '<strong>' . escapeHtml($name) . '</strong>' : 'Add Payment Provider' ?>
<?php if ($mode !== '') { ?>
<span class="badge <?= $mode === 'live' ? 'text-bg-success' : 'text-bg-warning' ?> ms-2 align-middle" data-provider-mode><?= $mode === 'live' ? 'Live' : 'Test' ?></span>
<?php } ?>
</h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form action="post.php" method="post" autocomplete="off">
<form action="post.php" method="post" autocomplete="off" novalidate data-payment-provider-form>
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<input type="hidden" name="provider_id" value="<?= $provider_id ?>">
<input type="hidden" name="provider" value="<?= $provider_name ?>">
<div class="modal-body">
<ul class="nav nav-pills nav-justified mb-3">
<li class="nav-item">
<a class="nav-link active" data-bs-toggle="pill" href="#pills-details">Details</a>
</li>
<li class="nav-item">
<a class="nav-link" data-bs-toggle="pill" href="#pills-expense">Expense</a>
</li>
</ul>
<?php if (!$row && !$free_kinds) { ?>
<div class="alert alert-info py-2 small mb-3"><i class="fas fa-fw fa-info-circle me-1"></i><?= escapeHtml(implode(' and ', array_keys($kinds))) ?> is set up already - it is the only provider ITFlow takes payments through.</div>
<?php } ?>
<hr>
<div class="tab-content">
<div class="tab-pane fade show active" id="pills-details">
<div class="mb-3">
<label>Publishable key <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-eye"></i></span>
<input type="text" class="form-control" name="public_key" placeholder="Publishable API Key (pk_...)" maxlength="250" value="<?= $public_key ?>">
</div>
<?php if (!$row) { ?>
<div class="mb-3">
<label class="form-label" for="paymentProviderName">Provider <strong class="text-danger">*</strong></label>
<div class="input-group has-validation">
<span class="input-group-text"><i class="fa fa-fw fa-credit-card"></i></span>
<select class="form-select" name="provider" id="paymentProviderName">
<?php foreach ($kinds as $kind_name => $kind_info) { ?>
<option value="<?= escapeHtml($kind_name) ?>" <?= $kind_name === $name ? 'selected' : '' ?> <?= isset($taken[$kind_name]) ? 'disabled' : '' ?>><?= escapeHtml($kind_name) ?><?= isset($taken[$kind_name]) ? ' - set up already' : '' ?></option>
<?php } ?>
</select>
</div>
<div class="mb-3">
<label>Secret key <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-key"></i></span>
<input type="text" class="form-control" name="private_key" placeholder="Secret API Key (sk_...)" maxlength="250" value="<?= $private_key ?>">
</div>
<?= $error_for('provider') ?>
</div>
<?php } else { ?>
<div class="mb-3">
<div class="form-check form-switch">
<input type="checkbox" class="form-check-input" name="active" value="1" id="paymentProviderActive" <?= intval($row['payment_provider_active']) ? 'checked' : '' ?>>
<label class="form-check-label" for="paymentProviderActive">On - clients can pay invoices by card</label>
</div>
<div class="form-text ps-5">Off, they can't, and autopay with its saved cards is skipped. Its cards are kept.</div>
</div>
<?php } ?>
<div class="mb-3">
<label>Income / Expense Account <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-piggy-bank"></i></span>
<select class="form-select select2" name="account" required>
<option value="">- Select an Account -</option>
<?php
<div class="mb-3">
<label class="form-label" for="paymentProviderDescription">Description</label>
<div class="input-group has-validation">
<span class="input-group-text"><i class="fa fa-fw fa-align-left"></i></span>
<input type="text" class="form-control" name="description" id="paymentProviderDescription" maxlength="250" placeholder="What it is for, if you like" value="<?= escapeHtml($row['payment_provider_description'] ?? '') ?>">
</div>
<?= $error_for('description') ?>
</div>
$sql = mysqli_query($mysqli, "SELECT account_id, account_name FROM accounts WHERE account_archived_at IS NULL ORDER BY account_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$account_id_select = intval($row['account_id']);
$account_name = escapeHtml($row['account_name']);
?>
<option <?php if ($account_id === $account_id_select) { echo "selected"; } ?> value="<?= $account_id_select ?>"><?= $account_name ?></option>
<h6 class="fw-semibold mt-4 mb-1">Keys</h6>
<p class="small text-body-secondary mb-2">From <a href="<?= escapeHtml($kind['keys_url']) ?>" target="_blank" rel="noopener noreferrer"><?= escapeHtml($name) ?>'s Developers &gt; API keys <i class="fas fa-external-link-alt fa-xs"></i></a> - both live, or both test while you try it out.</p>
<?php
}
?>
</select>
</div>
<small class="form-text text-muted">Should have a seperate account created off the payment provider's name e.g. Stripe</small>
<div class="mb-3">
<label class="form-label" for="paymentProviderPublicKey">Publishable key <strong class="text-danger">*</strong></label>
<div class="input-group has-validation">
<span class="input-group-text"><i class="fa fa-fw fa-eye"></i></span>
<input type="text" class="form-control font-monospace" name="public_key" id="paymentProviderPublicKey" maxlength="250" spellcheck="false" placeholder="<?= escapeHtml($kind['public_example']) ?>" value="<?= escapeHtml($row['payment_provider_public_key'] ?? '') ?>">
</div>
<?= $error_for('public_key') ?>
</div>
<div class="mb-3">
<label class="form-label" for="paymentProviderSecretKey">Secret key <?= $row ? '' : '<strong class="text-danger">*</strong>' ?></label>
<div class="input-group has-validation">
<span class="input-group-text"><i class="fa fa-fw fa-key"></i></span>
<input type="password" class="form-control font-monospace" name="private_key" id="paymentProviderSecretKey" maxlength="250" spellcheck="false" autocomplete="new-password"
placeholder="<?= $row && trim((string) $row['payment_provider_private_key']) !== '' ? 'Saved - type a new one to replace it' : escapeHtml($kind['secret_example']) ?>">
</div>
<?= $error_for('private_key') ?>
<div class="form-text">A restricted key (rk_...) does too, with write access to payment intents, customers, setup intents and payment methods, and read on the account.</div>
</div>
<div class="alert alert-success py-2 small d-none" data-provider-account></div>
<h6 class="fw-semibold mt-4 mb-2">Payments</h6>
<div class="mb-3">
<label class="form-label" for="paymentProviderAccount">Payments go into <strong class="text-danger">*</strong></label>
<div class="input-group has-validation">
<span class="input-group-text"><i class="fa fa-fw fa-piggy-bank"></i></span>
<select class="form-select select2" name="account" id="paymentProviderAccount">
<option value="">- Pick an account -</option>
<?php while ($account = mysqli_fetch_assoc($accounts)) { ?>
<option value="<?= intval($account['account_id']) ?>" <?= intval($account['account_id']) === $account_id ? 'selected' : '' ?>><?= escapeHtml($account['account_name']) ?><?= $account['account_archived_at'] ? ' (archived)' : '' ?></option>
<?php } ?>
</select>
</div>
<?= $error_for('account') ?>
<div class="form-text">An account of its own, named for it, makes its payouts easy to match.</div>
</div>
<div class="mb-3">
<label class="form-label" for="paymentProviderThreshold">Card limit</label>
<div class="input-group has-validation">
<span class="input-group-text"><i class="fa fa-fw fa-shopping-cart"></i></span>
<input type="text" class="form-control" name="threshold" id="paymentProviderThreshold" inputmode="decimal" maxlength="16" placeholder="No limit" value="<?= $threshold > 0 ? escapeHtml(number_format($threshold, 2, '.', '')) : '' ?>">
<?php if ($currency !== '') { ?><span class="input-group-text"><?= escapeHtml($currency) ?></span><?php } ?>
</div>
<?= $error_for('threshold') ?>
<div class="form-text">An invoice of this much or more can't be paid by card. Empty for no limit.</div>
</div>
<h6 class="fw-semibold mt-4 mb-2">Fees</h6>
<div class="mb-3">
<div class="form-check form-switch">
<input type="checkbox" class="form-check-input" name="record_fees" value="1" id="paymentProviderRecordFees" <?= $records_fees ? 'checked' : '' ?> data-provider-fees-switch>
<label class="form-check-label" for="paymentProviderRecordFees">Record its fees as expenses</label>
</div>
<div class="form-text ps-5">Each night, its fee on each card payment is recorded as an expense from the account above.</div>
</div>
<div data-provider-fees>
<div class="mb-3">
<label class="form-label" for="paymentProviderVendor">Paid to <strong class="text-danger">*</strong></label>
<div class="input-group has-validation">
<span class="input-group-text"><i class="fa fa-fw fa-building"></i></span>
<select class="form-select select2" name="expense_vendor" id="paymentProviderVendor">
<option value="">- Pick a vendor -</option>
<?php while ($vendor = mysqli_fetch_assoc($vendors)) { ?>
<option value="<?= intval($vendor['vendor_id']) ?>" <?= intval($vendor['vendor_id']) === $vendor_id ? 'selected' : '' ?>><?= escapeHtml($vendor['vendor_name']) ?><?= $vendor['vendor_archived_at'] ? ' (archived)' : '' ?></option>
<?php } ?>
</select>
</div>
<div class="mb-3">
<label>Threshold</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-shopping-cart"></i></span>
<input type="text" class="form-control" inputmode="decimal" pattern="[0-9]*\.?[0-9]{0,2}" name="threshold" placeholder="1000.00" value="<?= $threshold ?>">
</div>
<small class="form-text text-muted">Will not show as an option at Checkout if above this number</small>
</div>
<?= $error_for('expense_vendor') ?>
<div class="form-text">One of your own vendors - <?= escapeHtml($name) ?> itself.</div>
</div>
<div class="tab-pane fade" id="pills-expense">
<div class="alert alert-info text-center">
Payment Processing Fee Expenses get reconciled nighly via the cron
</div>
<div class="mb-3">
<label>Payment Provider Vendor <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-building"></i></span>
<select class="form-select select2" name="expense_vendor" required>
<option value="0">Expense Disabled</option>
<?php
$sql = mysqli_query($mysqli, "SELECT vendor_id, vendor_name FROM vendors WHERE vendor_client_id = 0 AND vendor_archived_at IS NULL ORDER BY vendor_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$vendor_id_select = intval($row['vendor_id']);
$vendor_name = escapeHtml($row['vendor_name']);
?>
<option <?php if ($vendor_id === $vendor_id_select) { echo "selected"; } ?>
value="<?= $vendor_id_select ?>"><?= $vendor_name ?>
</option>
<?php
}
?>
</select>
</div>
<small class="form-text text-muted">Payment Privider name e.g. Stripe</small>
</div>
<div class="mb-3">
<label>Expense Category <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-list"></i></span>
<select class="form-select select2" name="expense_category" required>
<option value="">- Select a Category -</option>
<?= categoryOptionsHtml('Expense', $category_id) ?>
</select>
<?= categoryAddButtonHtml('Expense', 'btn btn-secondary') ?>
</div>
<small class="form-text text-muted">Processing Fee, Credit Card Fee etc</small>
<div class="mb-3">
<label class="form-label" for="paymentProviderCategory">Category <strong class="text-danger">*</strong></label>
<div class="input-group has-validation">
<span class="input-group-text"><i class="fa fa-fw fa-list"></i></span>
<select class="form-select select2" name="expense_category" id="paymentProviderCategory">
<option value="">- Pick a category -</option>
<?= categoryOptionsHtml('Expense', $category_id ?: null) ?>
</select>
<?= categoryAddButtonHtml('Expense', 'btn btn-secondary') ?>
</div>
<?= $error_for('expense_category') ?>
<div class="form-text">Processing Fee, or the like.</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" name="edit_payment_provider" class="btn btn-primary text-bold"><i class="fa fa-check me-2"></i>Save</button>
<button type="submit" name="<?= $row ? 'edit_payment_provider' : 'add_payment_provider' ?>" class="btn btn-primary text-bold" data-provider-save <?= !$row && !$free_kinds ? 'disabled' : '' ?>>
<i class="fa fa-check me-2"></i><?= $row ? 'Save' : 'Add' ?>
</button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fa fa-times me-2"></i>Cancel</button>
</div>
</form>
<?php
<script>
// Fees - their vendor and category only while they are recorded. Save - asked first, so what is wrong shows here
(function () {
var form = document.querySelector('[data-payment-provider-form]:not([data-ready])');
if (!form) {
return;
}
form.setAttribute('data-ready', '1');
var feesSwitch = form.querySelector('[data-provider-fees-switch]');
var fees = form.querySelector('[data-provider-fees]');
var save = form.querySelector('[data-provider-save]');
var accountNote = form.querySelector('[data-provider-account]');
var checked = false;
// A disabled select isn't sent, and its picker follows it
function showFees() {
var on = feesSwitch.checked;
fees.classList.toggle('opacity-50', !on);
fees.querySelectorAll('select, button').forEach(function (el) {
el.disabled = !on;
});
}
feesSwitch.addEventListener('change', showFees);
showFees();
function clearErrors() {
form.querySelectorAll('.is-invalid').forEach(function (el) { el.classList.remove('is-invalid'); });
form.querySelectorAll('[data-error-for]').forEach(function (el) {
el.textContent = '';
el.classList.remove('d-block');
});
}
function showErrors(errors) {
var first = null;
Object.keys(errors).forEach(function (field) {
var input = form.querySelector('[name="' + field + '"]');
var box = form.querySelector('[data-error-for="' + field + '"]');
if (input) {
input.classList.add('is-invalid');
first = first || input;
}
if (box) {
box.textContent = errors[field];
box.classList.add('d-block');
}
});
if (first && first.offsetParent !== null) {
first.focus();
}
}
form.addEventListener('submit', function (e) {
if (checked) {
return;
}
e.preventDefault();
var label = save.innerHTML;
save.disabled = true;
save.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Checking';
var data = new FormData(form);
data.append('check_payment_provider', '1');
fetch(form.getAttribute('action'), { method: 'POST', body: data, credentials: 'same-origin', headers: { 'Accept': 'application/json' } })
.then(function (response) { return response.json(); })
.then(function (answer) {
clearErrors();
save.disabled = false;
if (answer.ok) {
if (answer.account && answer.account.name) {
accountNote.textContent = 'Connected to ' + answer.account.name + (answer.account.email ? ' (' + answer.account.email + ')' : '') + ' - saving';
accountNote.classList.remove('d-none');
}
checked = true;
save.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Saving';
form.requestSubmit(save);
save.disabled = true;
return;
}
save.innerHTML = label;
showErrors(answer.errors || {});
})
.catch(function () {
// Couldn't ask - send it as it is, and the save says what is wrong
checked = true;
save.disabled = false;
save.innerHTML = label;
form.requestSubmit(save);
});
});
})();
</script>
<?php
require_once '../../../includes/modal_footer.php';

View File

@@ -1,145 +1,192 @@
<?php
/*
* Admin > Payment Providers - the services clients pay invoices by card
* through (functions/payment_provider.php). Each row says whether it is on,
* live or test (as its keys say), the account its payments go into, its card
* limit, whether its fees are recorded as expenses, its saved cards and the
* autopay on them, and when a card payment last came through it. Add and
* Edit are one window (modals/payment_provider/payment_provider_edit.php);
* turning one off, on and deleting it are admin/post/payment_provider.php.
*/
// Default Column Sortby Filter
$sort = "payment_provider_name";
$order = "ASC";
require_once "includes/inc_all_admin.php";
$sql = mysqli_query($mysqli, "SELECT SQL_CALC_FOUND_ROWS account_name, category_name, payment_provider_description, payment_provider_id,
payment_provider_name, payment_provider_threshold, vendor_name FROM payment_providers
LEFT JOIN accounts ON payment_provider_account = account_id
LEFT JOIN vendors ON payment_provider_expense_vendor = vendor_id
LEFT JOIN categories ON payment_provider_expense_category = category_id
WHERE payment_provider_name LIKE '%$q%' OR payment_provider_description LIKE '%$q%'
ORDER BY $sort $order LIMIT $record_from, $record_to"
);
// Only these sort - an unknown column would take the page down
$sortable_columns = [
'payment_provider_name' => "payment_provider_name $order",
'account_name' => "account_name $order, payment_provider_name ASC",
'payment_provider_threshold' => "payment_provider_threshold $order, payment_provider_name ASC",
'saved_cards' => "saved_cards $order, payment_provider_name ASC",
'last_paid' => "last_paid IS NULL, last_paid $order, payment_provider_name ASC",
];
if (!isset($sortable_columns[$sort])) {
$sort = 'payment_provider_name';
}
$sql = mysqli_query($mysqli, "SELECT SQL_CALC_FOUND_ROWS payment_provider_id, payment_provider_name, payment_provider_description, payment_provider_private_key,
payment_provider_threshold, payment_provider_active, payment_provider_account, payment_provider_expense_vendor, payment_provider_expense_category,
account_name, account_archived_at, vendor_name, category_name,
COALESCE(cards.saved_cards, 0) AS saved_cards, COALESCE(cards.autopay, 0) AS autopay,
(SELECT MAX(payment_date) FROM payments WHERE payment_archived_at IS NULL AND payment_reference LIKE CONCAT(payment_provider_name, ' - %')) AS last_paid
FROM payment_providers
LEFT JOIN accounts ON account_id = payment_provider_account
LEFT JOIN vendors ON vendor_id = payment_provider_expense_vendor AND payment_provider_expense_vendor > 0
LEFT JOIN categories ON category_id = payment_provider_expense_category AND payment_provider_expense_category > 0
LEFT JOIN (
SELECT saved_payment_provider_id, COUNT(DISTINCT saved_payment_id) AS saved_cards, COUNT(recurring_payment_id) AS autopay
FROM client_saved_payment_methods LEFT JOIN recurring_payments ON recurring_payment_saved_payment_id = saved_payment_id
GROUP BY saved_payment_provider_id
) cards ON cards.saved_payment_provider_id = payment_provider_id
WHERE (payment_provider_name LIKE '%$q%' OR payment_provider_description LIKE '%$q%' OR account_name LIKE '%$q%' OR vendor_name LIKE '%$q%' OR category_name LIKE '%$q%')
ORDER BY {$sortable_columns[$sort]}, payment_provider_id ASC
LIMIT $record_from, $record_to");
$num_rows = mysqli_fetch_row(mysqli_query($mysqli, "SELECT FOUND_ROWS()"));
// Add only while there is a provider ITFlow takes payments through that isn't set up
$set_up = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(DISTINCT payment_provider_name) FROM payment_providers WHERE payment_provider_name IN ('"
. implode("', '", array_map('escapeSql', array_keys(paymentProviderKinds()))) . "')"))[0]);
$can_add = $set_up < count(paymentProviderKinds());
$sort_link = function ($column, $label) use ($url_query_strings_sort, $sort, $disp, $order_icon) {
return '<a class="text-reset text-decoration-none" href="?' . escapeHtml($url_query_strings_sort) . '&amp;sort=' . $column . '&amp;order=' . $disp . '">'
. $label . ($sort === $column ? " $order_icon" : '') . '</a>';
};
$add_url = 'modals/payment_provider/payment_provider_add.php';
$csrf = $_SESSION['csrf_token'];
?>
<div class="card">
<div class="card-header bg-dark py-2">
<h3 class="card-title mt-2"><i class="fas fa-fw fa-credit-card me-2"></i>Payment Providers</h3>
<div class="card-tools">
<button type="button" class="btn btn-primary ajax-modal" data-modal-url="modals/payment_provider/payment_provider_add.php"><i class="fas fa-plus me-2"></i>Add Provider</button>
<a class="btn btn-outline-light me-1" href="saved_payment_methods.php"><i class="fas fa-fw fa-wallet"></i><span class="d-none d-lg-inline ms-2">Saved Cards</span></a>
<?php if ($can_add) { ?>
<button type="button" class="btn btn-primary ajax-modal" data-modal-url="<?= $add_url ?>"><i class="fas fa-plus"></i><span class="d-none d-lg-inline ms-2">Add Provider</span></button>
<?php } ?>
</div>
</div>
<div class="card-header py-3">
<form autocomplete="off">
<div class="row g-2 align-items-center">
<div class="col-md-4">
<div class="col-lg-5 col-md-6">
<div class="input-group">
<input type="search" class="form-control" name="q" value="<?php if (isset($q)) { echo stripslashes(escapeHtml($q)); } ?>" placeholder="Search Payment Providers">
<button class="btn btn-primary" title="Search"><i class="fa fa-search"></i></button>
<input type="search" class="form-control" name="q" value="<?php if (isset($q)) { echo stripslashes(escapeHtml($q)); } ?>" placeholder="Search payment providers..." title="Name, description, account, fee vendor or category">
<button class="btn btn-dark" title="Search"><i class="fa fa-search"></i></button>
</div>
</div>
</div>
</form>
</div>
<div class="table-responsive-sm">
<table class="table table-striped table-borderless table-hover mb-0">
<thead class="text-dark <?php if ($num_rows[0] == 0) { echo "d-none"; } ?>">
<div class="table-responsive">
<table class="table table-hover align-middle mb-0">
<thead class="table-light text-nowrap <?php if ($num_rows[0] == 0) { echo "d-none"; } ?>">
<tr>
<th class="ps-3">
<a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=payment_provider_name&order=<?= $disp ?>">
Provider <?php if ($sort == 'payment_provider_name') { echo $order_icon; } ?>
</a>
</th>
<th>
<a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=account_name&order=<?= $disp ?>">
Expense / Income Account <?php if ($sort == 'account_name') { echo $order_icon; } ?>
</a>
</th>
<th>
<a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=payment_provider_threshold&order=<?= $disp ?>">
Threshold <?php if ($sort == 'payment_provider_threshold') { echo $order_icon; } ?>
</a>
</th>
<th>
<a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=vendor_name&order=<?= $disp ?>">
Expense Vendor <?php if ($sort == 'vendor_name') { echo $order_icon; } ?>
</a>
</th>
<th>
<a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=category_name&order=<?= $disp ?>">
Expense Category <?php if ($sort == 'category_name') { echo $order_icon; } ?>
</a>
</th>
<th class="text-center">
<a class="text-dark">Saved Payment Methods</a>
</th>
<th class="text-center">Action</th>
<th class="ps-3"><?= $sort_link('payment_provider_name', 'Provider') ?></th>
<th class="d-none d-md-table-cell"><?= $sort_link('account_name', 'Payments go into') ?></th>
<th class="d-none d-lg-table-cell"><?= $sort_link('payment_provider_threshold', 'Card limit') ?></th>
<th class="d-none d-lg-table-cell">Fees</th>
<th class="d-none d-md-table-cell"><?= $sort_link('saved_cards', 'Saved cards') ?></th>
<th class="d-none d-md-table-cell"><?= $sort_link('last_paid', 'Last card payment') ?></th>
<th></th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysqli_fetch_assoc($sql)) {
<?php while ($row = mysqli_fetch_assoc($sql)) {
$provider_id = intval($row['payment_provider_id']);
$provider_name = escapeHtml($row['payment_provider_name']);
$provider_description = escapeHtml($row['payment_provider_description']);
$account_name = escapeHtml($row['account_name']);
$threshold = floatval($row['payment_provider_threshold']);
if (!$threshold) {
$threshold = "Not Enforced";
} else {
$threshold = numfmt_format_currency($currency_format, $threshold, $session_company_currency);
}
$vendor_name = escapeHtml($row['vendor_name'] ?? "Expense Disabled");
$category = escapeHtml($row['category_name']);
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('saved_payment_id') AS saved_payment_count FROM client_saved_payment_methods WHERE saved_payment_provider_id = $provider_id"));
$saved_payment_count = intval($row['saved_payment_count']);
$name = (string) $row['payment_provider_name'];
$kind = paymentProviderKinds()[$name] ?? null;
$on = intval($row['payment_provider_active']) === 1;
$mode = paymentProviderMode($row['payment_provider_private_key']);
$edit_url = "modals/payment_provider/payment_provider_edit.php?id=$provider_id";
$cards = intval($row['saved_cards']);
$autopay = intval($row['autopay']);
$fees_on = intval($row['payment_provider_expense_vendor']) > 0 && intval($row['payment_provider_expense_category']) > 0;
$ties = paymentProviderTiesText(paymentProviderTies($provider_id));
?>
<tr>
<tr data-payment-provider-id="<?= $provider_id ?>" class="<?= $on ? '' : 'text-body-secondary' ?>">
<td class="ps-3">
<a class="text-dark text-bold ajax-modal" href="#"
data-modal-url="modals/payment_provider/payment_provider_edit.php?id=<?= $provider_id ?>">
<?= $provider_name ?>
</a>
<span class="text-secondary"><?= $provider_description ?></span>
<div class="d-flex align-items-center gap-3">
<span class="d-none d-sm-inline-flex itflow-asset-icon itflow-asset-tone-other" aria-hidden="true"><i class="<?= escapeHtml($kind['icon'] ?? 'fas fa-credit-card') ?>"></i></span>
<div class="min-w-0">
<a class="fw-semibold text-body ajax-modal" href="#" data-modal-url="<?= $edit_url ?>"><?= escapeHtml($name) ?></a>
<?php if (!$on) { ?>
<span class="badge text-bg-secondary ms-1" data-provider-state="off" title="Clients can't pay by card through it, and autopay with its cards is skipped">Off</span>
<?php } ?>
<?php if ($mode === 'test') { ?>
<span class="badge bg-warning-subtle text-warning-emphasis border border-warning-subtle ms-1" data-provider-mode="test" title="Its keys are test keys - no real money moves">Test</span>
<?php } elseif ($mode === 'live') { ?>
<span class="badge bg-success-subtle text-success-emphasis border border-success-subtle ms-1" data-provider-mode="live">Live</span>
<?php } ?>
<?php if (trim((string) $row['payment_provider_description']) !== '') { ?>
<div class="small text-body-secondary"><?= escapeHtml($row['payment_provider_description']) ?></div>
<?php } ?>
<!-- On smaller screens where its payments go comes along under the name -->
<div class="d-md-none small text-body-secondary"><?= $row['account_name'] !== null ? 'Into ' . escapeHtml($row['account_name']) : '' ?></div>
</div>
</div>
</td>
<td><?= $account_name ?></td>
<td><?= $threshold ?></td>
<td><?= $vendor_name ?></td>
<td><?= $category ?></td>
<td class="text-center">
<a class="badge bg-dark rounded-pill p-2" href="saved_payment_methods.php"><?= $saved_payment_count ?></a>
<td class="d-none d-md-table-cell small">
<?php if ($row['account_name'] === null) { ?>
<span class="text-danger-emphasis"><i class="fas fa-fw fa-exclamation-triangle me-1"></i>No account - pick one in Edit</span>
<?php } else { ?>
<a class="text-reset" href="/agent/accounts.php"><?= escapeHtml($row['account_name']) ?></a>
<?php if ($row['account_archived_at']) { ?><div class="text-danger-emphasis"><i class="fas fa-fw fa-archive me-1"></i>Archived - pick another in Edit</div><?php } ?>
<?php } ?>
</td>
<td>
<div class="dropdown dropstart text-center">
<button class="btn btn-secondary btn-sm" title="More actions" type="button" data-bs-toggle="dropdown">
<i class="fas fa-ellipsis-h"></i>
</button>
<td class="d-none d-lg-table-cell small text-nowrap"><?= escapeHtml(paymentProviderLimitText($row['payment_provider_threshold'])) ?></td>
<td class="d-none d-lg-table-cell small" data-provider-fees="<?= $fees_on ? 'on' : 'off' ?>">
<?php if ($fees_on) { ?>
<div><i class="fas fa-fw fa-receipt text-secondary me-1"></i>Recorded</div>
<div class="text-body-secondary"><?= escapeHtml(trim($row['vendor_name'] . ' · ' . $row['category_name'], ' ·')) ?></div>
<?php } else { ?>
<span class="text-body-secondary">Not recorded</span>
<?php } ?>
</td>
<td class="d-none d-md-table-cell small text-nowrap">
<?php if ($cards) { ?>
<a class="text-reset" href="saved_payment_methods.php"><?= $cards ?> card<?= $cards === 1 ? '' : 's' ?></a>
<?php if ($autopay) { ?><div class="text-body-secondary">Autopay on <?= $autopay ?></div><?php } ?>
<?php } else { ?>
<span class="text-body-secondary">None yet</span>
<?php } ?>
</td>
<td class="d-none d-md-table-cell small text-body-secondary text-nowrap"<?= $row['last_paid'] ? ' title="' . escapeHtml($row['last_paid']) . '"' : '' ?>><?= $row['last_paid'] ? escapeHtml(date('M j, Y', strtotime($row['last_paid']))) : 'None yet' ?></td>
<td class="text-end pe-3">
<div class="dropdown dropstart">
<button class="btn btn-sm btn-light" title="More actions" type="button" data-bs-toggle="dropdown"><i class="fas fa-fw fa-ellipsis-v"></i></button>
<div class="dropdown-menu">
<a class="dropdown-item ajax-modal" href="#"
data-modal-url="modals/payment_provider/payment_provider_edit.php?id=<?= $provider_id ?>">
<i class="fas fa-fw fa-edit me-2"></i>Edit
<a class="dropdown-item ajax-modal" href="#" data-modal-url="<?= $edit_url ?>">
<i class="fas fa-fw fa-edit text-secondary me-2"></i>Edit
</a>
<?php if ($on) { ?>
<a class="dropdown-item confirm-link" href="post.php?turn_payment_provider_off=<?= $provider_id ?>&csrf_token=<?= $csrf ?>"
data-confirm-title="Turn <?= escapeHtml($name) ?> off?" data-confirm-text="Clients won't be able to pay by card, and autopay with its saved cards is skipped until it is on again. Its cards are kept." data-confirm-button="Turn off">
<i class="fas fa-fw fa-toggle-off text-secondary me-2"></i>Turn off
</a>
<?php } else { ?>
<a class="dropdown-item" href="post.php?turn_payment_provider_on=<?= $provider_id ?>&csrf_token=<?= $csrf ?>">
<i class="fas fa-fw fa-toggle-on text-secondary me-2"></i>Turn on
</a>
<?php } ?>
<div class="dropdown-divider"></div>
<a class="dropdown-item text-danger confirm-link" href="post.php?delete_payment_provider=<?= $provider_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>">
<i class="fas fa-fw fa-trash me-2"></i><strong>Delete Provider and</strong>
<ul class="text-xs">
<li>Related Recurring Payments</li>
<li>Related Saved cards</li>
<li>Client Provider Relations</li>
</ul>
<a class="dropdown-item text-danger confirm-link" href="post.php?delete_payment_provider=<?= $provider_id ?>&csrf_token=<?= $csrf ?>"
data-confirm-title="Delete <?= escapeHtml($name) ?>?" data-confirm-button="Delete"
data-confirm-text="<?= escapeHtml($ties !== '' ? "Its $ties go with it. To stop card payments and keep them, turn it off instead." : 'Clients will no longer be able to pay by card.') ?>">
<i class="fas fa-fw fa-trash me-2"></i>Delete
</a>
</div>
</div>
</td>
</tr>
<?php
}
?>
<?php } ?>
</tbody>
</table>
</div>
@@ -147,8 +194,8 @@ $num_rows = mysqli_fetch_row(mysqli_query($mysqli, "SELECT FOUND_ROWS()"));
$empty_state = [
'thing' => 'payment providers',
'icon' => 'fa-credit-card',
'text' => 'Take card payments online when clients pay an invoice.',
'actions' => [['label' => 'Add Provider', 'modal' => 'modals/payment_provider/payment_provider_add.php']],
'text' => 'Set up Stripe and clients can pay their invoices by card, save a card, and pay recurring invoices by autopay.',
'actions' => $can_add ? [['label' => 'Add Provider', 'modal' => $add_url]] : [],
];
?>
<?php require_once "../includes/filter_footer.php"; ?>

View File

@@ -1,99 +1,141 @@
<?php
/*
* ITFlow - GET/POST request handler for payment Providers ('payment_providers')
* ITFlow - Admin > Payment Providers (admin/payment_providers.php): adding
* one, changing it, turning it off and on, and deleting it.
*
* Saving checks what was sent (paymentProviderCheck(),
* functions/payment_provider.php) and, when the keys are new or changed, asks
* the provider whether it takes them - nothing is saved until both are right.
* The Add and Edit window asks first (check_payment_provider, which answers
* in JSON) and says what is wrong beside each field, so nothing typed is
* lost; a key the window has just had taken isn't asked about twice. What
* changed is in the audit log, from what to what - the keys only as changed.
*/
defined('FROM_POST_HANDLER') || die("Direct file access is not allowed");
if (isset($_POST['add_payment_provider'])) {
if (isset($_POST['check_payment_provider']) || isset($_POST['add_payment_provider']) || isset($_POST['edit_payment_provider'])) {
validateCSRFToken();
$provider = escapeSql($_POST['provider']);
require_once 'payment_provider_model.php';
$checking = isset($_POST['check_payment_provider']);
$provider_id = intval($_POST['provider_id'] ?? 0);
$before = $provider_id ? paymentProviderRow($provider_id) : null;
// Check to ensure provider isn't added twice
$sql = mysqli_query($mysqli, "SELECT 1 FROM payment_providers WHERE payment_provider_name = '$provider' LIMIT 1");
if (mysqli_num_rows($sql) > 0) {
flashAlert("Payment Provider <strong>$provider</strong> already exists", 'error');
if ($provider_id && !$before) {
if ($checking) {
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['ok' => false, 'errors' => ['provider' => 'That payment provider no longer exists - close this and look again.'], 'account' => []]);
exit;
}
flashAlert('That payment provider no longer exists.', 'error');
redirect('payment_providers.php');
}
[$after, $errors] = paymentProviderCheck($_POST, $before);
// New or changed keys - does the provider take them? Once taken, not asked again for ten minutes
$account = [];
if (!array_intersect_key($errors, ['provider' => 1, 'public_key' => 1, 'private_key' => 1]) && paymentProviderKeysChanged($after, $before)) {
$asked_key = hash('sha256', $after['payment_provider_name'] . '|' . $after['payment_provider_private_key']);
$asked_at = $_SESSION['payment_provider_asked'][$asked_key] ?? 0;
if ($checking || time() - $asked_at > 600) {
$asked = paymentProviderAsk($after['payment_provider_name'], $after['payment_provider_private_key']);
if ($asked['ok']) {
$_SESSION['payment_provider_asked'] = [$asked_key => time()];
$account = $asked['account'];
} else {
$errors['private_key'] = $asked['error'];
}
}
}
if ($checking) {
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['ok' => !$errors, 'errors' => $errors, 'account' => $account]);
exit;
}
// Only reached without the window's script - say the first thing wrong
if ($errors) {
flashAlert('Not saved - ' . escapeHtml(reset($errors)), 'error');
redirect();
}
mysqli_query($mysqli,"INSERT INTO payment_providers SET payment_provider_name = '$provider', payment_provider_public_key = '$public_key', payment_provider_private_key = '$private_key', payment_provider_threshold = $threshold, payment_provider_account = $account, payment_provider_expense_vendor = $expense_vendor, payment_provider_expense_category = $expense_category");
$name = $after['payment_provider_name'];
$mode = paymentProviderMode($after['payment_provider_private_key']);
$provider_id = mysqli_insert_id($mysqli);
logAudit("Payment Provider", "Create", "$session_name created Payment Provider $provider");
// Check Stripe sk
if ($provider === 'Stripe') {
try {
require_once '../includes/stripe_init.php';
$stripe = new \Stripe\StripeClient($private_key);
$account = $stripe->accounts->retrieve();
} catch (Exception $e) {
flashAlert("Error checking Stripe key: " . $e->getMessage(), 'error');
redirect();
}
if (!$before) {
$provider_id = paymentProviderWrite($after);
$account_name = (string) (paymentProviderRow($provider_id)['account_name'] ?? '');
logAudit("Payment Provider", "Create", "$session_name added payment provider " . escapeSql("$name ($mode mode), payments into $account_name, card limit " . paymentProviderLimitText($after['payment_provider_threshold'])
. ', fees ' . ($after['payment_provider_expense_vendor'] ? 'recorded' : 'not recorded')), 0, $provider_id);
flashAlert('<strong>' . escapeHtml($name) . '</strong> added - clients can pay invoices by card' . ($mode === 'test' ? '. Its keys are test keys, so no real money moves until they are live ones' : ''));
redirect();
}
flashAlert("Payment provider <strong>$provider</strong> created");
$lines = paymentProviderChangeLines($before, $after);
if (!$lines) {
flashAlert('Nothing changed on <strong>' . escapeHtml($name) . '</strong>', 'info');
redirect();
}
paymentProviderWrite($after, $provider_id);
logAudit("Payment Provider", "Edit", "$session_name changed payment provider " . escapeSql("$name: " . implode('; ', $lines)), 0, $provider_id);
flashAlert('<strong>' . escapeHtml($name) . '</strong> saved - ' . escapeHtml(count($lines) === 1 ? $lines[0] : count($lines) . ' changes'));
redirect();
}
if (isset($_POST['edit_payment_provider'])) {
// Turn a provider off - clients can't pay through it, and autopay with its cards is skipped - or on again
if (isset($_GET['turn_payment_provider_off']) || isset($_GET['turn_payment_provider_on'])) {
validateCSRFToken();
require_once 'payment_provider_model.php';
$provider_id = intval($_POST['provider_id']);
mysqli_query($mysqli,"UPDATE payment_providers SET payment_provider_public_key = '$public_key', payment_provider_private_key = '$private_key', payment_provider_threshold = $threshold, payment_provider_account = $account, payment_provider_expense_vendor = $expense_vendor, payment_provider_expense_category = $expense_category WHERE payment_provider_id = $provider_id");
logAudit("Payment Provider", "Edit", "$session_name edited Payment Provider $provider");
// Check Stripe sk
if ($_POST['provider'] === 'Stripe') {
try {
require_once '../includes/stripe_init.php';
$stripe = new \Stripe\StripeClient($private_key);
$account = $stripe->accounts->retrieve();
} catch (Exception $e) {
flashAlert("Error checking Stripe key: " . $e->getMessage(), 'error');
redirect();
}
$on = isset($_GET['turn_payment_provider_on']);
$row = paymentProviderRow($on ? $_GET['turn_payment_provider_on'] : $_GET['turn_payment_provider_off']);
if (!$row) {
flashAlert('That payment provider no longer exists.', 'error');
redirect('payment_providers.php');
}
$name = $row['payment_provider_name'];
if (intval($row['payment_provider_active']) === ($on ? 1 : 0)) {
flashAlert('<strong>' . escapeHtml($name) . '</strong> is ' . ($on ? 'on' : 'off') . ' already', 'info');
redirect();
}
if ($on && (!$row['account_name'] || $row['account_archived_at'])) {
flashAlert('Its payments would go into an account that is ' . ($row['account_name'] ? 'archived' : 'gone') . ' - pick another in Edit, then turn it on', 'error');
redirect();
}
flashAlert("Payment Provider <strong>$provider</strong> edited");
mysqli_query($mysqli, "UPDATE payment_providers SET payment_provider_active = " . ($on ? 1 : 0) . " WHERE payment_provider_id = " . intval($row['payment_provider_id']));
logAudit("Payment Provider", "Edit", "$session_name turned payment provider " . escapeSql($name) . ($on ? ' on' : ' off'), 0, intval($row['payment_provider_id']));
flashAlert($on
? '<strong>' . escapeHtml($name) . '</strong> turned on - clients can pay by card again'
: '<strong>' . escapeHtml($name) . '</strong> turned off - clients can\'t pay by card, and autopay with its cards is skipped until it is on again');
redirect();
}
// Delete a provider - its saved cards, the autopay on them and its links to clients go with it
if (isset($_GET['delete_payment_provider'])) {
validateCSRFToken();
$provider_id = intval($_GET['delete_payment_provider']);
$row = paymentProviderRow($_GET['delete_payment_provider']);
if (!$row) {
flashAlert('That payment provider no longer exists.', 'error');
redirect('payment_providers.php');
}
$provider_id = intval($row['payment_provider_id']);
$name = $row['payment_provider_name'];
$ties = paymentProviderTiesText(paymentProviderTies($provider_id));
// When deleted it cascades deletes
// all Recurring payments related to payment provider
// Delete all Saved Cards related
// Delete Client Payment Provider Releation
// The cards, autopay and client links cascade with it
mysqli_query($mysqli, "DELETE FROM payment_providers WHERE payment_provider_id = $provider_id");
$provider_name = escapeSql(getFieldById('payment_providers', $provider_id, 'payment_provider_name'));
// Delete provider
mysqli_query($mysqli,"DELETE FROM payment_providers WHERE payment_provider_id = $provider_id");
logAudit("Payment Provider", "Delete", "$session_name deleted Payment Provider $provider_name");
flashAlert("Payment Provider <strong>$provider_name</strong> deleted", 'error');
redirect();
logAudit("Payment Provider", "Delete", "$session_name deleted payment provider " . escapeSql($name . ($ties !== '' ? " - and with it $ties" : '')), 0, $provider_id);
flashAlert('<strong>' . escapeHtml($name) . '</strong> deleted' . ($ties !== '' ? ', with ' . escapeHtml($ties) : ''), 'error');
redirect('payment_providers.php');
}

View File

@@ -1,9 +0,0 @@
<?php
defined('FROM_POST_HANDLER') || die("Direct file access is not allowed");
$public_key = escapeSql($_POST['public_key']);
$private_key = escapeSql($_POST['private_key']);
$threshold = floatval($_POST['threshold']);
$account = intval($_POST['account']);
$expense_vendor = intval($_POST['expense_vendor']) ?? 0;
$expense_category = intval($_POST['expense_category']) ?? 0;

View File

@@ -73,6 +73,7 @@ require_once __DIR__ . '/functions/billing.php';
require_once __DIR__ . '/functions/products.php';
require_once __DIR__ . '/functions/billing_email.php';
require_once __DIR__ . '/functions/billing_pay.php';
require_once __DIR__ . '/functions/payment_provider.php';
require_once __DIR__ . '/functions/tax.php';
require_once __DIR__ . '/functions/expenses.php';
require_once __DIR__ . '/functions/expense_import.php';

View File

@@ -289,7 +289,7 @@ function accountArchive($account_id, &$error = '') {
return null;
}
if (mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM payment_providers WHERE payment_provider_active = 1 AND payment_provider_account = " . intval($row['account_id'])))) {
$error = 'Online payments go into ' . $row['account_name'] . ' - pick another account for them in Admin > Settings > Online Payment first';
$error = 'Online payments go into ' . $row['account_name'] . ' - pick another account for them in Admin > Payment Providers first';
return null;
}
mysqli_query($mysqli, "UPDATE accounts SET account_archived_at = NOW() WHERE account_id = " . intval($row['account_id']));

View File

@@ -0,0 +1,291 @@
<?php
/*
* ITFlow - Payment providers (Admin > Payment Providers)
*
* The services clients pay invoices by card through - Stripe, for now. Each
* has its keys (live or test, as the keys say), whether it is on, the account
* its payments go into, the invoices it is too small for (the card limit), and
* whether its fees are recorded as expenses - each night, by
* cron/nightly_tasks.php. Paying through one is functions/billing_pay.php.
*
* A provider is saved only once it is right: its keys look like that
* provider's, come from the same mode, and - when they are new or changed -
* the provider takes the secret one. The Add and Edit window asks first
* (check_payment_provider), so what is wrong is said beside it while the
* window stays open.
*/
/* The providers ITFlow can take payments through - by name, what their keys look like and where they are. */
function paymentProviderKinds() {
return [
'Stripe' => [
'icon' => 'fab fa-stripe-s',
'public' => '/^pk_(live|test)_[A-Za-z0-9]{8,}$/',
'secret' => '/^(sk|rk)_(live|test)_[A-Za-z0-9]{8,}$/',
'public_example' => 'pk_live_...',
'secret_example' => 'sk_live_...',
'keys_url' => 'https://dashboard.stripe.com/apikeys',
],
];
}
/* Live or test, as a key says - '' when it says neither. */
function paymentProviderMode($key) {
return preg_match('/^[a-z]{2}_(live|test)_/', (string) $key, $m) ? $m[1] : '';
}
/* One provider's row, with its account, vendor and category names - null when there is none. */
function paymentProviderRow($provider_id) {
global $mysqli;
$provider_id = intval($provider_id);
return mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT payment_providers.*, account_name, account_archived_at, vendor_name, category_name
FROM payment_providers
LEFT JOIN accounts ON account_id = payment_provider_account
LEFT JOIN vendors ON vendor_id = payment_provider_expense_vendor AND payment_provider_expense_vendor > 0
LEFT JOIN categories ON category_id = payment_provider_expense_category AND payment_provider_expense_category > 0
WHERE payment_provider_id = $provider_id LIMIT 1")) ?: null;
}
/* What goes with a provider when it is deleted - its saved cards, the recurring invoices that autopay with them, and the clients it knows. */
function paymentProviderTies($provider_id) {
global $mysqli;
$provider_id = intval($provider_id);
$row = mysqli_fetch_row(mysqli_query($mysqli, "SELECT
(SELECT COUNT(*) FROM client_saved_payment_methods WHERE saved_payment_provider_id = $provider_id),
(SELECT COUNT(*) FROM recurring_payments JOIN client_saved_payment_methods ON saved_payment_id = recurring_payment_saved_payment_id WHERE saved_payment_provider_id = $provider_id),
(SELECT COUNT(*) FROM client_payment_provider WHERE payment_provider_id = $provider_id)"));
return ['cards' => intval($row[0]), 'autopay' => intval($row[1]), 'clients' => intval($row[2])];
}
/* "3 saved cards, autopay on 2 recurring invoices" - what paymentProviderTies() counted, in words ('' when nothing). */
function paymentProviderTiesText(array $ties) {
$parts = [];
if ($ties['cards']) {
$parts[] = $ties['cards'] . ' saved card' . ($ties['cards'] === 1 ? '' : 's');
}
if ($ties['autopay']) {
$parts[] = 'autopay on ' . $ties['autopay'] . ' recurring invoice' . ($ties['autopay'] === 1 ? '' : 's');
}
if ($ties['clients']) {
$parts[] = 'the link to ' . $ties['clients'] . ' client' . ($ties['clients'] === 1 ? '' : 's') . ' as its customers';
}
if (count($parts) > 1) {
$last = array_pop($parts);
return implode(', ', $parts) . ' and ' . $last;
}
return $parts[0] ?? '';
}
/* A card limit as it reads - "Under $1,000.00", or "No limit". */
function paymentProviderLimitText($threshold) {
$threshold = round(floatval($threshold), 2);
return $threshold > 0 ? 'Under ' . billingMoney($threshold) : 'No limit';
}
/*
* What a provider's form sent, checked against what is saved ($before, null
* for a new one) - [the columns to save, errors by field]. Keys: one that
* isn't that provider's shape, or one live and one test, is wrong; a secret
* left empty stays as saved. Fees are recorded with a vendor and a category,
* or not at all.
*/
function paymentProviderCheck(array $post, $before = null) {
global $mysqli;
$errors = [];
$kinds = paymentProviderKinds();
$name = $before ? (string) $before['payment_provider_name'] : trim((string) ($post['provider'] ?? ''));
$kind = $kinds[$name] ?? null;
if (!$before) {
if (!$kind) {
$errors['provider'] = 'Pick one of these.';
} elseif (mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM payment_providers WHERE payment_provider_name = '" . escapeSql($name) . "' LIMIT 1"))) {
$errors['provider'] = "$name is set up already - edit it instead.";
}
}
$description = trim(preg_replace('/\s+/u', ' ', (string) ($post['description'] ?? '')));
if (mb_strlen($description) > 250) {
$errors['description'] = 'Up to 250 characters.';
}
// The keys - the secret one left empty stays as saved
$public_key = trim((string) ($post['public_key'] ?? ''));
$secret_typed = trim((string) ($post['private_key'] ?? ''));
$secret_key = $secret_typed !== '' ? $secret_typed : (string) ($before['payment_provider_private_key'] ?? '');
if ($kind) {
if ($public_key === '') {
$errors['public_key'] = "The publishable key - it starts {$kind['public_example']}";
} elseif (mb_strlen($public_key) > 250 || !preg_match($kind['public'], $public_key)) {
$errors['public_key'] = "That isn't a publishable key - it starts {$kind['public_example']}";
}
if ($secret_key === '') {
$errors['private_key'] = "The secret key - it starts {$kind['secret_example']}";
} elseif ($secret_typed !== '' && (mb_strlen($secret_typed) > 250 || !preg_match($kind['secret'], $secret_typed))) {
$errors['private_key'] = "That isn't a secret key - it starts {$kind['secret_example']}, or rk_ for a restricted key.";
}
if (!isset($errors['public_key']) && !isset($errors['private_key']) && paymentProviderMode($secret_key) === '') {
$errors['private_key'] = "The saved secret key doesn't say whether it is live or test - type it in again.";
} elseif (!isset($errors['public_key']) && !isset($errors['private_key']) && paymentProviderMode($public_key) !== paymentProviderMode($secret_key)) {
$errors['private_key'] = 'One key is a ' . paymentProviderMode($public_key) . ' key and the other a ' . paymentProviderMode($secret_key) . ' one - both have to be live, or both test.';
}
}
// Where payments go - an open account, or the one it is set to
$account_id = intval($post['account'] ?? 0);
$account = $account_id ? mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT account_id, account_archived_at FROM accounts WHERE account_id = $account_id LIMIT 1")) : null;
if (!$account || ($account['account_archived_at'] && $account_id !== intval($before['payment_provider_account'] ?? 0))) {
$errors['account'] = 'Pick the account its payments go into.';
}
// The card limit - empty, or 0, for none
$threshold_text = str_replace([',', ' '], '', trim((string) ($post['threshold'] ?? '')));
$threshold = 0.0;
if ($threshold_text !== '') {
if (!preg_match('/^\d{1,13}(\.\d{1,2})?$/', $threshold_text)) {
$errors['threshold'] = 'A sum of money, as 1000 or 1000.50 - or empty for no limit.';
} else {
$threshold = round(floatval($threshold_text), 2);
}
}
// Its fees - recorded under a vendor of yours and an expense category, or not at all
$vendor_id = 0;
$category_id = 0;
if (!empty($post['record_fees'])) {
$vendor_id = intval($post['expense_vendor'] ?? 0);
$category_id = intval($post['expense_category'] ?? 0);
$vendor = $vendor_id ? mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT vendor_id, vendor_archived_at FROM vendors WHERE vendor_id = $vendor_id AND vendor_client_id = 0 LIMIT 1")) : null;
if (!$vendor || ($vendor['vendor_archived_at'] && $vendor_id !== intval($before['payment_provider_expense_vendor'] ?? 0))) {
$errors['expense_vendor'] = 'Pick the vendor its fees are paid to - one of your own, as ' . ($name !== '' ? $name : 'Stripe') . '.';
}
$category = $category_id ? mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT category_id, category_archived_at FROM categories WHERE category_id = $category_id AND category_type = 'Expense' LIMIT 1")) : null;
if (!$category || ($category['category_archived_at'] && $category_id !== intval($before['payment_provider_expense_category'] ?? 0))) {
$errors['expense_category'] = 'Pick the expense category they go under, as Processing Fee.';
}
}
$after = [
'payment_provider_name' => $name,
'payment_provider_description' => $description,
'payment_provider_public_key' => $public_key,
'payment_provider_private_key' => $secret_key,
'payment_provider_threshold' => $threshold,
'payment_provider_active' => $before ? (!empty($post['active']) ? 1 : 0) : 1,
'payment_provider_account' => $account_id,
'payment_provider_expense_vendor' => $vendor_id,
'payment_provider_expense_category' => $category_id,
];
return [$after, $errors];
}
/* Whether the keys are new or changed - only then is the provider asked about them. */
function paymentProviderKeysChanged(array $after, $before = null) {
return !$before || $after['payment_provider_public_key'] !== (string) $before['payment_provider_public_key']
|| $after['payment_provider_private_key'] !== (string) $before['payment_provider_private_key'];
}
/*
* Ask the provider whether it takes the secret key - ['ok' => bool, 'error'
* => what is wrong, for the secret key field, 'account' => its name, email
* and country, as it gives them].
*/
function paymentProviderAsk($name, $secret_key) {
if ($name !== 'Stripe') {
return ['ok' => true, 'error' => '', 'account' => []];
}
require_once __DIR__ . '/../includes/stripe_init.php';
try {
$stripe = new \Stripe\StripeClient((string) $secret_key);
$account = $stripe->accounts->retrieve();
} catch (\Stripe\Exception\AuthenticationException $e) {
return ['ok' => false, 'error' => 'Stripe doesn\'t know that secret key - copy it again from Developers > API keys.', 'account' => []];
} catch (\Stripe\Exception\PermissionException $e) {
return ['ok' => false, 'error' => 'That restricted key can\'t read the account - give it Read on Account, or use the secret key.', 'account' => []];
} catch (\Stripe\Exception\ApiConnectionException $e) {
return ['ok' => false, 'error' => 'Stripe couldn\'t be reached to check the key - ' . $e->getMessage(), 'account' => []];
} catch (\Throwable $e) {
return ['ok' => false, 'error' => 'Stripe turned the key away - ' . $e->getMessage(), 'account' => []];
}
$display = (string) ($account->settings->dashboard->display_name ?? '');
if ($display === '') {
$display = (string) ($account->business_profile->name ?? '');
}
return ['ok' => true, 'error' => '', 'account' => [
'name' => $display,
'email' => (string) ($account->email ?? ''),
'country' => (string) ($account->country ?? ''),
'id' => (string) ($account->id ?? ''),
]];
}
/* What changed on a provider, a line each - "Card limit Under $1,000.00 -> No limit", "Secret key changed", "Turned off". */
function paymentProviderChangeLines(array $before, array $after) {
global $mysqli;
$name_of = function ($table, $id) use ($mysqli) {
$id = intval($id);
if (!$id) {
return 'none';
}
$column = ['accounts' => ['account_name', 'account_id'], 'vendors' => ['vendor_name', 'vendor_id'], 'categories' => ['category_name', 'category_id']][$table];
$row = mysqli_fetch_row(mysqli_query($mysqli, "SELECT {$column[0]} FROM $table WHERE {$column[1]} = $id"));
return $row ? $row[0] : "#$id";
};
$lines = [];
if ((string) $before['payment_provider_description'] !== $after['payment_provider_description']) {
$lines[] = 'Description ' . ((string) $before['payment_provider_description'] !== '' ? $before['payment_provider_description'] : 'blank') . ' → ' . ($after['payment_provider_description'] !== '' ? $after['payment_provider_description'] : 'blank');
}
$was_mode = paymentProviderMode($before['payment_provider_private_key']);
$now_mode = paymentProviderMode($after['payment_provider_private_key']);
if ($was_mode !== $now_mode) {
$lines[] = "Mode $was_mode → $now_mode";
}
if ((string) $before['payment_provider_public_key'] !== $after['payment_provider_public_key']) {
$lines[] = 'Publishable key changed';
}
if ((string) $before['payment_provider_private_key'] !== $after['payment_provider_private_key']) {
$lines[] = 'Secret key changed';
}
if (intval($before['payment_provider_account']) !== $after['payment_provider_account']) {
$lines[] = 'Payments go into ' . $name_of('accounts', $before['payment_provider_account']) . ' → ' . $name_of('accounts', $after['payment_provider_account']);
}
if (round(floatval($before['payment_provider_threshold']), 2) !== round($after['payment_provider_threshold'], 2)) {
$lines[] = 'Card limit ' . paymentProviderLimitText($before['payment_provider_threshold']) . ' → ' . paymentProviderLimitText($after['payment_provider_threshold']);
}
$fees = function ($vendor_id, $category_id) use ($name_of) {
return intval($vendor_id) && intval($category_id) ? $name_of('vendors', $vendor_id) . ', ' . $name_of('categories', $category_id) : 'not recorded';
};
$fees_before = $fees($before['payment_provider_expense_vendor'], $before['payment_provider_expense_category']);
$fees_after = $fees($after['payment_provider_expense_vendor'], $after['payment_provider_expense_category']);
if ($fees_before !== $fees_after) {
$lines[] = "Fees $fees_before → $fees_after";
}
if (intval($before['payment_provider_active']) !== $after['payment_provider_active']) {
$lines[] = $after['payment_provider_active'] ? 'Turned on' : 'Turned off';
}
return $lines;
}
/* Save a provider's columns - new ($provider_id 0) or changed. Its id. */
function paymentProviderWrite(array $after, $provider_id = 0) {
global $mysqli;
$sets = [];
foreach ($after as $column => $value) {
$column_sql = '`' . preg_replace('/[^a-z_]/', '', $column) . '`';
if (is_int($value)) {
$sets[] = "$column_sql = $value";
} elseif (is_float($value)) {
$sets[] = "$column_sql = " . sprintf('%.2F', $value);
} else {
// Keys exactly as given - escapeSql() would trim them and take out anything like a tag
$sets[] = "$column_sql = '" . mysqli_real_escape_string($mysqli, (string) $value) . "'";
}
}
$provider_id = intval($provider_id);
if ($provider_id) {
mysqli_query($mysqli, "UPDATE payment_providers SET " . implode(', ', $sets) . " WHERE payment_provider_id = $provider_id");
return $provider_id;
}
mysqli_query($mysqli, "INSERT INTO payment_providers SET " . implode(', ', $sets));
return intval(mysqli_insert_id($mysqli));
}