Files
wp-donations/includes/Rest/DonateController.php
T
shadowdaoandClaude Sonnet 5.5 4c379a0245
Test and Release / test (push) Successful in 1m21s
Test and Release / release (push) Successful in 4s
Tiered goals: ordered milestones with unlocks, tier-aware goal bar, TIER UNLOCKED alerts, next-unlock line
- Tiers\TierPolicy (pure), TierRepository (atomic reached marking), Tiers\Recorder hooked before close-at-target
- Admin tiers screen; goal target derived from the final tier
- Overlay goal widget shows Tier N of M and fills within the tier; alert pill; donate form 'Next unlock'
- Installer DB_VERSION 4 (sg_goal_tiers)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 13:09:18 -08:00

318 lines
14 KiB
PHP

<?php
declare( strict_types=1 );
namespace StreamGoals\Rest;
use StreamGoals\Core\GoalTargetPolicy;
use StreamGoals\Core\Money;
use StreamGoals\Core\Settings;
use StreamGoals\PayPal\CaptureFinalizer;
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 ) );
}
$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
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();
$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'] ) );
foreach ( DonationStore::active_goals() as $g ) {
if ( $pinned && (int) $g['id'] !== $pinned ) {
continue;
}
$next = self::next_unlock( $g );
$goals[] = ( null === $next ? array() : array( 'nextUnlock' => $next ) ) + array(
'id' => (int) $g['id'],
'title' => (string) $g['title'],
'currency' => strtoupper( (string) $g['currency'] ),
'exp' => Money::exponent( (string) $g['currency'] ),
'actions' => $actions[ (int) $g['id'] ] ?? array(),
);
}
if ( ! $goals ) {
$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>';
}
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' => \StreamGoals\Core\Settings::effectiveMin( (int) $s['min_donation_minor'] ),
'messageMax' => min( 500, (int) $s['message_max_length'] ),
'disableFunding' => array_values( array_filter( array( empty( $s['funding_paylater'] ) ? 'paylater' : '', empty( $s['funding_card'] ) ? 'card' : '' ) ) ),
'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' ),
'customAmount' => __( 'Or enter your own amount', 'streamgoals-donate' ),
'customPlaceholder' => __( 'Other amount', 'streamgoals-donate' ),
/* translators: %s: formatted amount, e.g. $5.00 */
'everyLabel' => __( 'Every %s', 'streamgoals-donate' ),
/* 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' ),
'actionsHint' => __( 'Pick a reward, or enter your own amount below.', 'streamgoals-donate' ),
/* translators: %s: formatted minimum amount, e.g. $1.00 */
'minHint' => __( 'Minimum donation: %s', 'streamgoals-donate' ),
/* translators: %s: formatted minimum amount, e.g. $1.00 */
'belowMin' => __( 'The minimum donation is %s.', 'streamgoals-donate' ),
'coverInfoLabel' => __( 'What does this mean?', 'streamgoals-donate' ),
'coverInfo' => __( 'PayPal takes a small fee from every donation. Tick this box to add that fee to your total, so the full amount you chose reaches the streamer. It is optional.', 'streamgoals-donate' ),
),
);
wp_add_inline_script( 'streamgoals-donate', 'window.StreamGoalsDonate=' . wp_json_encode( $config, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT ) . ';', 'before' );
return '<div class="sg-donate" data-goal="' . esc_attr( (string) $pinned ) . '"></div>';
}
/* ------------------------------------------------------------- Helpers */
/**
* "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;
}
}
/**
* 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;
}
/** 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 {
$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', 'auto' ), (array) apply_filters( 'streamgoals_cloudflare_ranges', array() ) );
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 ) );
}
}