From e22675f54b9ff1e1016499bc7b84e63b64d59c7f Mon Sep 17 00:00:00 2001 From: Josh Knapp Date: Sun, 15 Nov 2026 10:41:29 -0800 Subject: [PATCH] Donate form: custom-amount label, visible minimum, fee-cover info icon; hard 1.00 floor; purge abandoned checkouts; drop refund filters; soften personal-account wording Co-Authored-By: Claude Sonnet 5.5 --- assets/donate/donate.css | 6 +++ assets/donate/donate.js | 33 +++++++++++--- includes/Admin/DonationsPage.php | 2 +- includes/Admin/PayPalConnector.php | 2 +- includes/Admin/SettingsPage.php | 6 +-- includes/Admin/Store.php | 2 +- includes/Core/Maintenance.php | 41 +++++++++++++++++ includes/Core/Plugin.php | 1 + includes/Core/Settings.php | 11 +++++ includes/PayPal/OrderValidator.php | 4 +- includes/Rest/DonateController.php | 10 +++- streamgoals-donate.php | 1 + tests/Unit/MinimumDonationTest.php | 73 ++++++++++++++++++++++++++++++ 13 files changed, 177 insertions(+), 15 deletions(-) create mode 100644 includes/Core/Maintenance.php create mode 100644 tests/Unit/MinimumDonationTest.php diff --git a/assets/donate/donate.css b/assets/donate/donate.css index 5fecac2..2dfe6d8 100644 --- a/assets/donate/donate.css +++ b/assets/donate/donate.css @@ -11,3 +11,9 @@ .sg-donate .sg-msg.sg-error{color:#b32d2e} .sg-donate .sg-msg.sg-ok{color:#1a7f37} .sg-donate .sg-buttons[data-disabled=true]{opacity:.45;pointer-events:none} +.sg-donate label.sg-sub{font-weight:400;margin:.2rem 0 .25rem} +.sg-donate .sg-hint{font-size:.85em;opacity:.75;margin-top:.25rem} +.sg-donate .sg-cover{display:flex;align-items:center;gap:.5rem} +.sg-donate .sg-info{flex:none;width:1.4rem;height:1.4rem;padding:0;border-radius:50%;border:1.5px solid currentColor;background:transparent;color:inherit;font:italic 700 .85rem/1 Georgia,serif;cursor:pointer;display:inline-flex;align-items:center;justify-content:center} +.sg-donate .sg-info:focus-visible{outline:2px solid currentColor;outline-offset:2px} +.sg-donate .sg-tip{margin-top:.4rem;padding:.6rem .75rem;border:1px solid rgba(128,128,128,.5);border-radius:.4rem;font-size:.9em;line-height:1.4} diff --git a/assets/donate/donate.js b/assets/donate/donate.js index 32b2a41..84d9768 100644 --- a/assets/donate/donate.js +++ b/assets/donate/donate.js @@ -54,10 +54,12 @@ try { return new Intl.NumberFormat(undefined, { style: 'currency', currency: cur }).format(v); } catch (e) { return v.toFixed(exp) + ' ' + cur; } } + // Preset buttons, minus any below the minimum donation (values are whole currency units, or minor units for zero-decimal). function presets(exp) { var base = exp === 0 ? [500, 1000, 2500, 5000] : [5, 10, 25, 50]; - return base; + return base.filter(function (p) { return (exp === 0 ? p : p * 100) >= (C.minMinor || 0); }); } + function sprintf1(tpl, v) { return String(tpl || '%s').replace('%s', v); } function init(root) { var pinned = parseInt(root.getAttribute('data-goal'), 10) || 0; @@ -68,7 +70,8 @@ var goalSel = el('select', { id: uid + '-goal' }); goals.forEach(function (g) { goalSel.appendChild(el('option', { value: g.id, text: g.title + ' (' + g.currency + ')' })); }); - var amount = el('input', { type: 'text', inputmode: 'decimal', id: uid + '-amt', autocomplete: 'off', 'aria-describedby': uid + '-total' }); + var amount = el('input', { type: 'text', inputmode: 'decimal', id: uid + '-amt', autocomplete: 'off', placeholder: T.customPlaceholder || 'Other amount', 'aria-describedby': uid + '-hint ' + uid + '-total' }); + var hint = el('div', { 'class': 'sg-hint', id: uid + '-hint' }); var presetBox = el('div', { 'class': 'sg-presets' }); var name = el('input', { type: 'text', id: uid + '-name', maxlength: '100', autocomplete: 'nickname' }); var anon = el('input', { type: 'checkbox', id: uid + '-anon' }); @@ -79,7 +82,7 @@ var buttons = el('div', { 'class': 'sg-buttons' }); if (goals.length > 1) { root.appendChild(row([el('label', { 'for': uid + '-goal', text: T.goal }), goalSel])); } - root.appendChild(row([el('label', { 'for': uid + '-amt', text: T.amount }), presetBox, amount])); + root.appendChild(row([el('label', { text: T.amount }), presetBox, el('label', { 'class': 'sg-sub', 'for': uid + '-amt', text: T.customAmount || 'Or enter your own amount' }), amount, hint])); var nameRow = row([el('label', { 'for': uid + '-name', text: T.name }), name]); var anonRow = row([el('label', { 'class': 'sg-inline', 'for': uid + '-anon' }, [anon, document.createTextNode(T.anonymous)])]); if (C.policy === 'force_anonymous') { anon.checked = true; anon.disabled = true; nameRow.hidden = true; } @@ -87,7 +90,20 @@ root.appendChild(nameRow); root.appendChild(anonRow); root.appendChild(row([el('label', { 'for': uid + '-msg', text: T.message }), msg])); - root.appendChild(row([el('label', { 'class': 'sg-inline', 'for': uid + '-cover' }, [cover, document.createTextNode(T.coverFees)])])); + var tip = el('div', { 'class': 'sg-tip', id: uid + '-tip', role: 'note', text: T.coverInfo || '' }); + tip.hidden = true; + var info = el('button', { type: 'button', 'class': 'sg-info', 'aria-label': T.coverInfoLabel || 'What does this mean?', 'aria-expanded': 'false', 'aria-controls': uid + '-tip', text: 'i' }); + var pinnedOpen = false; + function showTip(open) { tip.hidden = !open; info.setAttribute('aria-expanded', String(open)); } + info.addEventListener('click', function () { pinnedOpen = tip.hidden; showTip(pinnedOpen); }); + info.addEventListener('mouseenter', function () { showTip(true); }); + info.addEventListener('mouseleave', function () { if (!pinnedOpen) { showTip(false); } }); + info.addEventListener('blur', function () { pinnedOpen = false; showTip(false); }); + info.addEventListener('keydown', function (e) { if (e.key === 'Escape') { pinnedOpen = false; showTip(false); } }); + root.appendChild(row([ + el('div', { 'class': 'sg-cover' }, [el('label', { 'class': 'sg-inline', 'for': uid + '-cover' }, [cover, document.createTextNode(T.coverFees)]), info]), + tip + ])); root.appendChild(row([total])); root.appendChild(buttons); root.appendChild(status); @@ -99,6 +115,7 @@ function buildPresets() { presetBox.textContent = ''; + hint.textContent = sprintf1(T.minHint, fmt(C.minMinor || 0, state.goal.exp, state.goal.currency)); presets(state.goal.exp).forEach(function (p) { var b = el('button', { type: 'button', 'aria-pressed': 'false', text: fmt(state.goal.exp === 0 ? p : p * 100, state.goal.exp, state.goal.currency) }); b.addEventListener('click', function () { amount.value = String(p); refresh(); }); @@ -119,7 +136,11 @@ state.quote = null; buttons.setAttribute('data-disabled', 'true'); clearTimeout(timer); - if (!amountStr()) { total.textContent = ''; return; } + if (!amountStr()) { total.textContent = ''; say(''); return; } + var typed = parseFloat(amountStr()); + if (isFinite(typed) && Math.round(typed * Math.pow(10, state.goal.exp)) < (C.minMinor || 0)) { + total.textContent = ''; say(sprintf1(T.belowMin, fmt(C.minMinor, state.goal.exp, state.goal.currency)), 'sg-error'); return; + } var mine = ++seq; timer = setTimeout(function () { var qs = 'goal_id=' + state.goal.id + '&amount=' + encodeURIComponent(amountStr()) + '&cover_fees=' + (cover.checked ? '1' : '0'); @@ -149,7 +170,7 @@ if (token !== state.renderToken) { return; } paypal.Buttons({ onClick: function (d, actions) { - if (!state.quote || (C.policy === 'require_name' && !name.value.trim())) { say(T.fixForm, 'sg-error'); return actions.reject(); } + if (!state.quote || (C.policy === 'require_name' && !name.value.trim())) { if (!status.textContent) { say(T.fixForm, 'sg-error'); } return actions.reject(); } say(''); }, createOrder: function () { diff --git a/includes/Admin/DonationsPage.php b/includes/Admin/DonationsPage.php index 9efd1b1..3123ece 100644 --- a/includes/Admin/DonationsPage.php +++ b/includes/Admin/DonationsPage.php @@ -24,7 +24,7 @@ final class DonationsPage { echo '
'; echo ' '; diff --git a/includes/Admin/PayPalConnector.php b/includes/Admin/PayPalConnector.php index 59c3cd8..4e4208e 100644 --- a/includes/Admin/PayPalConnector.php +++ b/includes/Admin/PayPalConnector.php @@ -59,7 +59,7 @@ final class PayPalConnector { public static function instructions(): void { ?>
    -
  1. You need a PayPal Business account (free). A personal account cannot receive donations this way. Create one or upgrade your existing account in PayPal settings.
  2. +
  3. To take real payments PayPal requires a PayPal Business account (free; your own name is fine). Practising in Sandbox needs no business account. Create one or upgrade your existing account in PayPal settings.
  4. Open developer.paypal.com/dashboard/applications and log in with that Business account.
  5. At the top, pick Sandbox (to practise) or Live (real money) and click Create App.
  6. Give it any name (for example "My stream"), keep the type Merchant, and click Create App.
  7. diff --git a/includes/Admin/SettingsPage.php b/includes/Admin/SettingsPage.php index a24d042..5e9afa9 100644 --- a/includes/Admin/SettingsPage.php +++ b/includes/Admin/SettingsPage.php @@ -33,7 +33,7 @@ final class SettingsPage { echo ''; } echo '

    One currency for the whole site. It applies to goals you create from now on; existing goals keep their currency. Check the fixed fee below after changing it.

    '; - echo ''; + echo ' At least ' . esc_html( Format::money( \StreamGoals\Core\Settings::HARD_MIN_MINOR, $cur ) ) . '. Visitors cannot donate less than this.'; echo ' characters (0 to 500; 0 = no messages)'; echo 'Names
    '; foreach ( self::POLICIES as $k => $l ) { @@ -64,8 +64,8 @@ final class SettingsPage { $upd = array(); $min = Input::amountToMinor( $post['min_donation'] ?? '', $cur ); - if ( null === $min || $min < 1 ) { - $errors[] = 'Minimum donation must be an amount greater than zero.'; + if ( null === $min || $min < \StreamGoals\Core\Settings::HARD_MIN_MINOR ) { + $errors[] = 'Minimum donation must be at least ' . Format::money( \StreamGoals\Core\Settings::HARD_MIN_MINOR, $cur ) . '. PayPal\'s fixed fee makes smaller donations lose money.'; } else { $upd['min_donation_minor'] = $min; } diff --git a/includes/Admin/Store.php b/includes/Admin/Store.php index f8bc0bb..780159a 100644 --- a/includes/Admin/Store.php +++ b/includes/Admin/Store.php @@ -107,7 +107,7 @@ final class Store { $w = array( '1=1' ); $args = array(); $st = $f['status'] ?? ''; - if ( in_array( $st, array( 'pending', 'completed', 'refunded', 'reversed' ), true ) ) { + if ( in_array( $st, array( 'pending', 'completed' ), true ) ) { $w[] = 'status = %s'; $args[] = $st; } diff --git a/includes/Core/Maintenance.php b/includes/Core/Maintenance.php new file mode 100644 index 0000000..5b7d079 --- /dev/null +++ b/includes/Core/Maintenance.php @@ -0,0 +1,41 @@ +prefix . 'sg_donations'; + $cutoff = gmdate( 'Y-m-d H:i:s', time() - self::MAX_AGE_DAYS * DAY_IN_SECONDS ); + $n = $wpdb->query( + $wpdb->prepare( + "DELETE FROM {$table} WHERE status = 'pending' AND (paypal_capture_id IS NULL OR paypal_capture_id = '') AND goal_id > 0 AND created_at < %s", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared + $cutoff + ) + ); + return (int) $n; + } +} diff --git a/includes/Core/Plugin.php b/includes/Core/Plugin.php index fa5aded..114f409 100644 --- a/includes/Core/Plugin.php +++ b/includes/Core/Plugin.php @@ -18,6 +18,7 @@ final class Plugin { public static function boot(): void { Installer::maybe_upgrade(); + Maintenance::register(); foreach ( self::MODULES as $module ) { if ( class_exists( $module ) && method_exists( $module, 'register' ) ) { $module::register(); diff --git a/includes/Core/Settings.php b/includes/Core/Settings.php index cf37917..d0924de 100644 --- a/includes/Core/Settings.php +++ b/includes/Core/Settings.php @@ -8,6 +8,17 @@ namespace StreamGoals\Core; */ final class Settings { + /** + * Absolute minimum donation in minor units (1.00 of the currency). PayPal's fixed per-transaction fee + * makes smaller donations a net loss for the streamer, so the configured minimum can never go below this. + */ + public const HARD_MIN_MINOR = 100; + + /** The minimum that is actually enforced: the configured value, but never below the hard floor. */ + public static function effectiveMin( int $configured ): int { + return max( self::HARD_MIN_MINOR, $configured ); + } + public static function defaults(): array { return array( 'paypal_mode' => 'sandbox', // sandbox | live diff --git a/includes/PayPal/OrderValidator.php b/includes/PayPal/OrderValidator.php index 851e5d3..dd2440a 100644 --- a/includes/PayPal/OrderValidator.php +++ b/includes/PayPal/OrderValidator.php @@ -94,9 +94,9 @@ final class OrderValidator { } catch ( \InvalidArgumentException $e ) { throw new ValidationException( 'invalid_amount', 'Please enter a valid amount.' ); } - $min = (int) ( $settings['min_donation_minor'] ?? 0 ); + $min = \StreamGoals\Core\Settings::effectiveMin( (int) ( $settings['min_donation_minor'] ?? 0 ) ); if ( $base <= 0 || $base < $min ) { - throw new ValidationException( 'amount_too_small', 'The amount is below the minimum donation.' ); + throw new ValidationException( 'amount_too_small', 'The minimum donation is ' . ( new Money( $min, $currency ) )->toDecimalString() . ' ' . $currency . '.' ); } if ( $base > 99999999 ) { // sanity cap (~$999,999.99) throw new ValidationException( 'amount_too_large', 'The amount is too large.' ); diff --git a/includes/Rest/DonateController.php b/includes/Rest/DonateController.php index 3b14aff..d3ac3ec 100644 --- a/includes/Rest/DonateController.php +++ b/includes/Rest/DonateController.php @@ -177,7 +177,7 @@ final class DonateController { 'restUrl' => esc_url_raw( rest_url( self::NS ) ), 'clientId' => (string) $s['paypal_client_id'], 'policy' => (string) $s['anonymity_policy'], - 'minMinor' => (int) $s['min_donation_minor'], + 'minMinor' => \StreamGoals\Core\Settings::effectiveMin( (int) $s['min_donation_minor'] ), 'messageMax' => min( 500, (int) $s['message_max_length'] ), 'goals' => $goals, 'i18n' => array( @@ -193,6 +193,14 @@ final class DonateController { 'error' => __( 'Something went wrong. Please try again.', 'streamgoals-donate' ), 'sdkError' => __( 'Could not load PayPal.', 'streamgoals-donate' ), 'fixForm' => __( 'Please fix the form before paying.', 'streamgoals-donate' ), + 'customAmount' => __( 'Or enter your own amount', 'streamgoals-donate' ), + 'customPlaceholder' => __( 'Other amount', 'streamgoals-donate' ), + /* translators: %s: formatted minimum amount, e.g. $1.00 */ + 'minHint' => __( 'Minimum donation: %s', 'streamgoals-donate' ), + /* translators: %s: formatted minimum amount, e.g. $1.00 */ + 'belowMin' => __( 'The minimum donation is %s.', 'streamgoals-donate' ), + 'coverInfoLabel' => __( 'What does this mean?', 'streamgoals-donate' ), + 'coverInfo' => __( 'PayPal takes a small fee from every donation. Tick this box to add that fee to your total, so the full amount you chose reaches the streamer. It is optional.', 'streamgoals-donate' ), ), ); wp_add_inline_script( 'streamgoals-donate', 'window.StreamGoalsDonate=' . wp_json_encode( $config, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT ) . ';', 'before' ); diff --git a/streamgoals-donate.php b/streamgoals-donate.php index 42be2c5..992483b 100644 --- a/streamgoals-donate.php +++ b/streamgoals-donate.php @@ -31,4 +31,5 @@ spl_autoload_register( ); register_activation_hook( __FILE__, array( \StreamGoals\Core\Installer::class, 'activate' ) ); +register_deactivation_hook( __FILE__, array( \StreamGoals\Core\Maintenance::class, 'unschedule' ) ); add_action( 'plugins_loaded', array( \StreamGoals\Core\Plugin::class, 'boot' ) ); diff --git a/tests/Unit/MinimumDonationTest.php b/tests/Unit/MinimumDonationTest.php new file mode 100644 index 0000000..2ffeca2 --- /dev/null +++ b/tests/Unit/MinimumDonationTest.php @@ -0,0 +1,73 @@ + 1, 'currency' => $currency, 'status' => 'active', 'starts_at' => null, 'ends_at' => null ); + $settings = array_merge( Settings::defaults(), array( 'min_donation_minor' => $configuredMin ) ); + return OrderValidator::quote( array( 'amount' => $amount ), $goal, $settings, new FeeCalculator( 349, 49 ), self::NOW ); + } + + public function test_effective_min_never_below_hard_floor(): void { + $this->assertSame( 100, Settings::effectiveMin( 0 ) ); + $this->assertSame( 100, Settings::effectiveMin( 1 ) ); + $this->assertSame( 100, Settings::effectiveMin( 99 ) ); + $this->assertSame( 500, Settings::effectiveMin( 500 ) ); + } + + public function test_configured_zero_or_tiny_minimum_still_enforces_floor(): void { + foreach ( array( 0, 1, 50 ) as $configured ) { + try { + $this->quote( '0.50', $configured ); + $this->fail( "0.50 accepted with configured min $configured" ); + } catch ( ValidationException $e ) { + $this->assertSame( 'amount_too_small', $e->errorCode ); + } + } + } + + public function test_exactly_the_floor_is_accepted(): void { + $this->assertSame( 100, $this->quote( '1.00', 0 )['base_minor'] ); + $this->assertSame( 100, $this->quote( '1', 100 )['base_minor'] ); + } + + public function test_higher_configured_minimum_wins_and_error_names_it(): void { + $this->assertSame( 500, $this->quote( '5.00', 500 )['base_minor'] ); + try { + $this->quote( '4.99', 500 ); + $this->fail( 'expected rejection' ); + } catch ( ValidationException $e ) { + $this->assertSame( 'amount_too_small', $e->errorCode ); + $this->assertStringContainsString( '5.00 USD', $e->getMessage() ); + } + } + + public function test_zero_and_negative_rejected(): void { + foreach ( array( '0', '0.00', '-5' ) as $amt ) { + try { + $this->quote( $amt, 100 ); + $this->fail( "amount '$amt' was accepted" ); + } catch ( ValidationException $e ) { + $this->assertContains( $e->errorCode, array( 'amount_too_small', 'invalid_amount' ) ); + } + } + } + + public function test_fee_cover_does_not_change_the_floor_check(): void { + // The floor applies to the base amount the streamer receives, not the fee-inflated total. + $this->expectException( ValidationException::class ); + $goal = array( 'id' => 1, 'currency' => 'USD', 'status' => 'active', 'starts_at' => null, 'ends_at' => null ); + OrderValidator::quote( array( 'amount' => '0.60', 'cover_fees' => true ), $goal, Settings::defaults(), new FeeCalculator( 349, 49 ), self::NOW ); + } +}