rasuvaeff / payments-paypal
PayPal Orders, captures, refunds and webhooks adapter for rasuvaeff/payments
Requires
- php: 8.3 - 8.6
- ext-filter: *
- psr/clock: ^1.0
- psr/http-client: ^1.0
- psr/http-message: ^2.0
- rasuvaeff/payments: ^0.3
Requires (Dev)
- ergebnis/composer-normalize: ^2.51
- friendsofphp/php-cs-fixer: ^3.95
- guzzlehttp/guzzle: ^8.6
- infection/infection: ^0.35
- maglnet/composer-require-checker: ^4.17
- nyholm/psr7: ^1.8
- psr/simple-cache: ^3.0
- rasuvaeff/payments-testing: ^0.2
- rasuvaeff/property-testing-testo: ^1.4
- rasuvaeff/rector-named-literals: ^1.0.2
- rasuvaeff/understudy-testo: ^1.2
- rector/rector: ^2.4
- roave/backward-compatibility-check: ^8.0
- testo/bridge-infection: ^0.1.9
- testo/testo: ^0.10.62
- vimeo/psalm: ^7.23
Suggests
- psr/simple-cache: ^3.0 to enable PayPalPsr16TokenProvider, the shared access-token cache that survives a php-fpm request
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-11-29 14:35:15 UTC
README
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::$amountis refused. CreateRefundRequest::$reasongoes to PayPal asnote_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 anorderreference (/v2/checkout/orders/{id}) or thecapturereferencecapturePayment()returns (/v2/payments/captures/{id}), so aPENDINGcapture can be followed.PaymentAttempt::$capturedAmountis the gross captured amount, as Stripe'samount_received: refunds never reduce it. A captureCOMPLETED,PARTIALLY_REFUNDEDorREFUNDEDcounts its full amount (the refunds are their own resources — reconcile them throughRefundAttempt);PENDING,DECLINEDandFAILEDcount zero, as does an order not yet captured;nullwhen the response does not say — aCOMPLETEDorder that shows no capture, or an undocumented capture status.
Idempotency, timeouts and retries
PayPal-Request-Idcarries the request'sidempotencyKey. Orders v2 (order create and capture) accepts at most 108 characters; a longer key is refused withInvalidArgumentExceptionbefore 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
CreatePaymentRequestwithout a key gets a 36-character UUID from the core, which the adapter sends. Capture and refund sendPayPal-Request-Idonly 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
409with issuePREVIOUS_REQUEST_IN_PROGRESS(Payments v2: capture refund, authorization capture and void) means an earlier call on the same resource — usually the samePayPal-Request-Id— is still being processed. The adapter raises the core'sIdempotencyConflictExceptionwithproviderCodePREVIOUS_REQUEST_IN_PROGRESS: the one retryable idempotency conflict, asidempotency_key_in_useis 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 v2409without it is a state conflict (the order cannot be captured in its current state) and stays a plainPaymentExceptionthat 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
401the gateway and the webhook verifier drop a cached access token (PayPalCachedTokenProviderandPayPalPsr16TokenProviderimplementPayPalInvalidatableAccessTokenProviderInterface::invalidate()) and rethrowUnauthorizedExceptionwithout 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.