2026-11-15 08:47:00 -08:00
<? php
declare ( strict_types = 1 );
namespace StreamGoals\Rest ;
2026-11-15 12:53:07 -08:00
use StreamGoals\Core\GoalTargetPolicy ;
2026-11-15 08:47:00 -08:00
use StreamGoals\Core\Money ;
use StreamGoals\Core\Settings ;
2026-11-15 10:20:53 -08:00
use StreamGoals\PayPal\CaptureFinalizer ;
2026-11-15 08:47:00 -08:00
use StreamGoals\PayPal\Client ;
use StreamGoals\PayPal\DonationStore ;
use StreamGoals\PayPal\OrderValidator ;
use StreamGoals\PayPal\PayPalException ;
use StreamGoals\PayPal\RateLimiter ;
2026-11-15 14:07:44 -08:00
use StreamGoals\PayPal\RequestId ;
2026-11-15 08:47:00 -08:00
use StreamGoals\PayPal\ValidationException ;
use StreamGoals\PayPal\WpCache ;
/** Public donate endpoints + the [streamgoals_donate] shortcode. */
final class DonateController {
private const NS = 'streamgoals/v1' ;
2026-11-15 14:07:44 -08:00
/** Generous site-wide ceiling for POST /orders (all visitors together). */
public const GLOBAL_ORDERS_PER_MIN = 120 ;
2026-11-15 08:47:00 -08:00
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 ;
}
2026-11-15 14:07:44 -08:00
// Site-wide ceiling (checked after the per-visitor limit so one noisy visitor cannot burn it): rotating addresses
// (botnet, IPv6) still cannot flood the pending table or PayPal.
if ( ! ( new RateLimiter ( new WpCache () ) ) -> allow ( 'order|*global*' , self :: GLOBAL_ORDERS_PER_MIN , 60 ) ) {
return new \WP_Error ( 'sg_rate_limited' , __ ( 'Too many requests. Please wait a moment.' , 'streamgoals-donate' ), array ( 'status' => 429 ) );
}
2026-11-15 08:47:00 -08:00
$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 {
2026-11-15 14:07:44 -08:00
$orderId = Client :: fromSettings () -> createOrder ( new Money ( $v [ 'total_minor' ], $v [ 'currency' ] ), ( string ) $id , self :: request_id ( 'order' , $id ) );
2026-11-15 08:47:00 -08:00
} 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 {
2026-11-15 14:07:44 -08:00
$cap = Client :: fromSettings () -> captureOrder ( $orderId , self :: request_id ( 'capture' , ( int ) $row -> id , ( string ) $row -> created_at ) );
2026-11-15 08:47:00 -08:00
} 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 ) );
}
2026-11-15 10:20:53 -08:00
$res = CaptureFinalizer :: finalize (
$row ,
( string ) $cap [ 'status' ],
( string ) $cap [ 'capture_id' ],
$cap [ 'amount' ],
array ( DonationStore :: class , 'mark_completed' ),
2026-11-15 14:07:44 -08:00
array ( DonationStore :: class , 'notify_applied' ),
array ( DonationStore :: class , 'record_capture_id' )
2026-11-15 10:20:53 -08:00
);
if ( CaptureFinalizer :: PENDING === $res ) {
// PENDING capture (e-check/review) or amount mismatch: stay pending; the COMPLETED webhook finalizes it.
error_log ( 'StreamGoals: capture for donation ' . $row -> id . ' not finalized (status ' . $cap [ 'status' ] . '); awaiting webhook' ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
2026-11-15 08:47:00 -08:00
return new \WP_REST_Response ( array ( 'status' => 'processing' ), 202 );
}
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>' ;
}
2026-11-15 12:36:28 -08:00
$goals = array ();
$actions = self :: actions_by_goal ( array_map ( static fn ( $g ) => ( int ) $g [ 'id' ], DonationStore :: active_goals () ), \StreamGoals\Core\Settings :: effectiveMin ( ( int ) $s [ 'min_donation_minor' ] ) );
2026-11-15 08:47:00 -08:00
foreach ( DonationStore :: active_goals () as $g ) {
if ( $pinned && ( int ) $g [ 'id' ] !== $pinned ) {
continue ;
}
2026-11-15 13:09:18 -08:00
$next = self :: next_unlock ( $g );
$goals [] = ( null === $next ? array () : array ( 'nextUnlock' => $next ) ) + array (
2026-11-15 08:47:00 -08:00
'id' => ( int ) $g [ 'id' ],
'title' => ( string ) $g [ 'title' ],
'currency' => strtoupper ( ( string ) $g [ 'currency' ] ),
'exp' => Money :: exponent ( ( string ) $g [ 'currency' ] ),
2026-11-15 12:36:28 -08:00
'actions' => $actions [ ( int ) $g [ 'id' ] ] ?? array (),
2026-11-15 08:47:00 -08:00
);
}
if ( ! $goals ) {
2026-11-15 12:53:07 -08:00
$reached = $pinned ? DonationStore :: goal ( $pinned ) : null ;
$reached = $pinned ? ( $reached && GoalTargetPolicy :: isClosedAtTarget ( $reached ) ) : ( bool ) DonationStore :: reached_goals ();
if ( $reached ) {
return '<p class="sg-donate-unavailable sg-donate-reached">' . esc_html__ ( 'This goal has been reached - thank you for your support!' , 'streamgoals-donate' ) . '</p>' ;
}
2026-11-15 08:47:00 -08:00
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' ],
2026-11-15 10:41:29 -08:00
'minMinor' => \StreamGoals\Core\Settings :: effectiveMin ( ( int ) $s [ 'min_donation_minor' ] ),
2026-11-15 08:47:00 -08:00
'messageMax' => min ( 500 , ( int ) $s [ 'message_max_length' ] ),
2026-11-15 13:34:54 -08:00
'notice' => ( string ) ( $s [ 'donation_notice' ] ?? '' ),
2026-11-15 11:40:06 -08:00
'disableFunding' => array_values ( array_filter ( array ( empty ( $s [ 'funding_paylater' ] ) ? 'paylater' : '' , empty ( $s [ 'funding_card' ] ) ? 'card' : '' ) ) ),
2026-11-15 08:47:00 -08:00
'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' ),
2026-11-15 10:41:29 -08:00
'customAmount' => __ ( 'Or enter your own amount' , 'streamgoals-donate' ),
'customPlaceholder' => __ ( 'Other amount' , 'streamgoals-donate' ),
2026-11-15 12:36:28 -08:00
/* translators: %s: formatted amount, e.g. $5.00 */
'everyLabel' => __ ( 'Every %s' , 'streamgoals-donate' ),
2026-11-15 13:09:18 -08:00
/* translators: 1: item/unlock title, 2: formatted amount still needed, e.g. $106.00 */
'nextUnlock' => __ ( 'Next unlock: %1$s — %2$s to go' , 'streamgoals-donate' ),
2026-11-15 12:36:28 -08:00
'actionsHint' => __ ( 'Pick a reward, or enter your own amount below.' , 'streamgoals-donate' ),
2026-11-15 10:41:29 -08:00
/* translators: %s: formatted minimum amount, e.g. $1.00 */
'minHint' => __ ( 'Minimum donation: %s' , 'streamgoals-donate' ),
/* translators: %s: formatted minimum amount, e.g. $1.00 */
'belowMin' => __ ( 'The minimum donation is %s.' , 'streamgoals-donate' ),
'coverInfoLabel' => __ ( 'What does this mean?' , 'streamgoals-donate' ),
'coverInfo' => __ ( 'PayPal takes a small fee from every donation. Tick this box to add that fee to your total, so the full amount you chose reaches the streamer. It is optional.' , 'streamgoals-donate' ),
2026-11-15 08:47:00 -08:00
),
);
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 */
2026-11-15 13:09:18 -08:00
/**
* "Next unlock" hint for a tiered goal: the current (first unreached) tier's title and the amount still needed, in minor units.
* Null for goals without tiers or with every tier reached. Computed when the page renders.
*
* @return array{title:string,remaining_minor:int}|null
*/
private static function next_unlock ( array $goal ) : ? array {
try {
global $wpdb ;
$tiers = ( new \StreamGoals\Tiers\TierRepository ( $wpdb ) ) -> forGoal ( ( int ) $goal [ 'id' ] );
$cur = $tiers ? \StreamGoals\Tiers\TierPolicy :: currentTier ( $tiers ) : null ;
if ( null === $cur ) {
return null ;
}
$raised = ( new \StreamGoals\Core\GoalRepository ( $wpdb ) ) -> raised_minor ( ( int ) $goal [ 'id' ] );
return array ( 'title' => ( string ) $cur [ 'title' ], 'remaining_minor' => max ( 1 , ( int ) $cur [ 'target_minor' ] - $raised ) );
} catch ( \Throwable $e ) {
return null ;
}
}
2026-11-15 12:36:28 -08:00
/**
* Enabled actions per goal id (rows with goal_id 0 apply to every goal), at or above the effective minimum.
* Public-safe fields only. One query; reads sg_actions directly.
*
* @param int[] $goalIds
* @return array<int,array<int,array<string,mixed>>>
*/
private static function actions_by_goal ( array $goalIds , int $min ) : array {
global $wpdb ;
$out = array ();
if ( ! $goalIds ) {
return $out ;
}
$rows = $wpdb -> get_results ( $wpdb -> prepare (
"SELECT id, goal_id, title, description, amount_minor, mode FROM { $wpdb -> prefix } sg_actions
WHERE enabled = 1 AND amount_minor >= %d ORDER BY sort, amount_minor, id LIMIT 500" ,
max ( 1 , $min )
), ARRAY_A );
foreach ( ( array ) $rows as $r ) {
$item = array (
'id' => ( int ) $r [ 'id' ],
'title' => ( string ) $r [ 'title' ],
'description' => ( string ) $r [ 'description' ],
'amount_minor' => ( int ) $r [ 'amount_minor' ],
'mode' => 'every' === $r [ 'mode' ] ? 'every' : 'exact' ,
);
foreach ( $goalIds as $gid ) {
if ( 0 === ( int ) $r [ 'goal_id' ] || ( int ) $r [ 'goal_id' ] === $gid ) {
$out [ $gid ][] = $item ;
}
}
}
return $out ;
}
2026-11-15 08:47:00 -08:00
/** 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 (),
);
}
2026-11-15 14:07:44 -08:00
/** Idempotency key, stable per donation (created_at is stored), not derivable from the id alone. */
private static function request_id ( string $kind , int $id , ? string $createdAt = null ) : string {
if ( null === $createdAt ) {
$row = DonationStore :: find ( $id );
$createdAt = $row ? ( string ) $row -> created_at : '' ;
}
return RequestId :: make ( $kind , $id , $createdAt , wp_salt ( 'auth' ) );
}
2026-11-15 08:47:00 -08:00
private static function limit ( string $bucket , int $max , int $window ) : ? \WP_Error {
2026-11-15 14:07:44 -08:00
$ip = self :: visitor_bucket ();
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 ) );
}
/** Rate-limit bucket for the current visitor (resolved IP, IPv6 collapsed to its /64). */
public static function visitor_bucket () : string {
2026-11-15 11:40:06 -08:00
$server = array ();
foreach ( array ( 'REMOTE_ADDR' , 'HTTP_CF_CONNECTING_IP' , 'HTTP_X_REAL_IP' , 'HTTP_X_FORWARDED_FOR' ) as $k ) {
if ( isset ( $_SERVER [ $k ] ) && is_string ( $_SERVER [ $k ] ) ) {
$server [ $k ] = sanitize_text_field ( wp_unslash ( $_SERVER [ $k ] ) );
}
}
2026-11-15 12:54:10 -08:00
$ip = \StreamGoals\Core\ClientIp :: resolve ( $server , ( string ) \StreamGoals\Core\Settings :: get ( 'visitor_ip_header' , 'auto' ), ( array ) apply_filters ( 'streamgoals_cloudflare_ranges' , array () ) );
2026-11-15 14:07:44 -08:00
return \StreamGoals\Core\ClientIp :: bucketKey ( $ip );
2026-11-15 08:47:00 -08:00
}
}