44 lines
1.7 KiB
PHP
44 lines
1.7 KiB
PHP
<?php
|
|||
|
|
declare( strict_types=1 );
|
||
|
|
|
||
|
|
namespace StreamGoals\PayPal;
|
||
|
|
|
||
|
|
use StreamGoals\Core\Money;
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Pure decision logic shared by the capture endpoint and the COMPLETED webhook:
|
||
|
|
* a donation leaves "pending" only when PayPal reports a COMPLETED capture whose
|
||
|
|
* amount and currency match what we stored. Otherwise it stays pending until the
|
||
|
|
* webhook delivers a matching, finalized capture. The pending->completed
|
||
|
|
* transition is atomic (callable returns true for exactly one caller), so
|
||
|
|
* replays and races finalize at most once.
|
||
|
|
*/
|
||
|
|
final class CaptureFinalizer {
|
||
|
|
|
||
|
|
public const COMPLETED = 'completed'; // this call finalized the donation
|
||
|
|
public const DUPLICATE = 'duplicate'; // already finalized / not pending
|
||
|
|
public const PENDING = 'pending'; // capture looks off; donation left pending
|
||
|
|
|
||
|
|
/**
|
||
|
|
* @param object|array $row Donation row (status, total_minor, currency).
|
||
|
|
* @param callable $markCompleted fn(int $id, string $captureId): bool atomic pending->completed
|
||
|
|
* @param callable $notifyApplied fn(int $id): void
|
||
|
|
*/
|
||
|
|
public static function finalize( object|array $row, string $paypalStatus, string $captureId, ?Money $amount, callable $markCompleted, callable $notifyApplied ): string {
|
||
|
|
$r = (object) $row;
|
||
|
|
if ( 'pending' !== (string) $r->status ) {
|
||
|
|
return self::DUPLICATE;
|
||
|
|
}
|
||
|
|
if ( 'COMPLETED' !== $paypalStatus || '' === $captureId ) {
|
||
|
|
return self::PENDING;
|
||
|
|
}
|
||
|
|
if ( ! $amount || $amount->minor !== (int) $r->total_minor || $amount->currency !== (string) $r->currency ) {
|
||
|
|
return self::PENDING;
|
||
|
|
}
|
||
|
|
if ( $markCompleted( (int) $r->id, $captureId ) ) {
|
||
|
|
$notifyApplied( (int) $r->id );
|
||
|
|
return self::COMPLETED;
|
||
|
|
}
|
||
|
|
return self::DUPLICATE;
|
||
|
|
}
|
||
|
|
}
|