Files

110 lines
3.6 KiB
PHP

<?php
declare( strict_types=1 );
namespace StreamGoals\Rest;
use StreamGoals\Core\Settings;
use StreamGoals\PayPal\CaptureFinalizer;
use StreamGoals\PayPal\Client;
use StreamGoals\PayPal\DonationStore;
use StreamGoals\PayPal\RateLimiter;
use StreamGoals\PayPal\WebhookEvent;
use StreamGoals\PayPal\WebhookGuard;
use StreamGoals\PayPal\WpCache;
/** PayPal webhook receiver. Signature is verified through PayPal's API before anything is trusted. */
final class WebhookController {
public static function register(): void {
add_action( 'rest_api_init', array( self::class, 'routes' ) );
}
public static function routes(): void {
register_rest_route(
'streamgoals/v1',
'/webhook',
array(
'methods' => 'POST',
'callback' => array( self::class, 'handle' ),
'permission_callback' => '__return_true', // authenticated by PayPal signature
)
);
}
public static function handle( \WP_REST_Request $req ) {
$webhookId = (string) Settings::get( 'paypal_webhook_id', '' );
if ( '' === $webhookId ) {
return new \WP_Error( 'sg_webhook_unconfigured', 'Webhook is not configured.', array( 'status' => 503 ) );
}
if ( ! WebhookGuard::admit( new RateLimiter( new WpCache() ), DonateController::visitor_bucket() ) ) {
return new \WP_Error( 'sg_rate_limited', 'Too many requests.', array( 'status' => 429 ) );
}
$raw = $req->get_body();
$bad = WebhookGuard::check( $req->get_headers(), $raw, time() );
if ( null !== $bad ) {
return new \WP_Error( $bad['code'], 'Rejected.', array( 'status' => $bad['status'] ) );
}
if ( ! Client::fromSettings()->verifyWebhook( $req->get_headers(), $raw, $webhookId ) ) {
return new \WP_Error( 'sg_webhook_signature', 'Invalid signature.', array( 'status' => 401 ) );
}
$data = json_decode( $raw, true );
if ( ! is_array( $data ) ) {
return new \WP_Error( 'sg_webhook_body', 'Bad payload.', array( 'status' => 400 ) );
}
$ev = WebhookEvent::fromArray( $data );
$cache = new WpCache();
$seen = 'sg_wh_' . md5( $ev->eventId );
if ( '' !== $ev->eventId && false !== $cache->get( $seen ) ) {
return rest_ensure_response( array( 'result' => 'duplicate' ) );
}
$result = self::process( $ev );
if ( '' !== $ev->eventId ) {
$cache->set( $seen, 1, DAY_IN_SECONDS );
}
return rest_ensure_response( array( 'result' => $result ) );
}
/** Only PAYMENT.CAPTURE.COMPLETED is acted on; every other event is acknowledged (200) so PayPal stops retrying. */
private static function process( WebhookEvent $ev ): string {
if ( 'PAYMENT.CAPTURE.COMPLETED' === $ev->type ) {
return self::completed( $ev );
}
return 'ignored';
}
private static function locate( WebhookEvent $ev ): ?object {
$row = null;
if ( ctype_digit( $ev->customId ) && '' !== $ev->customId ) {
$row = DonationStore::find( (int) $ev->customId );
}
if ( ! $row && '' !== $ev->captureId ) {
$row = DonationStore::find_by_capture( $ev->captureId );
}
if ( ! $row && '' !== $ev->orderId ) {
$row = DonationStore::find_by_order( $ev->orderId );
}
return $row;
}
private static function completed( WebhookEvent $ev ): string {
$row = self::locate( $ev );
if ( ! $row || '' === $ev->captureId ) {
return 'ignored';
}
$res = CaptureFinalizer::finalize(
$row,
'COMPLETED',
$ev->captureId,
$ev->amount,
array( DonationStore::class, 'mark_completed' ),
array( DonationStore::class, 'notify_applied' )
);
if ( CaptureFinalizer::PENDING === $res ) {
error_log( 'StreamGoals: webhook capture does not match donation ' . $row->id . '; left pending' ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
return 'ignored';
}
return $res;
}
}