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 <noreply@anthropic.com>
This commit is contained in:
shadowdaoandClaude Sonnet 5.5 committed 2026-11-15 08:47:00 -08:00
1 parent 65082fb2f5
commit 589e84f28b
21 files changed
+1659

No files matched your search

+23
View File
@@ -0,0 +1,23 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\PayPal;
/** In-memory cache (tests, or a fallback). Ignores TTL expiry within a request. */
final class ArrayCache implements Cache {
/** @var array<string,mixed> */
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 ] );
}
}
+14
View File
@@ -0,0 +1,14 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\PayPal;
/** Tiny key/value TTL cache seam (transients in production). */
interface Cache {
public function get( string $key ): mixed;
public function set( string $key, mixed $value, int $ttl ): void;
public function delete( string $key ): void;
}
+250
View File
@@ -0,0 +1,250 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\PayPal;
use StreamGoals\Core\Money;
use StreamGoals\Core\Settings;
/** PayPal REST v1/v2 client. All HTTP goes through an injected HttpTransport. */
final class Client {
public const WEBHOOK_EVENTS = array( 'PAYMENT.CAPTURE.COMPLETED', 'PAYMENT.CAPTURE.REFUNDED', 'PAYMENT.CAPTURE.REVERSED' );
public function __construct(
private HttpTransport $http,
private Cache $cache,
private string $mode,
private string $clientId,
private string $secret
) {}
public static function fromSettings(): self {
$s = Settings::all();
return new self( new WpTransport(), new WpCache(), (string) $s['paypal_mode'], (string) $s['paypal_client_id'], (string) $s['paypal_client_secret'] );
}
public function baseUrl(): string {
return 'live' === $this->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<string,mixed> $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<string,string> $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;
}
}
+123
View File
@@ -0,0 +1,123 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\PayPal;
/** $wpdb access for sg_donations / sg_goals used by the donate flow. WordPress-only. */
final class DonationStore {
private static function t( string $name ): string {
global $wpdb;
return $wpdb->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
}
}
}
+15
View File
@@ -0,0 +1,15 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\PayPal;
/** Minimal HTTP seam so the PayPal client is testable without WordPress. */
interface HttpTransport {
/**
* @param array<string,string> $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;
}
+131
View File
@@ -0,0 +1,131 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\PayPal;
use StreamGoals\Core\FeeCalculator;
use StreamGoals\Core\Money;
/**
* Pure validation + total computation for a new donation order. The server is the
* only authority on the total: client-supplied totals/fees are never read.
*/
final class OrderValidator {
public const NAME_MAX = 100;
/**
* @param array $input Raw client params (goal_id, amount, display_name, anonymous, message, cover_fees).
* @param array $goal sg_goals row as array (id, currency, status, starts_at, ends_at).
* @param array $settings Settings::all()-shaped array.
* @return array{goal_id:int,currency:string,base_minor:int,fee_minor:int,total_minor:int,donor_name:string,is_anonymous:bool,message:string,cover_fees:bool,moderation:string}
* @throws ValidationException
*/
public static function validate( array $input, array $goal, array $settings, FeeCalculator $fees, int $nowTs ): array {
$q = self::quote( $input, $goal, $settings, $fees, $nowTs );
$base = $q['base_minor'];
$currency = $q['currency'];
$fee = $q['fee_minor'];
$cover = $q['cover_fees'];
$message = self::clean( $input['message'] ?? '' );
$maxLen = max( 0, min( 500, (int) ( $settings['message_max_length'] ?? 200 ) ) );
if ( mb_strlen( $message ) > $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 );
}
}
+12
View File
@@ -0,0 +1,12 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\PayPal;
/** An error talking to PayPal. getMessage() is safe to show to an admin. */
final class PayPalException extends \RuntimeException {
public function __construct( string $message, public readonly int $httpStatus = 0, public readonly string $paypalName = '' ) {
parent::__construct( $message );
}
}
+21
View File
@@ -0,0 +1,21 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\PayPal;
/** Fixed-window counter. Best-effort (non-atomic) which is fine for abuse throttling. */
final class RateLimiter {
public function __construct( private Cache $cache ) {}
/** Returns true if the call is allowed, false if the limit is exceeded. */
public function allow( string $key, int $limit, int $windowSeconds ): bool {
$k = 'sg_rl_' . md5( $key );
$count = (int) $this->cache->get( $k );
if ( $count >= $limit ) {
return false;
}
$this->cache->set( $k, $count + 1, $windowSeconds );
return true;
}
}
+6
View File
@@ -0,0 +1,6 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\PayPal;
final class TransportException extends \RuntimeException {}
+11
View File
@@ -0,0 +1,11 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\PayPal;
final class ValidationException extends \InvalidArgumentException {
public function __construct( public readonly string $errorCode, string $message, public readonly int $status = 400 ) {
parent::__construct( $message );
}
}
+50
View File
@@ -0,0 +1,50 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\PayPal;
use StreamGoals\Core\Money;
/** Pure extraction of the fields we care about from a PayPal webhook event. */
final class WebhookEvent {
public function __construct(
public readonly string $eventId,
public readonly string $type,
public readonly string $captureId,
public readonly string $customId,
public readonly string $orderId,
public readonly ?Money $amount
) {}
public static function fromArray( array $event ): self {
$r = is_array( $event['resource'] ?? null ) ? $event['resource'] : array();
$type = (string) ( $event['event_type'] ?? '' );
$capId = (string) ( $r['id'] ?? '' );
// REFUNDED/REVERSED resources are refund objects whose "up" link points at the capture.
if ( 'PAYMENT.CAPTURE.COMPLETED' !== $type ) {
foreach ( (array) ( $r['links'] ?? array() ) as $l ) {
if ( is_array( $l ) && 'up' === ( $l['rel'] ?? '' ) && preg_match( '#/captures/([A-Za-z0-9\-_]+)$#', (string) ( $l['href'] ?? '' ), $m ) ) {
$capId = $m[1];
break;
}
}
}
$amount = null;
if ( isset( $r['amount']['value'], $r['amount']['currency_code'] ) ) {
try {
$amount = Money::fromDecimalString( (string) $r['amount']['value'], (string) $r['amount']['currency_code'] );
} catch ( \InvalidArgumentException $e ) {
$amount = null;
}
}
return new self(
(string) ( $event['id'] ?? '' ),
$type,
$capId,
(string) ( $r['custom_id'] ?? '' ),
(string) ( $r['supplementary_data']['related_ids']['order_id'] ?? '' ),
$amount
);
}
}
+19
View File
@@ -0,0 +1,19 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\PayPal;
final class WpCache implements Cache {
public function get( string $key ): mixed {
return get_transient( $key );
}
public function set( string $key, mixed $value, int $ttl ): void {
set_transient( $key, $value, $ttl );
}
public function delete( string $key ): void {
delete_transient( $key );
}
}
+27
View File
@@ -0,0 +1,27 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\PayPal;
/** Production transport backed by wp_remote_request. */
final class WpTransport implements HttpTransport {
public function request( string $method, string $url, array $headers, ?string $body ): array {
$args = array(
'method' => $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 ),
);
}
}
+230
View File
@@ -0,0 +1,230 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Rest;
use StreamGoals\Core\Money;
use StreamGoals\Core\Settings;
use StreamGoals\PayPal\Client;
use StreamGoals\PayPal\DonationStore;
use StreamGoals\PayPal\OrderValidator;
use StreamGoals\PayPal\PayPalException;
use StreamGoals\PayPal\RateLimiter;
use StreamGoals\PayPal\ValidationException;
use StreamGoals\PayPal\WpCache;
/** Public donate endpoints + the [streamgoals_donate] shortcode. */
final class DonateController {
private const NS = 'streamgoals/v1';
public static function register(): void {
add_action( 'rest_api_init', array( self::class, 'routes' ) );
add_shortcode( 'streamgoals_donate', array( self::class, 'shortcode' ) );
}
public static function routes(): void {
register_rest_route(
self::NS,
'/orders',
array(
'methods' => 'POST',
'callback' => array( self::class, 'create_order' ),
'permission_callback' => '__return_true',
)
);
register_rest_route(
self::NS,
'/orders/(?P<id>[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 '<p class="sg-donate-unavailable">' . esc_html__( 'Donations are not available right now.', 'streamgoals-donate' ) . '</p>';
}
$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 '<p class="sg-donate-unavailable">' . esc_html__( 'There is no active goal to donate to right now.', 'streamgoals-donate' ) . '</p>';
}
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 '<div class="sg-donate" data-goal="' . esc_attr( (string) $pinned ) . '"></div>';
}
/* ------------------------------------------------------------- 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 ) );
}
}
+121
View File
@@ -0,0 +1,121 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Rest;
use StreamGoals\Core\Settings;
use StreamGoals\PayPal\Client;
use StreamGoals\PayPal\DonationStore;
use StreamGoals\PayPal\WebhookEvent;
use StreamGoals\PayPal\WpCache;
/** PayPal webhook receiver. Signature is verified through PayPal's API before anything is trusted. */
final class WebhookController {
public static function register(): void {
add_action( 'rest_api_init', array( self::class, 'routes' ) );
}
public static function routes(): void {
register_rest_route(
'streamgoals/v1',
'/webhook',
array(
'methods' => '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';
}
}
+22
View File
@@ -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,