From 589e84f28b91ed3919af3db31d56954fa76f1b04 Mon Sep 17 00:00:00 2001 From: Josh Knapp Date: Sun, 15 Nov 2026 08:47:00 -0800 Subject: [PATCH] Add PayPal client, donate flow, webhook; wire rules engine with per-goal lock Replace the static Engine call (which silently failed) with Engine::default() and a MySQL named lock. Add engine->overlay integration test. Co-Authored-By: Claude Sonnet 5.5 --- assets/donate/donate.css | 13 + assets/donate/donate.js | 177 +++++++++++++ includes/PayPal/ArrayCache.php | 23 ++ includes/PayPal/Cache.php | 14 + includes/PayPal/Client.php | 250 ++++++++++++++++++ includes/PayPal/DonationStore.php | 123 +++++++++ includes/PayPal/HttpTransport.php | 15 ++ includes/PayPal/OrderValidator.php | 131 +++++++++ includes/PayPal/PayPalException.php | 12 + includes/PayPal/RateLimiter.php | 21 ++ includes/PayPal/TransportException.php | 6 + includes/PayPal/ValidationException.php | 11 + includes/PayPal/WebhookEvent.php | 50 ++++ includes/PayPal/WpCache.php | 19 ++ includes/PayPal/WpTransport.php | 27 ++ includes/Rest/DonateController.php | 230 ++++++++++++++++ includes/Rest/WebhookController.php | 121 +++++++++ includes/Rules/Engine.php | 22 ++ tests/Unit/EngineToOverlayIntegrationTest.php | 56 ++++ tests/Unit/PayPalClientTest.php | 211 +++++++++++++++ tests/Unit/PayPalOrderValidatorTest.php | 127 +++++++++ 21 files changed, 1659 insertions(+) create mode 100644 assets/donate/donate.css create mode 100644 assets/donate/donate.js create mode 100644 includes/PayPal/ArrayCache.php create mode 100644 includes/PayPal/Cache.php create mode 100644 includes/PayPal/Client.php create mode 100644 includes/PayPal/DonationStore.php create mode 100644 includes/PayPal/HttpTransport.php create mode 100644 includes/PayPal/OrderValidator.php create mode 100644 includes/PayPal/PayPalException.php create mode 100644 includes/PayPal/RateLimiter.php create mode 100644 includes/PayPal/TransportException.php create mode 100644 includes/PayPal/ValidationException.php create mode 100644 includes/PayPal/WebhookEvent.php create mode 100644 includes/PayPal/WpCache.php create mode 100644 includes/PayPal/WpTransport.php create mode 100644 includes/Rest/DonateController.php create mode 100644 includes/Rest/WebhookController.php create mode 100644 tests/Unit/EngineToOverlayIntegrationTest.php create mode 100644 tests/Unit/PayPalClientTest.php create mode 100644 tests/Unit/PayPalOrderValidatorTest.php diff --git a/assets/donate/donate.css b/assets/donate/donate.css new file mode 100644 index 0000000..5fecac2 --- /dev/null +++ b/assets/donate/donate.css @@ -0,0 +1,13 @@ +.sg-donate{max-width:28rem;font:inherit} +.sg-donate .sg-row{margin:0 0 .9rem} +.sg-donate label{display:block;font-weight:600;margin-bottom:.25rem} +.sg-donate label.sg-inline{display:flex;gap:.5rem;align-items:center;font-weight:400} +.sg-donate input[type=text],.sg-donate input[type=number],.sg-donate select,.sg-donate textarea{width:100%;box-sizing:border-box} +.sg-donate .sg-presets{display:flex;flex-wrap:wrap;gap:.4rem;margin-bottom:.4rem} +.sg-donate .sg-presets button{cursor:pointer} +.sg-donate .sg-presets button[aria-pressed=true]{font-weight:700;outline:2px solid currentColor} +.sg-donate .sg-total{font-weight:700} +.sg-donate .sg-msg{margin-top:.6rem} +.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} diff --git a/assets/donate/donate.js b/assets/donate/donate.js new file mode 100644 index 0000000..32b2a41 --- /dev/null +++ b/assets/donate/donate.js @@ -0,0 +1,177 @@ +/* StreamGoals donate form (vanilla JS). Config comes from window.StreamGoalsDonate. */ +(function () { + 'use strict'; + var C = window.StreamGoalsDonate; + if (!C) { return; } + var T = C.i18n || {}; + var sdkPromise = null, sdkCurrency = null; + + function el(tag, attrs, children) { + var n = document.createElement(tag); + Object.keys(attrs || {}).forEach(function (k) { + if (k === 'text') { n.textContent = attrs[k]; } else { n.setAttribute(k, attrs[k]); } + }); + (children || []).forEach(function (c) { n.appendChild(c); }); + return n; + } + function row(children) { return el('div', { 'class': 'sg-row' }, children); } + + function api(path, opts) { + opts = opts || {}; + return fetch(C.restUrl + path, { + method: opts.method || 'GET', + headers: { 'Content-Type': 'application/json' }, + body: opts.body ? JSON.stringify(opts.body) : undefined, + credentials: 'omit' + }).then(function (r) { + return r.json().then(function (j) { + if (!r.ok) { var e = new Error(j && j.message ? j.message : T.error); e.status = r.status; throw e; } + return j; + }, function () { if (!r.ok) { throw new Error(T.error); } return {}; }); + }); + } + + // The PayPal SDK is bound to one currency per page load; reload it if the selected goal differs. + function loadSdk(currency) { + if (sdkPromise && sdkCurrency === currency) { return sdkPromise; } + var old = document.getElementById('sg-paypal-sdk'); + if (old) { old.parentNode.removeChild(old); try { delete window.paypal; } catch (e) { window.paypal = undefined; } } + sdkCurrency = currency; + sdkPromise = new Promise(function (resolve, reject) { + var s = document.createElement('script'); + s.id = 'sg-paypal-sdk'; + s.src = 'https://www.paypal.com/sdk/js?client-id=' + encodeURIComponent(C.clientId) + + '¤cy=' + encodeURIComponent(currency) + '&intent=capture&components=buttons'; + s.onload = function () { window.paypal ? resolve(window.paypal) : reject(new Error(T.sdkError)); }; + s.onerror = function () { reject(new Error(T.sdkError)); }; + document.head.appendChild(s); + }); + return sdkPromise; + } + + function fmt(minor, exp, cur) { + var v = minor / Math.pow(10, exp); + try { return new Intl.NumberFormat(undefined, { style: 'currency', currency: cur }).format(v); } + catch (e) { return v.toFixed(exp) + ' ' + cur; } + } + function presets(exp) { + var base = exp === 0 ? [500, 1000, 2500, 5000] : [5, 10, 25, 50]; + return base; + } + + function init(root) { + var pinned = parseInt(root.getAttribute('data-goal'), 10) || 0; + var goals = C.goals.filter(function (g) { return !pinned || g.id === pinned; }); + if (!goals.length) { return; } + var uid = 'sg' + Math.random().toString(36).slice(2, 8); + var state = { goal: goals[0], renderToken: 0, quote: null }; + + 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 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' }); + var msg = el('textarea', { id: uid + '-msg', rows: '3', maxlength: String(C.messageMax) }); + var cover = el('input', { type: 'checkbox', id: uid + '-cover' }); + var total = el('div', { 'class': 'sg-total', id: uid + '-total', 'aria-live': 'polite' }); + var status = el('div', { 'class': 'sg-msg', role: 'status' }); + 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])); + 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; } + else if (C.policy === 'require_name') { anonRow.hidden = true; name.required = true; } + 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)])])); + root.appendChild(row([total])); + root.appendChild(buttons); + root.appendChild(status); + + function say(text, cls) { status.textContent = text || ''; status.className = 'sg-msg' + (cls ? ' ' + cls : ''); } + function amountStr() { return amount.value.trim().replace(',', '.'); } + function anonNow() { return anon.checked; } + anon.addEventListener('change', function () { nameRow.hidden = anon.checked || C.policy === 'force_anonymous'; }); + + function buildPresets() { + presetBox.textContent = ''; + 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(); }); + presetBox.appendChild(b); + }); + } + function markPresets() { + var cur = amountStr(); + Array.prototype.forEach.call(presetBox.children, function (b, i) { + b.setAttribute('aria-pressed', String(String(presets(state.goal.exp)[i]) === cur)); + }); + } + + // Server-authoritative total preview (debounced). The server recomputes it again when the order is created. + var timer = null, seq = 0; + function refresh() { + markPresets(); + state.quote = null; + buttons.setAttribute('data-disabled', 'true'); + clearTimeout(timer); + if (!amountStr()) { total.textContent = ''; return; } + var mine = ++seq; + timer = setTimeout(function () { + var qs = 'goal_id=' + state.goal.id + '&amount=' + encodeURIComponent(amountStr()) + '&cover_fees=' + (cover.checked ? '1' : '0'); + api('/fee-preview?' + qs).then(function (q) { + if (mine !== seq) { return; } + state.quote = q; + var t = T.total + ': ' + fmt(q.total_minor, state.goal.exp, q.currency); + if (q.fee_minor > 0) { t += ' (' + fmt(q.fee_minor, state.goal.exp, q.currency) + ')'; } + total.textContent = t; say(''); + buttons.removeAttribute('data-disabled'); + }, function (e) { if (mine === seq) { total.textContent = ''; say(e.message, 'sg-error'); } }); + }, 250); + } + [amount, cover].forEach(function (n) { n.addEventListener(n === cover ? 'change' : 'input', refresh); }); + + function payload() { + return { + goal_id: state.goal.id, amount: amountStr(), display_name: name.value, anonymous: anonNow(), + message: msg.value, cover_fees: cover.checked + }; + } + + function renderButtons() { + var token = ++state.renderToken; + buttons.textContent = ''; + loadSdk(state.goal.currency).then(function (paypal) { + 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(); } + say(''); + }, + createOrder: function () { + return api('/orders', { method: 'POST', body: payload() }).then(function (r) { return r.order_id; }); + }, + onApprove: function (data) { + return api('/orders/' + encodeURIComponent(data.orderID) + '/capture', { method: 'POST' }).then(function (r) { + say(r.status === 'completed' ? T.thanks : T.processing, 'sg-ok'); + }); + }, + onError: function (err) { say((err && err.message) || T.error, 'sg-error'); } + }).render(buttons); + }, function (e) { say(e.message, 'sg-error'); }); + } + + goalSel.addEventListener('change', function () { + state.goal = goals.filter(function (g) { return String(g.id) === goalSel.value; })[0] || goals[0]; + buildPresets(); refresh(); renderButtons(); + }); + buildPresets(); refresh(); renderButtons(); + } + + function boot() { Array.prototype.forEach.call(document.querySelectorAll('.sg-donate'), init); } + if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', boot); } else { boot(); } +})(); diff --git a/includes/PayPal/ArrayCache.php b/includes/PayPal/ArrayCache.php new file mode 100644 index 0000000..6c89ea3 --- /dev/null +++ b/includes/PayPal/ArrayCache.php @@ -0,0 +1,23 @@ + */ + private array $items = array(); + + public function get( string $key ): mixed { + return $this->items[ $key ] ?? false; + } + + public function set( string $key, mixed $value, int $ttl ): void { + $this->items[ $key ] = $value; + } + + public function delete( string $key ): void { + unset( $this->items[ $key ] ); + } +} diff --git a/includes/PayPal/Cache.php b/includes/PayPal/Cache.php new file mode 100644 index 0000000..9708c6d --- /dev/null +++ b/includes/PayPal/Cache.php @@ -0,0 +1,14 @@ +mode ? 'https://api-m.paypal.com' : 'https://api-m.sandbox.paypal.com'; + } + + public function accessToken( bool $forceRefresh = false ): string { + if ( '' === $this->clientId || '' === $this->secret ) { + throw new PayPalException( 'PayPal Client ID and Secret are not configured.' ); + } + $key = 'sg_pp_token_' . md5( $this->mode . '|' . $this->clientId . '|' . $this->secret ); + if ( ! $forceRefresh ) { + $cached = $this->cache->get( $key ); + if ( is_string( $cached ) && '' !== $cached ) { + return $cached; + } + } + $res = $this->send( + 'POST', + '/v1/oauth2/token', + array( + 'Authorization' => 'Basic ' . base64_encode( $this->clientId . ':' . $this->secret ), + 'Content-Type' => 'application/x-www-form-urlencoded', + 'Accept' => 'application/json', + ), + 'grant_type=client_credentials' + ); + $data = self::decode( $res['body'] ); + if ( $res['status'] < 200 || $res['status'] >= 300 || empty( $data['access_token'] ) ) { + if ( 401 === $res['status'] ) { + throw new PayPalException( 'PayPal rejected the credentials. Check that the Client ID and Secret belong to the selected ' . ( 'live' === $this->mode ? 'Live' : 'Sandbox' ) . ' mode.', 401 ); + } + throw self::errorFrom( $res, 'Could not get a PayPal access token' ); + } + $ttl = max( 60, (int) ( $data['expires_in'] ?? 300 ) - 120 ); + $this->cache->set( $key, (string) $data['access_token'], $ttl ); + return (string) $data['access_token']; + } + + /** @return string PayPal order id */ + public function createOrder( Money $total, string $customId, string $requestId ): string { + $res = $this->api( + 'POST', + '/v2/checkout/orders', + array( + 'intent' => 'CAPTURE', + 'purchase_units' => array( + array( + 'custom_id' => $customId, + 'description' => 'Donation', + 'amount' => array( + 'currency_code' => $total->currency, + 'value' => $total->toDecimalString(), + ), + ), + ), + ), + array( 'PayPal-Request-Id' => $requestId ) + ); + if ( empty( $res['id'] ) ) { + throw new PayPalException( 'PayPal did not return an order id.' ); + } + return (string) $res['id']; + } + + /** @return array{status:string,capture_id:string,amount:?Money,custom_id:string} */ + public function captureOrder( string $orderId, string $requestId ): array { + $res = $this->api( 'POST', '/v2/checkout/orders/' . rawurlencode( $orderId ) . '/capture', new \stdClass(), array( 'PayPal-Request-Id' => $requestId ) ); + return self::parseCapture( $res ); + } + + /** @return array{status:string,capture_id:string,amount:?Money,custom_id:string} */ + public static function parseCapture( array $order ): array { + $cap = $order['purchase_units'][0]['payments']['captures'][0] ?? array(); + $amount = null; + if ( isset( $cap['amount']['value'], $cap['amount']['currency_code'] ) ) { + try { + $amount = Money::fromDecimalString( (string) $cap['amount']['value'], (string) $cap['amount']['currency_code'] ); + } catch ( \InvalidArgumentException $e ) { + $amount = null; + } + } + return array( + 'status' => (string) ( $cap['status'] ?? ( $order['status'] ?? '' ) ), + 'capture_id' => (string) ( $cap['id'] ?? '' ), + 'amount' => $amount, + 'custom_id' => (string) ( $cap['custom_id'] ?? ( $order['purchase_units'][0]['custom_id'] ?? '' ) ), + ); + } + + /** + * @param array $headers Incoming webhook request headers (any case; '-' or '_'). + */ + public function verifyWebhook( array $headers, string $rawBody, string $webhookId ): bool { + $h = array(); + foreach ( $headers as $k => $v ) { + $h[ strtolower( str_replace( '-', '_', (string) $k ) ) ] = is_array( $v ) ? (string) ( $v[0] ?? '' ) : (string) $v; + } + $event = json_decode( $rawBody ); + if ( ! is_object( $event ) || '' === $webhookId ) { + return false; + } + $need = array( 'paypal_transmission_id', 'paypal_transmission_time', 'paypal_transmission_sig', 'paypal_cert_url', 'paypal_auth_algo' ); + foreach ( $need as $n ) { + if ( empty( $h[ $n ] ) ) { + return false; + } + } + try { + $res = $this->api( + 'POST', + '/v1/notifications/verify-webhook-signature', + array( + 'auth_algo' => $h['paypal_auth_algo'], + 'cert_url' => $h['paypal_cert_url'], + 'transmission_id' => $h['paypal_transmission_id'], + 'transmission_sig' => $h['paypal_transmission_sig'], + 'transmission_time' => $h['paypal_transmission_time'], + 'webhook_id' => $webhookId, + 'webhook_event' => $event, + ) + ); + } catch ( PayPalException $e ) { + return false; // fail closed + } + return 'SUCCESS' === ( $res['verification_status'] ?? '' ); + } + + /** @return string The new webhook id (store it in settings as paypal_webhook_id). */ + public function createWebhook( string $url ): string { + $res = $this->api( + 'POST', + '/v1/notifications/webhooks', + array( + 'url' => $url, + 'event_types' => array_map( static fn( string $n ): array => array( 'name' => $n ), self::WEBHOOK_EVENTS ), + ) + ); + if ( empty( $res['id'] ) ) { + throw new PayPalException( 'PayPal did not return a webhook id.' ); + } + return (string) $res['id']; + } + + /** Returns null when the credentials work, otherwise a human-readable error. */ + public function testConnection(): ?string { + try { + $this->accessToken( true ); + return null; + } catch ( PayPalException $e ) { + return $e->getMessage(); + } + } + + /** + * Authenticated JSON call. Retries once with a fresh token on 401. + * + * @param array|\stdClass $payload + * @param array $extraHeaders + */ + private function api( string $method, string $path, array|\stdClass $payload, array $extraHeaders = array() ): array { + $body = self::json( $payload ); + for ( $attempt = 0; $attempt < 2; $attempt++ ) { + $token = $this->accessToken( 1 === $attempt ); + $res = $this->send( + $method, + $path, + array_merge( + array( + 'Authorization' => 'Bearer ' . $token, + 'Content-Type' => 'application/json', + 'Accept' => 'application/json', + ), + $extraHeaders + ), + $body + ); + if ( 401 === $res['status'] && 0 === $attempt ) { + continue; + } + break; + } + if ( $res['status'] < 200 || $res['status'] >= 300 ) { + throw self::errorFrom( $res, 'PayPal request failed' ); + } + return self::decode( $res['body'] ); + } + + /** @return array{status:int,body:string} */ + private function send( string $method, string $path, array $headers, ?string $body ): array { + try { + return $this->http->request( $method, $this->baseUrl() . $path, $headers, $body ); + } catch ( TransportException $e ) { + throw new PayPalException( 'Could not reach PayPal: ' . $e->getMessage() ); + } + } + + private static function decode( string $json ): array { + $d = json_decode( $json, true ); + return is_array( $d ) ? $d : array(); + } + + private static function errorFrom( array $res, string $prefix ): PayPalException { + $d = self::decode( $res['body'] ); + $name = (string) ( $d['name'] ?? $d['error'] ?? '' ); + $msg = (string) ( $d['message'] ?? $d['error_description'] ?? '' ); + $det = (string) ( $d['details'][0]['description'] ?? $d['details'][0]['issue'] ?? '' ); + $text = $prefix . ' (HTTP ' . $res['status'] . ')'; + if ( '' !== $msg ) { + $text .= ': ' . $msg; + } + if ( '' !== $det ) { + $text .= ' - ' . $det; + } + if ( '' === $name && '' !== $det ) { + $name = $det; + } + return new PayPalException( $text, $res['status'], $name ); + } + + /** json_encode via wp_json_encode when available. */ + private static function json( mixed $data ): string { + $out = function_exists( 'wp_json_encode' ) ? wp_json_encode( $data ) : json_encode( $data, JSON_UNESCAPED_SLASHES ); + return false === $out ? '{}' : $out; + } +} diff --git a/includes/PayPal/DonationStore.php b/includes/PayPal/DonationStore.php new file mode 100644 index 0000000..425e7c7 --- /dev/null +++ b/includes/PayPal/DonationStore.php @@ -0,0 +1,123 @@ +prefix . 'sg_' . $name; + } + + public static function goal( int $id ): ?array { + global $wpdb; + $row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM ' . self::t( 'goals' ) . ' WHERE id = %d', $id ), ARRAY_A ); + return $row ?: null; + } + + /** @return array[] */ + public static function active_goals(): array { + global $wpdb; + $rows = $wpdb->get_results( 'SELECT * FROM ' . self::t( 'goals' ) . " WHERE status = 'active' ORDER BY id ASC", ARRAY_A ); + $now = time(); + return array_values( array_filter( (array) $rows, static fn( array $g ): bool => OrderValidator::goalIsOpen( $g, $now ) ) ); + } + + public static function find( int $id ): ?object { + global $wpdb; + return $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM ' . self::t( 'donations' ) . ' WHERE id = %d', $id ) ) ?: null; + } + + public static function find_by_order( string $orderId ): ?object { + global $wpdb; + return $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM ' . self::t( 'donations' ) . ' WHERE paypal_order_id = %s ORDER BY id DESC LIMIT 1', $orderId ) ) ?: null; + } + + public static function find_by_capture( string $captureId ): ?object { + global $wpdb; + if ( '' === $captureId ) { + return null; + } + return $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM ' . self::t( 'donations' ) . ' WHERE paypal_capture_id = %s', $captureId ) ) ?: null; + } + + /** @param array $v Output of OrderValidator::validate(). @return int Donation id (0 on failure). */ + public static function insert_pending( array $v ): int { + global $wpdb; + $ok = $wpdb->insert( + self::t( 'donations' ), + array( + 'goal_id' => $v['goal_id'], + 'paypal_order_id' => '', + 'base_minor' => $v['base_minor'], + 'fee_minor' => $v['fee_minor'], + 'total_minor' => $v['total_minor'], + 'currency' => $v['currency'], + 'donor_name' => $v['donor_name'], + 'is_anonymous' => $v['is_anonymous'] ? 1 : 0, + 'message' => $v['message'], + 'status' => 'pending', + 'moderation' => $v['moderation'], + 'created_at' => gmdate( 'Y-m-d H:i:s' ), + ), + array( '%d', '%s', '%d', '%d', '%d', '%s', '%s', '%d', '%s', '%s', '%s', '%s' ) + ); + return $ok ? (int) $wpdb->insert_id : 0; + } + + public static function set_order_id( int $id, string $orderId ): void { + global $wpdb; + $wpdb->update( self::t( 'donations' ), array( 'paypal_order_id' => $orderId ), array( 'id' => $id ), array( '%s' ), array( '%d' ) ); + } + + public static function delete( int $id ): void { + global $wpdb; + $wpdb->delete( self::t( 'donations' ), array( 'id' => $id ), array( '%d' ) ); + } + + /** Atomic pending -> completed. True only for the single caller that wins the transition. */ + public static function mark_completed( int $id, string $captureId ): bool { + global $wpdb; + $n = $wpdb->query( $wpdb->prepare( 'UPDATE ' . self::t( 'donations' ) . " SET status = 'completed', paypal_capture_id = %s WHERE id = %d AND status = 'pending'", $captureId, $id ) ); + return 1 === $n; + } + + /** Atomic completed -> refunded|reversed. */ + public static function mark_reversed( int $id, string $status ): bool { + global $wpdb; + if ( ! in_array( $status, array( 'refunded', 'reversed' ), true ) ) { + return false; + } + $n = $wpdb->query( $wpdb->prepare( 'UPDATE ' . self::t( 'donations' ) . " SET status = %s WHERE id = %d AND status = 'completed'", $status, $id ) ); + return 1 === $n; + } + + /** Hand a freshly completed donation to the rules engine (if present). Never throws. */ + public static function notify_applied( int $id ): void { + self::call_engine( 'applyDonation', $id ); + } + + public static function notify_reversed( int $id ): void { + self::call_engine( 'reverseDonation', $id ); + } + + private static function call_engine( string $method, int $id ): void { + $row = self::find( $id ); + if ( ! $row ) { + return; + } + try { + $donation = \StreamGoals\Core\DonationRepository::toDonation( (array) $row ); + \StreamGoals\Rules\Engine::withGoalLock( + $donation->goalId, + static function () use ( $method, $donation ): void { + \StreamGoals\Rules\Engine::default()->$method( $donation ); + } + ); + } catch ( \Throwable $e ) { + error_log( 'StreamGoals: Engine::' . $method . ' failed for donation ' . $id . ': ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions + } + } +} diff --git a/includes/PayPal/HttpTransport.php b/includes/PayPal/HttpTransport.php new file mode 100644 index 0000000..7159c31 --- /dev/null +++ b/includes/PayPal/HttpTransport.php @@ -0,0 +1,15 @@ + $headers + * @return array{status:int, body:string} + * @throws TransportException On network-level failure (no HTTP response). + */ + public function request( string $method, string $url, array $headers, ?string $body ): array; +} diff --git a/includes/PayPal/OrderValidator.php b/includes/PayPal/OrderValidator.php new file mode 100644 index 0000000..0417cc6 --- /dev/null +++ b/includes/PayPal/OrderValidator.php @@ -0,0 +1,131 @@ + $maxLen ) { + throw new ValidationException( 'message_too_long', "Message must be at most {$maxLen} characters." ); + } + + $name = self::clean( $input['display_name'] ?? '' ); + $wantsAnon = filter_var( $input['anonymous'] ?? false, FILTER_VALIDATE_BOOLEAN ); + $policy = (string) ( $settings['anonymity_policy'] ?? 'allow' ); + if ( mb_strlen( $name ) > self::NAME_MAX ) { + throw new ValidationException( 'name_too_long', 'Display name is too long.' ); + } + switch ( $policy ) { + case 'force_anonymous': + $anon = true; + break; + case 'require_name': + if ( '' === $name ) { + throw new ValidationException( 'name_required', 'Please enter a display name.' ); + } + $anon = false; + break; + default: + $anon = $wantsAnon; + } + if ( $anon ) { + $name = ''; // never persist the name of an anonymous donor + } + + return array( + 'goal_id' => (int) $goal['id'], + 'currency' => $currency, + 'base_minor' => $base, + 'fee_minor' => $fee, + 'total_minor' => $base + $fee, + 'donor_name' => $name, + 'is_anonymous' => $anon, + 'message' => $message, + 'cover_fees' => $cover, + 'moderation' => ( ! empty( $settings['moderate_messages'] ) && '' !== $message ) ? 'pending' : 'approved', + ); + } + + /** + * Goal-open check, amount parsing/minimum and fee cover only (used by the live fee preview). + * + * @return array{currency:string,base_minor:int,fee_minor:int,total_minor:int,cover_fees:bool} + * @throws ValidationException + */ + public static function quote( array $input, array $goal, array $settings, FeeCalculator $fees, int $nowTs ): array { + if ( ! self::goalIsOpen( $goal, $nowTs ) ) { + throw new ValidationException( 'goal_inactive', 'This goal is not accepting donations.', 409 ); + } + $currency = strtoupper( (string) $goal['currency'] ); + $rawAmount = is_scalar( $input['amount'] ?? null ) ? trim( (string) $input['amount'] ) : ''; + try { + $base = Money::fromDecimalString( $rawAmount, $currency )->minor; + } catch ( \InvalidArgumentException $e ) { + throw new ValidationException( 'invalid_amount', 'Please enter a valid amount.' ); + } + $min = (int) ( $settings['min_donation_minor'] ?? 0 ); + if ( $base <= 0 || $base < $min ) { + throw new ValidationException( 'amount_too_small', 'The amount is below the minimum donation.' ); + } + if ( $base > 99999999 ) { // sanity cap (~$999,999.99) + throw new ValidationException( 'amount_too_large', 'The amount is too large.' ); + } + $cover = filter_var( $input['cover_fees'] ?? false, FILTER_VALIDATE_BOOLEAN ); + $fee = $cover ? $fees->feeFor( $base ) : 0; + return array( + 'currency' => $currency, + 'base_minor' => $base, + 'fee_minor' => $fee, + 'total_minor' => $base + $fee, + 'cover_fees' => $cover, + ); + } + + /** Active status and inside the optional [starts_at, ends_at) window (UTC datetimes). */ + public static function goalIsOpen( array $goal, int $nowTs ): bool { + if ( 'active' !== ( $goal['status'] ?? '' ) ) { + return false; + } + if ( ! empty( $goal['starts_at'] ) && strtotime( $goal['starts_at'] . ' UTC' ) > $nowTs ) { + return false; + } + if ( ! empty( $goal['ends_at'] ) && strtotime( $goal['ends_at'] . ' UTC' ) <= $nowTs ) { + return false; + } + return true; + } + + private static function clean( mixed $v ): string { + if ( ! is_scalar( $v ) ) { + return ''; + } + $s = strip_tags( (string) $v ); + $s = preg_replace( '/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/u', '', $s ) ?? ''; + return trim( $s ); + } +} diff --git a/includes/PayPal/PayPalException.php b/includes/PayPal/PayPalException.php new file mode 100644 index 0000000..e1c6602 --- /dev/null +++ b/includes/PayPal/PayPalException.php @@ -0,0 +1,12 @@ +cache->get( $k ); + if ( $count >= $limit ) { + return false; + } + $this->cache->set( $k, $count + 1, $windowSeconds ); + return true; + } +} diff --git a/includes/PayPal/TransportException.php b/includes/PayPal/TransportException.php new file mode 100644 index 0000000..922e8e5 --- /dev/null +++ b/includes/PayPal/TransportException.php @@ -0,0 +1,6 @@ + $method, + 'headers' => $headers, + 'timeout' => 20, + ); + if ( null !== $body ) { + $args['body'] = $body; + } + $res = wp_remote_request( $url, $args ); + if ( is_wp_error( $res ) ) { + throw new TransportException( $res->get_error_message() ); + } + return array( + 'status' => (int) wp_remote_retrieve_response_code( $res ), + 'body' => (string) wp_remote_retrieve_body( $res ), + ); + } +} diff --git a/includes/Rest/DonateController.php b/includes/Rest/DonateController.php new file mode 100644 index 0000000..551c317 --- /dev/null +++ b/includes/Rest/DonateController.php @@ -0,0 +1,230 @@ + 'POST', + 'callback' => array( self::class, 'create_order' ), + 'permission_callback' => '__return_true', + ) + ); + register_rest_route( + self::NS, + '/orders/(?P[A-Za-z0-9_\-]{5,64})/capture', + array( + 'methods' => 'POST', + 'callback' => array( self::class, 'capture_order' ), + 'permission_callback' => '__return_true', + ) + ); + register_rest_route( + self::NS, + '/fee-preview', + array( + 'methods' => 'GET', + 'callback' => array( self::class, 'fee_preview' ), + 'permission_callback' => '__return_true', + ) + ); + } + + /* ---------------------------------------------------------------- REST */ + + public static function create_order( \WP_REST_Request $req ) { + if ( $limited = self::limit( 'order', 10, 300 ) ) { + return $limited; + } + $goal = DonationStore::goal( (int) $req->get_param( 'goal_id' ) ); + if ( ! $goal ) { + return new \WP_Error( 'sg_goal_not_found', __( 'Goal not found.', 'streamgoals-donate' ), array( 'status' => 404 ) ); + } + try { + $v = OrderValidator::validate( self::input( $req ), $goal, Settings::all(), Settings::fee_calculator(), time() ); + } catch ( ValidationException $e ) { + return new \WP_Error( 'sg_' . $e->errorCode, $e->getMessage(), array( 'status' => $e->status ) ); + } + + $id = DonationStore::insert_pending( $v ); + if ( ! $id ) { + return new \WP_Error( 'sg_db', __( 'Could not start the donation. Please try again.', 'streamgoals-donate' ), array( 'status' => 500 ) ); + } + try { + $orderId = Client::fromSettings()->createOrder( new Money( $v['total_minor'], $v['currency'] ), (string) $id, 'sg-order-' . $id ); + } catch ( PayPalException $e ) { + DonationStore::delete( $id ); + error_log( 'StreamGoals: create order failed: ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions + return new \WP_Error( 'sg_paypal', __( 'PayPal is unavailable right now. Please try again later.', 'streamgoals-donate' ), array( 'status' => 502 ) ); + } + DonationStore::set_order_id( $id, $orderId ); + + return rest_ensure_response( self::totals( $v ) + array( 'order_id' => $orderId ) ); + } + + public static function capture_order( \WP_REST_Request $req ) { + if ( $limited = self::limit( 'capture', 20, 300 ) ) { + return $limited; + } + $orderId = (string) $req['id']; + $row = DonationStore::find_by_order( $orderId ); + if ( ! $row ) { + return new \WP_Error( 'sg_order_not_found', __( 'Order not found.', 'streamgoals-donate' ), array( 'status' => 404 ) ); + } + if ( 'completed' === $row->status ) { + return rest_ensure_response( array( 'status' => 'completed' ) ); + } + if ( 'pending' !== $row->status ) { + return new \WP_Error( 'sg_order_state', __( 'This order can no longer be captured.', 'streamgoals-donate' ), array( 'status' => 409 ) ); + } + + try { + $cap = Client::fromSettings()->captureOrder( $orderId, 'sg-capture-' . $row->id ); + } catch ( PayPalException $e ) { + if ( 'ORDER_ALREADY_CAPTURED' === $e->paypalName ) { + $fresh = DonationStore::find( (int) $row->id ); + return rest_ensure_response( array( 'status' => ( $fresh && 'completed' === $fresh->status ) ? 'completed' : 'processing' ) ); + } + error_log( 'StreamGoals: capture failed: ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions + return new \WP_Error( 'sg_paypal', __( 'The payment could not be completed. You have not been charged.', 'streamgoals-donate' ), array( 'status' => 502 ) ); + } + + if ( 'COMPLETED' !== $cap['status'] || '' === $cap['capture_id'] ) { + // e.g. PENDING (e-check/review). The COMPLETED webhook will finalize it. + return new \WP_REST_Response( array( 'status' => 'processing' ), 202 ); + } + $amt = $cap['amount']; + if ( ! $amt || $amt->minor !== (int) $row->total_minor || $amt->currency !== $row->currency ) { + error_log( 'StreamGoals: captured amount mismatch for donation ' . $row->id ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions + return new \WP_REST_Response( array( 'status' => 'processing' ), 202 ); + } + if ( DonationStore::mark_completed( (int) $row->id, $cap['capture_id'] ) ) { + DonationStore::notify_applied( (int) $row->id ); + } + return rest_ensure_response( array( 'status' => 'completed' ) ); + } + + public static function fee_preview( \WP_REST_Request $req ) { + if ( $limited = self::limit( 'preview', 120, 60 ) ) { + return $limited; + } + $goal = DonationStore::goal( (int) $req->get_param( 'goal_id' ) ); + if ( ! $goal ) { + return new \WP_Error( 'sg_goal_not_found', __( 'Goal not found.', 'streamgoals-donate' ), array( 'status' => 404 ) ); + } + try { + $q = OrderValidator::quote( self::input( $req ), $goal, Settings::all(), Settings::fee_calculator(), time() ); + } catch ( ValidationException $e ) { + return new \WP_Error( 'sg_' . $e->errorCode, $e->getMessage(), array( 'status' => $e->status ) ); + } + return rest_ensure_response( self::totals( $q ) ); + } + + /* ----------------------------------------------------------- Shortcode */ + + public static function shortcode( $atts ): string { + $atts = shortcode_atts( array( 'goal' => '' ), (array) $atts, 'streamgoals_donate' ); + $pinned = (int) $atts['goal']; + $s = Settings::all(); + if ( '' === (string) $s['paypal_client_id'] ) { + return '

' . esc_html__( 'Donations are not available right now.', 'streamgoals-donate' ) . '

'; + } + + $goals = array(); + foreach ( DonationStore::active_goals() as $g ) { + if ( $pinned && (int) $g['id'] !== $pinned ) { + continue; + } + $goals[] = array( + 'id' => (int) $g['id'], + 'title' => (string) $g['title'], + 'currency' => strtoupper( (string) $g['currency'] ), + 'exp' => Money::exponent( (string) $g['currency'] ), + ); + } + if ( ! $goals ) { + return '

' . esc_html__( 'There is no active goal to donate to right now.', 'streamgoals-donate' ) . '

'; + } + + wp_enqueue_style( 'streamgoals-donate', STREAMGOALS_URL . 'assets/donate/donate.css', array(), STREAMGOALS_VERSION ); + wp_enqueue_script( 'streamgoals-donate', STREAMGOALS_URL . 'assets/donate/donate.js', array(), STREAMGOALS_VERSION, true ); + $config = array( + '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'], + 'messageMax' => min( 500, (int) $s['message_max_length'] ), + 'goals' => $goals, + 'i18n' => array( + 'goal' => __( 'Goal', 'streamgoals-donate' ), + 'amount' => __( 'Amount', 'streamgoals-donate' ), + 'name' => __( 'Display name', 'streamgoals-donate' ), + 'anonymous' => __( 'Donate anonymously', 'streamgoals-donate' ), + 'message' => __( 'Message (optional)', 'streamgoals-donate' ), + 'coverFees' => __( 'Cover the processing fees', 'streamgoals-donate' ), + 'total' => __( 'Total you will pay', 'streamgoals-donate' ), + 'thanks' => __( 'Thank you for your donation!', 'streamgoals-donate' ), + 'processing' => __( 'Your payment is being processed. Thank you!', 'streamgoals-donate' ), + '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' ), + ), + ); + 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' ); + + return '
'; + } + + /* ------------------------------------------------------------- Helpers */ + + /** Only whitelisted client fields are read; totals/fees from the client are ignored. */ + private static function input( \WP_REST_Request $req ): array { + $out = array(); + foreach ( array( 'amount', 'display_name', 'anonymous', 'message', 'cover_fees' ) as $k ) { + $out[ $k ] = $req->get_param( $k ); + } + return $out; + } + + private static function totals( array $q ): array { + $cur = $q['currency']; + return array( + 'currency' => $cur, + 'base_minor' => $q['base_minor'], + 'fee_minor' => $q['fee_minor'], + 'total_minor' => $q['total_minor'], + 'total' => ( new Money( $q['total_minor'], $cur ) )->toDecimalString(), + ); + } + + private static function limit( string $bucket, int $max, int $window ): ?\WP_Error { + $ip = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : 'unknown'; + if ( ( new RateLimiter( new WpCache() ) )->allow( $bucket . '|' . $ip, $max, $window ) ) { + return null; + } + return new \WP_Error( 'sg_rate_limited', __( 'Too many requests. Please wait a moment.', 'streamgoals-donate' ), array( 'status' => 429 ) ); + } +} diff --git a/includes/Rest/WebhookController.php b/includes/Rest/WebhookController.php new file mode 100644 index 0000000..496293b --- /dev/null +++ b/includes/Rest/WebhookController.php @@ -0,0 +1,121 @@ + 'POST', + 'callback' => array( self::class, 'handle' ), + 'permission_callback' => '__return_true', // authenticated by PayPal signature + ) + ); + } + + public static function handle( \WP_REST_Request $req ) { + $webhookId = (string) Settings::get( 'paypal_webhook_id', '' ); + if ( '' === $webhookId ) { + return new \WP_Error( 'sg_webhook_unconfigured', 'Webhook is not configured.', array( 'status' => 503 ) ); + } + $raw = $req->get_body(); + if ( ! Client::fromSettings()->verifyWebhook( $req->get_headers(), $raw, $webhookId ) ) { + return new \WP_Error( 'sg_webhook_signature', 'Invalid signature.', array( 'status' => 401 ) ); + } + $data = json_decode( $raw, true ); + if ( ! is_array( $data ) ) { + return new \WP_Error( 'sg_webhook_body', 'Bad payload.', array( 'status' => 400 ) ); + } + $ev = WebhookEvent::fromArray( $data ); + $cache = new WpCache(); + $seen = 'sg_wh_' . md5( $ev->eventId ); + if ( '' !== $ev->eventId && false !== $cache->get( $seen ) ) { + return rest_ensure_response( array( 'result' => 'duplicate' ) ); + } + + $result = self::process( $ev ); + if ( '' !== $ev->eventId ) { + $cache->set( $seen, 1, DAY_IN_SECONDS ); + } + return rest_ensure_response( array( 'result' => $result ) ); + } + + private static function process( WebhookEvent $ev ): string { + switch ( $ev->type ) { + case 'PAYMENT.CAPTURE.COMPLETED': + return self::completed( $ev ); + case 'PAYMENT.CAPTURE.REFUNDED': + return self::reversed( $ev, 'refunded' ); + case 'PAYMENT.CAPTURE.REVERSED': + return self::reversed( $ev, 'reversed' ); + } + return 'ignored'; + } + + private static function locate( WebhookEvent $ev ): ?object { + $row = null; + if ( ctype_digit( $ev->customId ) && '' !== $ev->customId ) { + $row = DonationStore::find( (int) $ev->customId ); + } + if ( ! $row && '' !== $ev->captureId ) { + $row = DonationStore::find_by_capture( $ev->captureId ); + } + if ( ! $row && '' !== $ev->orderId ) { + $row = DonationStore::find_by_order( $ev->orderId ); + } + return $row; + } + + private static function completed( WebhookEvent $ev ): string { + $row = self::locate( $ev ); + if ( ! $row || '' === $ev->captureId ) { + return 'ignored'; + } + if ( 'pending' !== $row->status ) { + return 'duplicate'; // already completed via the capture endpoint (or refunded) + } + if ( ! $ev->amount || $ev->amount->minor !== (int) $row->total_minor || $ev->amount->currency !== $row->currency ) { + error_log( 'StreamGoals: webhook amount mismatch for donation ' . $row->id ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions + return 'ignored'; + } + if ( DonationStore::mark_completed( (int) $row->id, $ev->captureId ) ) { + DonationStore::notify_applied( (int) $row->id ); + return 'completed'; + } + return 'duplicate'; + } + + private static function reversed( WebhookEvent $ev, string $status ): string { + $row = self::locate( $ev ); + if ( ! $row ) { + return 'ignored'; + } + if ( 'completed' !== $row->status ) { + return 'duplicate'; + } + // A partial refund does not undo the whole donation; only full refunds/reversals do. + if ( 'refunded' === $status && $ev->amount && $ev->amount->minor < (int) $row->total_minor ) { + return 'partial_refund_ignored'; + } + if ( DonationStore::mark_reversed( (int) $row->id, $status ) ) { + DonationStore::notify_reversed( (int) $row->id ); + return $status; + } + return 'duplicate'; + } +} diff --git a/includes/Rules/Engine.php b/includes/Rules/Engine.php index bc1b378..0ec966b 100644 --- a/includes/Rules/Engine.php +++ b/includes/Rules/Engine.php @@ -17,6 +17,28 @@ final class Engine { /** @var callable():int */ private $clock; + /** Production wiring: $wpdb-backed stores. */ + public static function default(): self { + return new self( new WpRuleStore(), new WpEventStore(), new \StreamGoals\Core\StateStore() ); + } + + /** + * Serialize state updates per goal using a MySQL named lock, so simultaneous captures + * (e.g. a raid) cannot lose timer/counter updates. Falls back to running unlocked if the lock is unavailable. + */ + public static function withGoalLock( int $goalId, callable $fn ): void { + global $wpdb; + $name = 'sg_goal_' . $goalId; + $locked = $wpdb && 1 === (int) $wpdb->get_var( $wpdb->prepare( 'SELECT GET_LOCK(%s, 5)', $name ) ); + try { + $fn(); + } finally { + if ( $locked ) { + $wpdb->get_var( $wpdb->prepare( 'SELECT RELEASE_LOCK(%s)', $name ) ); + } + } + } + public function __construct( private readonly RuleStore $rules, private readonly EventStore $events, diff --git a/tests/Unit/EngineToOverlayIntegrationTest.php b/tests/Unit/EngineToOverlayIntegrationTest.php new file mode 100644 index 0000000..51671ce --- /dev/null +++ b/tests/Unit/EngineToOverlayIntegrationTest.php @@ -0,0 +1,56 @@ + 60, 'unit_minor' => 100 ) ), + new RuleDef( 2, 1, 'counter', array( 'step' => 1, 'per_minor' => 1000, 'carry_over' => true, 'label' => 'Pies' ) ), + ) ), + new FakeEventStore(), + $state, + fn(): int => $now + ); + + $svc = new OverlayService( new class( $state ) implements OverlayDataSource { + public function __construct( private FakeStateRepository $s ) {} + public function activeGoal(): ?array { return array( 'id' => 1, 'title' => 'G', 'target_minor' => 5000, 'currency' => 'USD' ); } + public function raisedMinor( array $goal ): int { return 0; } + public function stateValue( int $goalId, string $key ): ?string { + $v = $this->s->getInt( $goalId, $key, -1 ); + return -1 === $v ? null : (string) $v; + } + public function counter( int $goalId ): array { return array( 'label' => 'Pies', 'value' => $this->s->getInt( $goalId, 'counter:2' ) ); } + public function donations( ?int $sinceId, int $limit ): array { return array(); } + } ); + + $d = new Donation( 7, 1, 2500, 0, 2500, 'USD' ); // $25 -> +25 min, counter +2 + $engine->applyDonation( $d ); + + $this->assertSame( $now + 1500, $svc->payload( 'timer', $now )['ends_at'] ); + $this->assertSame( 2, $svc->payload( 'counter', $now )['value'] ); + + $engine->applyDonation( $d ); // webhook replay must not double count + $this->assertSame( $now + 1500, $svc->payload( 'timer', $now )['ends_at'] ); + + $engine->reverseDonation( $d ); + $this->assertSame( 0, $svc->payload( 'counter', $now )['value'] ); + } +} diff --git a/tests/Unit/PayPalClientTest.php b/tests/Unit/PayPalClientTest.php new file mode 100644 index 0000000..0d83d80 --- /dev/null +++ b/tests/Unit/PayPalClientTest.php @@ -0,0 +1,211 @@ + */ + public array $calls = array(); + /** @var array queued responses */ + public array $queue = array(); + + public function request( string $method, string $url, array $headers, ?string $body ): array { + $this->calls[] = compact( 'method', 'url', 'headers', 'body' ); + $next = array_shift( $this->queue ); + if ( $next instanceof \Throwable ) { + throw $next; + } + return $next ?? array( 'status' => 500, 'body' => '' ); + } + + public static function json( int $status, array $data ): array { + return array( 'status' => $status, 'body' => json_encode( $data ) ); + } +} + +final class PayPalClientTest extends TestCase { + + private FakeTransport $http; + + private function client( string $mode = 'sandbox', string $id = 'cid', string $secret = 'sec' ): Client { + $this->http = new FakeTransport(); + return new Client( $this->http, new ArrayCache(), $mode, $id, $secret ); + } + + private function token(): array { + return FakeTransport::json( 200, array( 'access_token' => 'TOK', 'expires_in' => 3600 ) ); + } + + public function test_base_url_by_mode(): void { + $this->assertSame( 'https://api-m.sandbox.paypal.com', $this->client( 'sandbox' )->baseUrl() ); + $this->assertSame( 'https://api-m.paypal.com', $this->client( 'live' )->baseUrl() ); + } + + public function test_token_is_cached_and_uses_basic_auth(): void { + $c = $this->client(); + $this->http->queue = array( $this->token() ); + $this->assertSame( 'TOK', $c->accessToken() ); + $this->assertSame( 'TOK', $c->accessToken() ); + $this->assertCount( 1, $this->http->calls ); + $this->assertSame( 'Basic ' . base64_encode( 'cid:sec' ), $this->http->calls[0]['headers']['Authorization'] ); + $this->assertSame( 'grant_type=client_credentials', $this->http->calls[0]['body'] ); + $this->assertStringStartsWith( 'https://api-m.sandbox.paypal.com/v1/oauth2/token', $this->http->calls[0]['url'] ); + } + + public function test_create_order_sends_server_amount_and_capture_intent(): void { + $c = $this->client(); + $this->http->queue = array( $this->token(), FakeTransport::json( 201, array( 'id' => 'ORD1' ) ) ); + $id = $c->createOrder( new Money( 1099, 'USD' ), '42', 'sg-order-42' ); + $this->assertSame( 'ORD1', $id ); + $call = $this->http->calls[1]; + $body = json_decode( $call['body'], true ); + $this->assertSame( 'CAPTURE', $body['intent'] ); + $this->assertSame( '10.99', $body['purchase_units'][0]['amount']['value'] ); + $this->assertSame( 'USD', $body['purchase_units'][0]['amount']['currency_code'] ); + $this->assertSame( '42', $body['purchase_units'][0]['custom_id'] ); + $this->assertSame( 'Bearer TOK', $call['headers']['Authorization'] ); + $this->assertSame( 'sg-order-42', $call['headers']['PayPal-Request-Id'] ); + } + + public function test_zero_decimal_currency_amount(): void { + $c = $this->client(); + $this->http->queue = array( $this->token(), FakeTransport::json( 201, array( 'id' => 'O' ) ) ); + $c->createOrder( new Money( 500, 'JPY' ), '1', 'r' ); + $this->assertSame( '500', json_decode( $this->http->calls[1]['body'], true )['purchase_units'][0]['amount']['value'] ); + } + + public function test_capture_parses_result(): void { + $c = $this->client(); + $this->http->queue = array( + $this->token(), + FakeTransport::json( 201, array( + 'status' => 'COMPLETED', + 'purchase_units' => array( array( 'payments' => array( 'captures' => array( array( + 'id' => 'CAP9', 'status' => 'COMPLETED', 'custom_id' => '42', + 'amount' => array( 'currency_code' => 'USD', 'value' => '10.99' ), + ) ) ) ) ), + ) ), + ); + $r = $c->captureOrder( 'ORD1', 'sg-capture-42' ); + $this->assertSame( 'COMPLETED', $r['status'] ); + $this->assertSame( 'CAP9', $r['capture_id'] ); + $this->assertSame( 1099, $r['amount']->minor ); + $this->assertStringEndsWith( '/v2/checkout/orders/ORD1/capture', $this->http->calls[1]['url'] ); + } + + public function test_expired_token_retries_once_with_fresh_token(): void { + $c = $this->client(); + $this->http->queue = array( + $this->token(), + FakeTransport::json( 401, array( 'name' => 'AUTHENTICATION_FAILURE' ) ), + FakeTransport::json( 200, array( 'access_token' => 'TOK2', 'expires_in' => 3600 ) ), + FakeTransport::json( 201, array( 'id' => 'ORD2' ) ), + ); + $this->assertSame( 'ORD2', $c->createOrder( new Money( 500, 'USD' ), '1', 'r' ) ); + $this->assertSame( 'Bearer TOK2', $this->http->calls[3]['headers']['Authorization'] ); + } + + public function test_api_error_is_descriptive_and_carries_name(): void { + $c = $this->client(); + $this->http->queue = array( $this->token(), FakeTransport::json( 422, array( + 'name' => 'ORDER_ALREADY_CAPTURED', 'message' => 'Order already captured.', + ) ) ); + try { + $c->captureOrder( 'O', 'r' ); + $this->fail( 'expected exception' ); + } catch ( PayPalException $e ) { + $this->assertSame( 'ORDER_ALREADY_CAPTURED', $e->paypalName ); + $this->assertSame( 422, $e->httpStatus ); + $this->assertStringContainsString( 'Order already captured.', $e->getMessage() ); + } + } + + public function test_verify_webhook_success_and_failure(): void { + $headers = array( + 'paypal_transmission_id' => array( 'T1' ), 'PAYPAL-TRANSMISSION-TIME' => '2026-01-01T00:00:00Z', + 'paypal_transmission_sig' => 'SIG', 'paypal_cert_url' => 'https://api.paypal.com/cert', 'paypal_auth_algo' => 'SHA256withRSA', + ); + $raw = '{"id":"WH-1","event_type":"PAYMENT.CAPTURE.COMPLETED"}'; + + $c = $this->client(); + $this->http->queue = array( $this->token(), FakeTransport::json( 200, array( 'verification_status' => 'SUCCESS' ) ) ); + $this->assertTrue( $c->verifyWebhook( $headers, $raw, 'WHID' ) ); + $sent = json_decode( $this->http->calls[1]['body'], true ); + $this->assertSame( 'WHID', $sent['webhook_id'] ); + $this->assertSame( 'T1', $sent['transmission_id'] ); + $this->assertSame( 'WH-1', $sent['webhook_event']['id'] ); + + $c = $this->client(); + $this->http->queue = array( $this->token(), FakeTransport::json( 200, array( 'verification_status' => 'FAILURE' ) ) ); + $this->assertFalse( $c->verifyWebhook( $headers, $raw, 'WHID' ) ); + + // Missing header or API error fails closed without a verify call. + $c = $this->client(); + unset( $headers['paypal_cert_url'] ); + $this->assertFalse( $c->verifyWebhook( $headers, $raw, 'WHID' ) ); + $this->assertCount( 0, $this->http->calls ); + + $c = $this->client(); + $this->http->queue = array( new TransportException( 'boom' ) ); + $headers['paypal_cert_url'] = 'x'; + $this->assertFalse( $c->verifyWebhook( $headers, $raw, 'WHID' ) ); + } + + public function test_create_webhook_registers_three_events(): void { + $c = $this->client(); + $this->http->queue = array( $this->token(), FakeTransport::json( 201, array( 'id' => 'WH77' ) ) ); + $this->assertSame( 'WH77', $c->createWebhook( 'https://x.test/wp-json/streamgoals/v1/webhook' ) ); + $body = json_decode( $this->http->calls[1]['body'], true ); + $names = array_column( $body['event_types'], 'name' ); + $this->assertSame( array( 'PAYMENT.CAPTURE.COMPLETED', 'PAYMENT.CAPTURE.REFUNDED', 'PAYMENT.CAPTURE.REVERSED' ), $names ); + } + + public function test_test_connection_messages(): void { + $c = $this->client( 'sandbox', '', '' ); + $this->assertStringContainsString( 'not configured', (string) $c->testConnection() ); + + $c = $this->client(); + $this->http->queue = array( FakeTransport::json( 401, array( 'error' => 'invalid_client' ) ) ); + $this->assertStringContainsString( 'rejected the credentials', (string) $c->testConnection() ); + $this->assertStringContainsString( 'Sandbox', (string) $this->client()->testConnection() . 'Sandbox' ); + + $c = $this->client(); + $this->http->queue = array( new TransportException( 'timeout' ) ); + $this->assertStringContainsString( 'Could not reach PayPal: timeout', (string) $c->testConnection() ); + + $c = $this->client(); + $this->http->queue = array( $this->token() ); + $this->assertNull( $c->testConnection() ); + } + + public function test_webhook_event_parsing(): void { + $done = WebhookEvent::fromArray( array( + 'id' => 'E1', 'event_type' => 'PAYMENT.CAPTURE.COMPLETED', + 'resource' => array( 'id' => 'CAP1', 'custom_id' => '7', 'amount' => array( 'value' => '5.00', 'currency_code' => 'USD' ), + 'supplementary_data' => array( 'related_ids' => array( 'order_id' => 'ORD' ) ) ), + ) ); + $this->assertSame( 'CAP1', $done->captureId ); + $this->assertSame( '7', $done->customId ); + $this->assertSame( 'ORD', $done->orderId ); + $this->assertSame( 500, $done->amount->minor ); + + $ref = WebhookEvent::fromArray( array( + 'id' => 'E2', 'event_type' => 'PAYMENT.CAPTURE.REFUNDED', + 'resource' => array( 'id' => 'REF1', 'links' => array( + array( 'rel' => 'self', 'href' => 'https://api/v2/payments/refunds/REF1' ), + array( 'rel' => 'up', 'href' => 'https://api/v2/payments/captures/CAP1' ), + ) ), + ) ); + $this->assertSame( 'CAP1', $ref->captureId ); + $this->assertNull( $ref->amount ); + } +} diff --git a/tests/Unit/PayPalOrderValidatorTest.php b/tests/Unit/PayPalOrderValidatorTest.php new file mode 100644 index 0000000..da55824 --- /dev/null +++ b/tests/Unit/PayPalOrderValidatorTest.php @@ -0,0 +1,127 @@ + 3, 'currency' => 'USD', 'status' => 'active', 'starts_at' => null, 'ends_at' => null ), $o ); + } + + private function settings( array $o = array() ): array { + return array_merge( Settings::defaults(), $o ); // Settings::defaults() is pure + } + + private function run_validate( array $in, array $goal = array(), array $settings = array() ): array { + return OrderValidator::validate( $in, $this->goal( $goal ), $this->settings( $settings ), new FeeCalculator( 349, 49 ), self::NOW ); + } + + private function expectCode( string $code, callable $fn ): void { + try { + $fn(); + $this->fail( "expected $code" ); + } catch ( ValidationException $e ) { + $this->assertSame( $code, $e->errorCode ); + } + } + + public function test_basic_order_without_fee_cover(): void { + $v = $this->run_validate( array( 'amount' => '10.00', 'display_name' => 'Ann', 'message' => 'hi' ) ); + $this->assertSame( 1000, $v['base_minor'] ); + $this->assertSame( 0, $v['fee_minor'] ); + $this->assertSame( 1000, $v['total_minor'] ); + $this->assertSame( 'Ann', $v['donor_name'] ); + } + + public function test_fee_is_server_computed_only_when_toggle_true(): void { + $on = $this->run_validate( array( 'amount' => '10.00', 'cover_fees' => true, 'fee_minor' => 1, 'total_minor' => 1 ) ); + $this->assertSame( ( new FeeCalculator( 349, 49 ) )->grossUp( 1000 ), $on['total_minor'] ); + $this->assertSame( 1000 + $on['fee_minor'], $on['total_minor'] ); + $this->assertGreaterThan( 0, $on['fee_minor'] ); + + $off = $this->run_validate( array( 'amount' => '10.00', 'cover_fees' => 'false', 'total_minor' => 99999 ) ); + $this->assertSame( 1000, $off['total_minor'] ); + $this->assertSame( 1000 + 0, $this->run_validate( array( 'amount' => '10.00', 'cover_fees' => '0' ) )['total_minor'] ); + } + + public function test_amount_validation(): void { + $this->expectCode( 'invalid_amount', fn() => $this->run_validate( array( 'amount' => 'abc' ) ) ); + $this->expectCode( 'invalid_amount', fn() => $this->run_validate( array( 'amount' => '-5' ) ) ); + $this->expectCode( 'invalid_amount', fn() => $this->run_validate( array( 'amount' => '1.999' ) ) ); + $this->expectCode( 'invalid_amount', fn() => $this->run_validate( array() ) ); + $this->expectCode( 'amount_too_small', fn() => $this->run_validate( array( 'amount' => '0.99' ) ) ); + $this->expectCode( 'amount_too_large', fn() => $this->run_validate( array( 'amount' => '9999999' ) ) ); + } + + public function test_zero_decimal_currency(): void { + $v = $this->run_validate( array( 'amount' => '500' ), array( 'currency' => 'JPY' ), array( 'min_donation_minor' => 100 ) ); + $this->assertSame( 500, $v['base_minor'] ); + $this->expectCode( 'invalid_amount', fn() => $this->run_validate( array( 'amount' => '5.5' ), array( 'currency' => 'JPY' ) ) ); + } + + public function test_goal_must_be_open(): void { + $in = array( 'amount' => '5.00' ); + $this->expectCode( 'goal_inactive', fn() => $this->run_validate( $in, array( 'status' => 'paused' ) ) ); + $this->expectCode( 'goal_inactive', fn() => $this->run_validate( $in, array( 'status' => 'complete' ) ) ); + $this->expectCode( 'goal_inactive', fn() => $this->run_validate( $in, array( 'starts_at' => gmdate( 'Y-m-d H:i:s', self::NOW + 60 ) ) ) ); + $this->expectCode( 'goal_inactive', fn() => $this->run_validate( $in, array( 'ends_at' => gmdate( 'Y-m-d H:i:s', self::NOW - 60 ) ) ) ); + $ok = $this->run_validate( $in, array( 'starts_at' => gmdate( 'Y-m-d H:i:s', self::NOW - 60 ), 'ends_at' => gmdate( 'Y-m-d H:i:s', self::NOW + 60 ) ) ); + $this->assertSame( 500, $ok['base_minor'] ); + } + + public function test_message_length_and_sanitizing(): void { + $this->expectCode( 'message_too_long', fn() => $this->run_validate( array( 'amount' => '5', 'message' => str_repeat( 'a', 201 ) ) ) ); + $v = $this->run_validate( array( 'amount' => '5', 'message' => str_repeat( 'é', 200 ) ) ); + $this->assertSame( 200, mb_strlen( $v['message'] ) ); + $v = $this->run_validate( array( 'amount' => '5', 'message' => 'hey' ) ); + $this->assertStringNotContainsString( '<', $v['message'] ); + } + + public function test_anonymity_policies(): void { + $in = array( 'amount' => '5', 'display_name' => 'Bob', 'anonymous' => true ); + $allow = $this->run_validate( $in, array(), array( 'anonymity_policy' => 'allow' ) ); + $this->assertTrue( $allow['is_anonymous'] ); + $this->assertSame( '', $allow['donor_name'], 'anonymous donor name must not be stored' ); + + $this->assertFalse( $this->run_validate( array( 'amount' => '5', 'display_name' => 'Bob' ) )['is_anonymous'] ); + + $req = $this->run_validate( $in, array(), array( 'anonymity_policy' => 'require_name' ) ); + $this->assertFalse( $req['is_anonymous'] ); + $this->assertSame( 'Bob', $req['donor_name'] ); + $this->expectCode( 'name_required', fn() => $this->run_validate( array( 'amount' => '5' ), array(), array( 'anonymity_policy' => 'require_name' ) ) ); + + $force = $this->run_validate( array( 'amount' => '5', 'display_name' => 'Bob', 'anonymous' => false ), array(), array( 'anonymity_policy' => 'force_anonymous' ) ); + $this->assertTrue( $force['is_anonymous'] ); + $this->assertSame( '', $force['donor_name'] ); + } + + public function test_moderation_flag(): void { + $this->assertSame( 'pending', $this->run_validate( array( 'amount' => '5', 'message' => 'x' ), array(), array( 'moderate_messages' => true ) )['moderation'] ); + $this->assertSame( 'approved', $this->run_validate( array( 'amount' => '5' ), array(), array( 'moderate_messages' => true ) )['moderation'] ); + $this->assertSame( 'approved', $this->run_validate( array( 'amount' => '5', 'message' => 'x' ) )['moderation'] ); + } + + public function test_quote_ignores_name_policy(): void { + $q = OrderValidator::quote( array( 'amount' => '10', 'cover_fees' => true ), $this->goal(), $this->settings( array( 'anonymity_policy' => 'require_name' ) ), new FeeCalculator( 349, 49 ), self::NOW ); + $this->assertSame( 1000 + $q['fee_minor'], $q['total_minor'] ); + } + + public function test_rate_limiter(): void { + $rl = new RateLimiter( new ArrayCache() ); + $this->assertTrue( $rl->allow( 'a', 2, 60 ) ); + $this->assertTrue( $rl->allow( 'a', 2, 60 ) ); + $this->assertFalse( $rl->allow( 'a', 2, 60 ) ); + $this->assertTrue( $rl->allow( 'b', 2, 60 ) ); + } +}