Search by

rasuvaeff / payments-paypal

rasuvaeff

PayPal Orders, captures, refunds and webhooks adapter for rasuvaeff/payments

Package info

github.com/rasuvaeff/payments-paypal

pkg:composer/rasuvaeff/payments-paypal

Statistics

Installs: 4

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v0.2.1 2026-11-29 14:11 UTC

This package is auto-updated.

Last update: 2026-11-29 14:35:15 UTC


README

Latest Stable Version Total Downloads Build Static analysis Psalm level License

Provider-neutral PayPal Orders, captures, refunds, OAuth and network-verified webhooks for PHP.

Using an AI coding assistant? See llms.txt for the compact API contract.

Requirements

PHP 8.3-8.6, rasuvaeff/payments ^0.3 and a PSR-18-backed transport configuration.

psr/simple-cache is optional: install it only to use PayPalPsr16TokenProvider (see Access tokens). Nothing else in the package touches it.

Installation

composer require rasuvaeff/payments-paypal

Usage

Construct PayPalGateway with a PayPalAccessTokenProviderInterface, transport, JSON request builder, decoder and PSR clock. Create orders with PaymentMethodReference(id: 'paypal', kind: 'paypal'). Capture returns a provider-neutral payment attempt whose reference kind is capture; pass that reference to CreateRefundRequest.

The fastest route is the factory, which wires a PSR-18 client, the JSON request builder and the PayPal error-envelope decoder from PSR implementations:

use Rasuvaeff\PaymentsPayPal\PayPalCredentials;
use Rasuvaeff\PaymentsPayPal\PayPalGatewayConfig;
use Rasuvaeff\PaymentsPayPal\PayPalGatewayFactory;

$gateway = PayPalGatewayFactory::withCachedOAuth(
    credentials: new PayPalCredentials(clientId: $id, clientSecret: $secret),
    client: $psr18Client,
    requestFactory: $psr17Factory,   // implements both request and stream factories
    clock: $clock,
    config: new PayPalGatewayConfig(apiBaseUri: 'https://api-m.sandbox.paypal.com', sandbox: true),
);

Access tokens

PayPalOAuthTokenProvider exchanges credentials on every call. Wrap it in PayPalCachedTokenProvider (that is what withCachedOAuth above does) to reuse a token until a safety margin before the expiry PayPal reported:

use Rasuvaeff\PaymentsPayPal\PayPalCachedTokenProvider;
use Rasuvaeff\PaymentsPayPal\PayPalOAuthTokenProvider;

$provider = new PayPalOAuthTokenProvider(...);          // implements PayPalExpiringAccessTokenProviderInterface
$token = $provider->accessToken();                      // PayPalAccessToken: ->token(), ->expiresAt

$cache = new PayPalCachedTokenProvider(
    provider: $provider,
    clock: $clock,
    safetyMarginSeconds: 60,                            // refresh 60s early; 0 disables
);

Under php-fpm that cache lasts one request. It saves the second and third call within a request — a webhook verification plus a gateway call — but the container dies with the request, so the next one exchanges a fresh token. To pay the OAuth round trip once per token lifetime the cache has to outlive the request: either run on a long-lived worker (RoadRunner, Swoole), or share one token through a PSR-16 cache:

composer require psr/simple-cache
use Rasuvaeff\PaymentsPayPal\PayPalPsr16TokenProvider;

$shared = new PayPalPsr16TokenProvider(
    provider: $provider,
    cache: $psr16Cache,                                 // a backend you trust with credentials
    clock: $clock,
    safetyMarginSeconds: 60,
);

// or the whole stack in one call:
$gateway = PayPalGatewayFactory::withSharedCachedOAuth(
    credentials: $credentials,
    cache: $psr16Cache,
    client: $psr18Client,
    requestFactory: $psr17Factory,
    clock: $clock,
);

The stored TTL already subtracts the safety margin, so a cache hit is a token PayPal still accepts even if the two clocks disagree by up to that margin. Concurrent misses may exchange more than one token; every caller still gets a valid one.

For a custom composition, PayPalGatewayFactory::create() accepts any PayPalAccessTokenProviderInterface; manual construction with new PayPalGateway(...) also stays available.

Webhooks

For production webhooks use the factory — it assembles PayPalApiWebhookVerifier (the official network verification endpoint), PayPalWebhookValidator, the event type extractor/recognizer and payload mapper around the core WebhookProcessor. Only the durable boundary — event store and acceptance mode — stays yours:

use Rasuvaeff\Payments\QueuedWebhookEventAcceptance;
use Rasuvaeff\PaymentsPayPal\PayPalWebhookProcessorFactory;

$processor = PayPalWebhookProcessorFactory::create(
    webhookId: '8PT597110X687430LKGECATA', // the webhook's id from the Developer Dashboard
    accessTokenProvider: $cache,        // or any token provider
    client: $psr18Client,
    requestFactory: $psr17Factory,
    clock: $clock,
    eventStore: $eventStore,
    eventAcceptance: new QueuedWebhookEventAcceptance(queue: $queue),
);

The webhook id is the id of the webhook subscription (letters and digits, at most 50, as the verification endpoint requires), not the WH-… id of an event; the constructor refuses anything else with InvalidArgumentException rather than letting every delivery fail verification.

PayPalApiWebhookVerifier also refuses a delivery whose transmission headers exceed the lengths the verification endpoint accepts (notifications_webhooks_v1.json): PayPal-Auth-Algo 100, PayPal-Cert-Url 500, PayPal-Transmission-Id 50, PayPal-Transmission-Sig 500, PayPal-Transmission-Time 100 bytes. Such a delivery could never verify, so it is an invalid webhook decided locally: no access token is fetched and no request is sent.

Subscribe the webhook to PAYMENT.CAPTURE.COMPLETED, PAYMENT.CAPTURE.PENDING, PAYMENT.CAPTURE.DECLINED (DENIED is the Payments v1 name and is still recognized), PAYMENT.CAPTURE.REFUNDED, PAYMENT.CAPTURE.REVERSED, PAYMENT.REFUND.PENDING, PAYMENT.REFUND.FAILED and CHECKOUT.ORDER.APPROVED (event names). The capture REFUNDED/REVERSED and the PAYMENT.REFUND.* events carry the refund resource and map to a refund observation of the linked capture; a reversal is a chargeback, and PAYMENT.REFUND.FAILED is how a refund that was pending (eCheck) reports its failure. PayPal publishes no example of the REVERSED resource: the adapter reads it as a refund linking its capture and refuses anything else as MalformedResponseException naming the chargeback — reconcile such an event with retrievePayment() on the capture. CHECKOUT.ORDER.COMPLETED is mapped too, but PayPal sends it to marketplaces and platforms only. PayPal's signature does not expire, so replay protection rests on the event store: keep event ids at least as long as PayPal retries (3 days). An opt-in freshness window adds a second line — PayPalWebhookProcessorFactory::create(..., maximumTransmissionAgeSeconds: 900) (or new PayPalWebhookValidator(verifier: ..., clock: ..., maximumTransmissionAgeSeconds: 900)) refuses a delivery whose PayPal-Transmission-Time is further than that from the clock, before the verification call. It is off by default because PayPal does not document whether a retried delivery carries a fresh transmission time; turn it on only after checking that against your own deliveries.

Currencies and amounts

Money::$minorUnits is the ISO 4217 minor unit (core contract). PayPal writes amounts as decimal strings with the ISO exponent, except HUF and TWD, which it takes without decimals (PayPal currency codes):

Currency ISO exponent PayPal value Adapter
HUF, TWD 2 whole units ("1000") refuses an amount not divisible by 100 with InvalidArgumentException before any request; sends minorUnits / 100; multiplies by 100 when reading
JPY and other zero-exponent currencies 0 "500" as ISO
BHD, KWD and other three-exponent currencies 3 "5.124" as ISO
everything else 2 "25.99" as ISO

Limits

  • Capture mode is automatic only: CaptureMethod::Manual (authorize now, capture later) is refused; there is no void/cancel.
  • No partial capture: CapturePaymentRequest::$amount is refused.
  • CreateRefundRequest::$reason goes to PayPal as note_to_payer, which the buyer sees in PayPal's refund notification. Pass a reason written for the customer, or none; keep internal reasons (fraud flags, chargeback risk) in your own records.
  • One purchase unit and one capture per order (see below).
  • retrievePayment() takes an order reference (/v2/checkout/orders/{id}) or the capture reference capturePayment() returns (/v2/payments/captures/{id}), so a PENDING capture can be followed.
  • PaymentAttempt::$capturedAmount is the gross captured amount, as Stripe's amount_received: refunds never reduce it. A capture COMPLETED, PARTIALLY_REFUNDED or REFUNDED counts its full amount (the refunds are their own resources — reconcile them through RefundAttempt); PENDING, DECLINED and FAILED count zero, as does an order not yet captured; null when the response does not say — a COMPLETED order that shows no capture, or an undocumented capture status.

Idempotency, timeouts and retries

  • PayPal-Request-Id carries the request's idempotencyKey. Orders v2 (order create and capture) accepts at most 108 characters; a longer key is refused with InvalidArgumentException before the request (the core allows 255). A refund (Payments v2, up to 10000) takes any core key. PayPal keeps a request id for about 6 hours, not 24 like Stripe: a retry after that repeats the operation.
  • A CreatePaymentRequest without a key gets a 36-character UUID from the core, which the adapter sends. Capture and refund send PayPal-Request-Id only when you set one; pass a stable key on every call you might retry.
  • The adapter sets no timeout and retries nothing. Configure a timeout on the PSR-18 client and retry only keyed calls.
  • A 409 with issue PREVIOUS_REQUEST_IN_PROGRESS (Payments v2: capture refund, authorization capture and void) means an earlier call on the same resource — usually the same PayPal-Request-Id — is still being processed. The adapter raises the core's IdempotencyConflictException with providerCode PREVIOUS_REQUEST_IN_PROGRESS: the one retryable idempotency conflict, as idempotency_key_in_use is at Stripe. Wait and retry with the same key, within PayPal's 6-hour window: the retry returns the first call's result, while a new key would refund twice. Only the issue decides; an Orders v2 409 without it is a state conflict (the order cannot be captured in its current state) and stays a plain PaymentException that no retry fixes.
  • Webhook verification is a synchronous call to PayPal on every delivery, inside the request PayPal is waiting on: give that client a short timeout so a slow PayPal does not turn into slow acknowledgements and redelivery storms.
  • On a 401 the gateway and the webhook verifier drop a cached access token (PayPalCachedTokenProvider and PayPalPsr16TokenProvider implement PayPalInvalidatableAccessTokenProviderInterface::invalidate()) and rethrow UnauthorizedException without retrying; the next call exchanges a fresh token after a secret rotation or a revoked token. Retry the operation yourself, with the same idempotency key.

Single purchase unit, single capture

The adapter supports one purchase unit per order and one capture per order. An order carrying more is refused with MalformedResponseException instead of being reported from its first element: a unit's amount becomes PaymentAttempt::$amount, the figure reconciliation compares against the order total, and quietly reporting the first of several would under-report the payment. Orders this package creates always carry exactly one unit, so the refusal only surfaces for orders built elsewhere or captured in parts.

Order and capture status

PayPal marks an order COMPLETED as soon as it is captured, whatever became of the capture: an eCheck still in review or a declined capture sits inside a COMPLETED order. So a completed order — from retrievePayment() or a CHECKOUT.ORDER.COMPLETED webhook — takes the state of its single capture, and rawStatus carries that capture status:

Status PaymentState
order PAYER_ACTION_REQUIRED RequiresAction
order APPROVED RequiresCapture
order VOIDED Canceled
order COMPLETED, capture COMPLETED / PARTIALLY_REFUNDED / REFUNDED Succeeded
order COMPLETED, capture PENDING Processing
order COMPLETED, capture DECLINED / FAILED Failed (with failure)
order COMPLETED without a capture in the response or event Processing
anything else Pending

A refunded capture is still a payment that succeeded; the refund is its own resource.

Order create, order capture and capture refund — every call that moves or reserves money — send Prefer: return=representation. PayPal's default (return=minimal) answers with the id, status and links only, without the purchase unit, create_time, captures or refund amount the adapter maps. Should a refund still come back minimal, the adapter reads it once (GET /v2/payments/refunds/{id}, no PayPal-Request-Id) instead of failing after the money moved.

Security

Credentials and OAuth tokens remain in headers. Durable events retain only allow-listed scalar observations, never raw bodies, signatures or credentials.

Webhooks are accepted only after PayPal's verification endpoint returns SUCCESS, and the body sent for verification is the body that was received, byte for byte. That matters: decoding and re-encoding the JSON does not round trip in PHP — non-ASCII gets escaped, an empty object becomes an empty array, a trailing zero disappears — so a re-encoded document is neither the one PayPal signed nor the one the mapper later acts on.

Access tokens live in memory only. PayPalAccessToken and PayPalCredentials mark their inputs #[\SensitiveParameter], which redacts stack traces, and additionally hide the value from __debugInfo() and refuse __serialize() — a dump or a cache write is how a credential usually escapes, and the attribute does nothing there. var_dump(), print_r() and Symfony VarDumper (dump()/dd(), checked with 8.2) show [REDACTED]; var_export(), an (array) cast and a dumper that ignores __debugInfo() read the private properties directly — do not use them on these objects. The token is a private property; reach it through authentication(), or token() when handing it to a cache.

Examples

See examples/ and versioned provider vectors in fixtures/v1/.

Development

composer build
composer test:integration
composer mutation

composer test:integration runs against the PayPal sandbox only and skips each step whose inputs are missing:

Step Needs Checks
create and retrieve an order PAYPAL_CLIENT_ID, PAYPAL_CLIENT_SECRET (sandbox app) Prefer on create; writes the approve link to build/paypal-sandbox-approve-url.txt
capture, partial and full refund the above plus PAYPAL_APPROVED_ORDER_ID (approve that link as a sandbox buyer) Prefer on capture and refund, refund read-back, gross capturedAmount after a refund
verify a recorded webhook delivery the above plus PAYPAL_WEBHOOK_ID and PAYPAL_WEBHOOK_DELIVERY (JSON file {"headers": {...}, "body": "..."}) network verification of the exact bytes and the mapping, e.g. of PAYMENT.CAPTURE.REVERSED

License

BSD-3-Clause. See LICENSE.md.