'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 ) ); } $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 '

' . 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 ) ); } }