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:
1 parent
65082fb2f5
commit
589e84f28b
21 files changed
+1659
No files matched your search
@@ -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 ) );
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user