Files
wp-donations/tests/Unit/PayPalClientTest.php
T

201 lines
8.6 KiB
PHP
Raw Permalink Normal View History

<?php
declare( strict_types=1 );
namespace StreamGoals\Tests\Unit;
use PHPUnit\Framework\TestCase;
use StreamGoals\Core\Money;
use StreamGoals\PayPal\ArrayCache;
use StreamGoals\PayPal\Client;
use StreamGoals\PayPal\HttpTransport;
use StreamGoals\PayPal\PayPalException;
use StreamGoals\PayPal\TransportException;
use StreamGoals\PayPal\WebhookEvent;
final class FakeTransport implements HttpTransport {
/** @var array<int,array{method:string,url:string,headers:array,body:?string}> */
public array $calls = array();
/** @var array<int,array|\Throwable> queued responses */
public array $queue = array();
public function request( string $method, string $url, array $headers, ?string $body ): array {
$this->calls[] = compact( 'method', 'url', 'headers', 'body' );
$next = array_shift( $this->queue );
if ( $next instanceof \Throwable ) {
throw $next;
}
return $next ?? array( 'status' => 500, 'body' => '' );
}
public static function json( int $status, array $data ): array {
return array( 'status' => $status, 'body' => json_encode( $data ) );
}
}
final class PayPalClientTest extends TestCase {
private FakeTransport $http;
private function client( string $mode = 'sandbox', string $id = 'cid', string $secret = 'sec' ): Client {
$this->http = new FakeTransport();
return new Client( $this->http, new ArrayCache(), $mode, $id, $secret );
}
private function token(): array {
return FakeTransport::json( 200, array( 'access_token' => 'TOK', 'expires_in' => 3600 ) );
}
public function test_base_url_by_mode(): void {
$this->assertSame( 'https://api-m.sandbox.paypal.com', $this->client( 'sandbox' )->baseUrl() );
$this->assertSame( 'https://api-m.paypal.com', $this->client( 'live' )->baseUrl() );
}
public function test_token_is_cached_and_uses_basic_auth(): void {
$c = $this->client();
$this->http->queue = array( $this->token() );
$this->assertSame( 'TOK', $c->accessToken() );
$this->assertSame( 'TOK', $c->accessToken() );
$this->assertCount( 1, $this->http->calls );
$this->assertSame( 'Basic ' . base64_encode( 'cid:sec' ), $this->http->calls[0]['headers']['Authorization'] );
$this->assertSame( 'grant_type=client_credentials', $this->http->calls[0]['body'] );
$this->assertStringStartsWith( 'https://api-m.sandbox.paypal.com/v1/oauth2/token', $this->http->calls[0]['url'] );
}
public function test_create_order_sends_server_amount_and_capture_intent(): void {
$c = $this->client();
$this->http->queue = array( $this->token(), FakeTransport::json( 201, array( 'id' => 'ORD1' ) ) );
$id = $c->createOrder( new Money( 1099, 'USD' ), '42', 'sg-order-42' );
$this->assertSame( 'ORD1', $id );
$call = $this->http->calls[1];
$body = json_decode( $call['body'], true );
$this->assertSame( 'CAPTURE', $body['intent'] );
$this->assertSame( '10.99', $body['purchase_units'][0]['amount']['value'] );
$this->assertSame( 'USD', $body['purchase_units'][0]['amount']['currency_code'] );
$this->assertSame( '42', $body['purchase_units'][0]['custom_id'] );
$this->assertSame( 'Bearer TOK', $call['headers']['Authorization'] );
$this->assertSame( 'sg-order-42', $call['headers']['PayPal-Request-Id'] );
}
public function test_zero_decimal_currency_amount(): void {
$c = $this->client();
$this->http->queue = array( $this->token(), FakeTransport::json( 201, array( 'id' => 'O' ) ) );
$c->createOrder( new Money( 500, 'JPY' ), '1', 'r' );
$this->assertSame( '500', json_decode( $this->http->calls[1]['body'], true )['purchase_units'][0]['amount']['value'] );
}
public function test_capture_parses_result(): void {
$c = $this->client();
$this->http->queue = array(
$this->token(),
FakeTransport::json( 201, array(
'status' => 'COMPLETED',
'purchase_units' => array( array( 'payments' => array( 'captures' => array( array(
'id' => 'CAP9', 'status' => 'COMPLETED', 'custom_id' => '42',
'amount' => array( 'currency_code' => 'USD', 'value' => '10.99' ),
) ) ) ) ),
) ),
);
$r = $c->captureOrder( 'ORD1', 'sg-capture-42' );
$this->assertSame( 'COMPLETED', $r['status'] );
$this->assertSame( 'CAP9', $r['capture_id'] );
$this->assertSame( 1099, $r['amount']->minor );
$this->assertStringEndsWith( '/v2/checkout/orders/ORD1/capture', $this->http->calls[1]['url'] );
}
public function test_expired_token_retries_once_with_fresh_token(): void {
$c = $this->client();
$this->http->queue = array(
$this->token(),
FakeTransport::json( 401, array( 'name' => 'AUTHENTICATION_FAILURE' ) ),
FakeTransport::json( 200, array( 'access_token' => 'TOK2', 'expires_in' => 3600 ) ),
FakeTransport::json( 201, array( 'id' => 'ORD2' ) ),
);
$this->assertSame( 'ORD2', $c->createOrder( new Money( 500, 'USD' ), '1', 'r' ) );
$this->assertSame( 'Bearer TOK2', $this->http->calls[3]['headers']['Authorization'] );
}
public function test_api_error_is_descriptive_and_carries_name(): void {
$c = $this->client();
$this->http->queue = array( $this->token(), FakeTransport::json( 422, array(
'name' => 'ORDER_ALREADY_CAPTURED', 'message' => 'Order already captured.',
) ) );
try {
$c->captureOrder( 'O', 'r' );
$this->fail( 'expected exception' );
} catch ( PayPalException $e ) {
$this->assertSame( 'ORDER_ALREADY_CAPTURED', $e->paypalName );
$this->assertSame( 422, $e->httpStatus );
$this->assertStringContainsString( 'Order already captured.', $e->getMessage() );
}
}
public function test_verify_webhook_success_and_failure(): void {
$headers = array(
'paypal_transmission_id' => array( 'T1' ), 'PAYPAL-TRANSMISSION-TIME' => '2026-01-01T00:00:00Z',
'paypal_transmission_sig' => 'SIG', 'paypal_cert_url' => 'https://api.paypal.com/cert', 'paypal_auth_algo' => 'SHA256withRSA',
);
$raw = '{"id":"WH-1","event_type":"PAYMENT.CAPTURE.COMPLETED"}';
$c = $this->client();
$this->http->queue = array( $this->token(), FakeTransport::json( 200, array( 'verification_status' => 'SUCCESS' ) ) );
$this->assertTrue( $c->verifyWebhook( $headers, $raw, 'WHID' ) );
$sent = json_decode( $this->http->calls[1]['body'], true );
$this->assertSame( 'WHID', $sent['webhook_id'] );
$this->assertSame( 'T1', $sent['transmission_id'] );
$this->assertSame( 'WH-1', $sent['webhook_event']['id'] );
$c = $this->client();
$this->http->queue = array( $this->token(), FakeTransport::json( 200, array( 'verification_status' => 'FAILURE' ) ) );
$this->assertFalse( $c->verifyWebhook( $headers, $raw, 'WHID' ) );
// Missing header or API error fails closed without a verify call.
$c = $this->client();
unset( $headers['paypal_cert_url'] );
$this->assertFalse( $c->verifyWebhook( $headers, $raw, 'WHID' ) );
$this->assertCount( 0, $this->http->calls );
$c = $this->client();
$this->http->queue = array( new TransportException( 'boom' ) );
$headers['paypal_cert_url'] = 'x';
$this->assertFalse( $c->verifyWebhook( $headers, $raw, 'WHID' ) );
}
public function test_create_webhook_registers_only_completed_event(): void {
$c = $this->client();
$this->http->queue = array( $this->token(), FakeTransport::json( 201, array( 'id' => 'WH77' ) ) );
$this->assertSame( 'WH77', $c->createWebhook( 'https://x.test/wp-json/streamgoals/v1/webhook' ) );
$body = json_decode( $this->http->calls[1]['body'], true );
$names = array_column( $body['event_types'], 'name' );
$this->assertSame( array( 'PAYMENT.CAPTURE.COMPLETED' ), $names );
}
public function test_test_connection_messages(): void {
$c = $this->client( 'sandbox', '', '' );
$this->assertStringContainsString( 'not configured', (string) $c->testConnection() );
$c = $this->client();
$this->http->queue = array( FakeTransport::json( 401, array( 'error' => 'invalid_client' ) ) );
$this->assertStringContainsString( 'rejected the credentials', (string) $c->testConnection() );
$this->assertStringContainsString( 'Sandbox', (string) $this->client()->testConnection() . 'Sandbox' );
$c = $this->client();
$this->http->queue = array( new TransportException( 'timeout' ) );
$this->assertStringContainsString( 'Could not reach PayPal: timeout', (string) $c->testConnection() );
$c = $this->client();
$this->http->queue = array( $this->token() );
$this->assertNull( $c->testConnection() );
}
public function test_webhook_event_parsing(): void {
$done = WebhookEvent::fromArray( array(
'id' => 'E1', 'event_type' => 'PAYMENT.CAPTURE.COMPLETED',
'resource' => array( 'id' => 'CAP1', 'custom_id' => '7', 'amount' => array( 'value' => '5.00', 'currency_code' => 'USD' ),
'supplementary_data' => array( 'related_ids' => array( 'order_id' => 'ORD' ) ) ),
) );
$this->assertSame( 'CAP1', $done->captureId );
$this->assertSame( '7', $done->customId );
$this->assertSame( 'ORD', $done->orderId );
$this->assertSame( 500, $done->amount->minor );
}
}