Files
wp-donations/includes/PayPal/WebhookEvent.php
T

50 lines
1.5 KiB
PHP
Raw Normal View History

<?php
declare( strict_types=1 );
namespace StreamGoals\PayPal;
use StreamGoals\Core\Money;
/** Pure extraction of the fields we care about from a PayPal webhook event. */
final class WebhookEvent {
public function __construct(
public readonly string $eventId,
public readonly string $type,
public readonly string $captureId,
public readonly string $customId,
public readonly string $orderId,
public readonly ?Money $amount
) {}
public static function fromArray( array $event ): self {
$r = is_array( $event['resource'] ?? null ) ? $event['resource'] : array();
$type = (string) ( $event['event_type'] ?? '' );
$capId = (string) ( $r['id'] ?? '' );
// REFUNDED/REVERSED resources are refund objects whose "up" link points at the capture.
if ( 'PAYMENT.CAPTURE.COMPLETED' !== $type ) {
foreach ( (array) ( $r['links'] ?? array() ) as $l ) {
if ( is_array( $l ) && 'up' === ( $l['rel'] ?? '' ) && preg_match( '#/captures/([A-Za-z0-9\-_]+)$#', (string) ( $l['href'] ?? '' ), $m ) ) {
$capId = $m[1];
break;
}
}
}
$amount = null;
if ( isset( $r['amount']['value'], $r['amount']['currency_code'] ) ) {
try {
$amount = Money::fromDecimalString( (string) $r['amount']['value'], (string) $r['amount']['currency_code'] );
} catch ( \InvalidArgumentException $e ) {
$amount = null;
}
}
return new self(
(string) ( $event['id'] ?? '' ),
$type,
$capId,
(string) ( $r['custom_id'] ?? '' ),
(string) ( $r['supplementary_data']['related_ids']['order_id'] ?? '' ),
$amount
);
}
}