2026-11-15 08:47:00 -08:00
<? php
declare ( strict_types = 1 );
namespace StreamGoals\Rest ;
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 ;
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 ) );
}
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' ),
array ( DonationStore :: class , 'notify_applied' )
);
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>' ;
}
$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' ],
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 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' ),
/* 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 */
/** 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 {
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 ] ) );
}
}
$ip = \StreamGoals\Core\ClientIp :: resolve ( $server , ( string ) \StreamGoals\Core\Settings :: get ( 'visitor_ip_header' , '' ) );
2026-11-15 08:47:00 -08:00
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 ) );
}
}