Search by

rasuvaeff / payments-stripe

rasuvaeff

Stripe PaymentIntent, refund and webhook adapter for rasuvaeff/payments

Package info

github.com/rasuvaeff/payments-stripe

pkg:composer/rasuvaeff/payments-stripe

Statistics

Installs: 4

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v0.1.2 2026-11-29 14:10 UTC

This package is auto-updated.

Last update: 2026-11-29 14:34:50 UTC


README

Latest Stable Version Total Downloads Build Static analysis Psalm level License

Stripe PaymentIntent, capture, cancellation, refund and webhook adapter for rasuvaeff/payments. It uses provider-neutral contracts and PSR interfaces, without the Stripe SDK or framework dependencies.

Using an AI coding assistant? llms.txt contains a compact API reference.

Requirements

  • PHP 8.3-8.5 with ext-filter (and ext-mbstring, required by rasuvaeff/schema)
  • rasuvaeff/payments ^0.3
  • rasuvaeff/schema, which parses Stripe responses and webhook bodies; it brings rasuvaeff/property-testing-core into the runtime dependencies.
  • PSR-17 request/stream factories, a TransportInterface, and a PSR-20 clock

No PHP 8.6 yet. rasuvaeff/schema supports PHP 8.3-8.5; this adapter adds 8.6 once its dependencies do, while the PayPal adapter already runs on it.

The adapter pins Stripe API version 2026-07-29.dahlia by default. StripeGatewayConfig accepts another apiVersion only of the same dahlia series (for example 2026-08-26.dahlia) and throws InvalidArgumentException for any other series: response and event shapes follow the series, and a different Stripe API series needs a different version of this adapter.

Installation

composer require rasuvaeff/payments-stripe

Usage

Build the gateway with the form request builder. Stripe API credentials are passed in memory and must come from application secret storage:

use Rasuvaeff\Payments\FormRequestBuilder;
use Rasuvaeff\Payments\ResponseDecoderInterface;
use Rasuvaeff\PaymentsStripe\StripeCredentials;
use Rasuvaeff\PaymentsStripe\StripeGateway;

$gateway = new StripeGateway(
    credentials: new StripeCredentials(secretKey: $_ENV['STRIPE_SECRET_KEY']),
    transport: $transport,
    requestBuilder: new FormRequestBuilder(
        requestFactory: $requestFactory,
        streamFactory: $streamFactory,
    ),
    responseDecoder: $responseDecoder,
    clock: $clock,
);

$transport implements Rasuvaeff\Payments\TransportInterface; use Psr18Transport to adapt a PSR-18 client. $responseDecoder implements Rasuvaeff\Payments\ResponseDecoderInterface — usually JsonResponseDecoder, but the interface keeps a decorating decoder (logging, metrics) possible. $clock implements Psr\Clock\ClockInterface.

Or take the default composition from PSR implementations in one call:

use Rasuvaeff\PaymentsStripe\StripeGatewayFactory;

$gateway = StripeGatewayFactory::create(
    credentials: new StripeCredentials(secretKey: $_ENV['STRIPE_SECRET_KEY']),
    client: $psr18Client,
    requestFactory: $psr17Factory,   // implements both request and stream factories
    clock: $clock,
);

Create a PaymentIntent using integer minor units and Stripe references:

use Rasuvaeff\Payments\CreatePaymentRequest;
use Rasuvaeff\Payments\Money;
use Rasuvaeff\Payments\OperationId;
use Rasuvaeff\Payments\PaymentMethodReference;

$attempt = $gateway->createPayment(request: new CreatePaymentRequest(
    operationId: new OperationId(value: 'checkout-2026-0001'),
    amount: new Money(minorUnits: 2599, currency: 'USD'),
    paymentMethod: new PaymentMethodReference(id: 'pm_123', kind: 'payment_method'),
    idempotencyKey: 'stripe-checkout-2026-0001-attempt-1',
));

The gateway implements PaymentGatewayInterface, CaptureGatewayInterface, CancelGatewayInterface, ConfirmGatewayInterface and RefundGatewayInterface.

PaymentAttempt::$amount is the amount the intent was created (authorized) for; PaymentAttempt::$capturedAmount is Stripe's amount_received — zero before a capture, less than amount after a partial one, null when the response omits it. It is the gross captured amount: refunds never reduce it (Stripe's amount_received does not fall either). Reconcile what was collected against capturedAmount and refunds against RefundAttempt.

Stripe takes a partial capture (amount_to_capture) and a partial refund (amount) in the PaymentIntent's currency: the capture has no currency field, and a refund's optional currency applies only to refunds without a PaymentIntent (customer balance), never to the one this adapter creates. So when CapturePaymentRequest::$amount or CreateRefundRequest::$amount is set, the gateway first reads the intent (GET /v1/payment_intents/{id}) and throws InvalidArgumentException before posting anything if the currency differs — a 1000 JPY refund on a USD payment would otherwise refund $10.00. A full capture or refund (no amount) makes no extra call. A refund Stripe answers in a currency other than the requested one raises MalformedResponseException naming the refund id.

Currencies and amounts

Money::$minorUnits is the ISO 4217 minor unit (core contract). Stripe deviates for a few currencies (Stripe: zero-decimal currencies and special cases), and the adapter converts:

Currency ISO exponent Stripe amount Adapter
ISK, UGX 0 two-decimal (500 = 5 ISK) multiplies by 100 on the way out, divides on the way back; a response amount not divisible by 100 is MalformedResponseException
MGA 2 zero-decimal (100 = 100 MGA) refuses an amount not divisible by 100 with InvalidArgumentException before any request; divides by 100 on the way out, multiplies on the way back
BHD, JOD, KWD, OMR, TND 3 three-decimal, last digit must be 0 refuses an amount not divisible by 10 with InvalidArgumentException before any request
HUF, TWD 2 two-decimal for charges (the divisible-by-100 rule is for payouts) passes through
everything else as ISO as ISO passes through

The list is the full difference between ISO 4217 exponents and Stripe's zero-decimal list plus special cases, pinned by a test against both sources copied into fixtures/currencies/stripe-amounts.json. Two rows rest on less than a live check:

  • UGX is on Stripe's zero-decimal list and among the special cases ("to charge 5 UGX, provide 500"). The adapter follows the special case, as for ISK; confirm with one test-mode payment before charging UGX in production.
  • Stripe's currency page no longer documents three-decimal currencies; the last-digit-zero rule comes from its former three-decimal section. Refusing is the safe side of it.

A zero or too-small amount is Stripe's to refuse; that refusal arrives as a PaymentException.

Manual confirmation

ConfirmationMethod::Manual with a pm_ payment method creates the intent unconfirmed. Stripe accepts confirmation of such an intent only with the secret key, so the attempt carries no ConfirmOnClient; confirm it server-side:

use Rasuvaeff\Payments\PaymentOperationRequest;

$confirmed = $gateway->confirmPayment(new PaymentOperationRequest(
    operationId: new OperationId(value: 'checkout-2026-0001-confirm'),
    payment: $attempt->payment,
    idempotencyKey: 'stripe-checkout-2026-0001-confirm-1',
));

Manual without a payment method (the deferred flow) is refused with InvalidArgumentException before any request: Stripe.js could not confirm it and there is no method to confirm on the server.

The one-step flow (a pm_ method, Automatic) confirms on create and sends no return_url. With automatic payment methods enabled on the account, Stripe may ask for a return_url when the method can redirect; card payments do not. Pass redirect-capable methods through the deferred flow instead.

Idempotency, timeouts and retries

  • A CreatePaymentRequest without an idempotencyKey gets a UUID from the core, and the adapter sends it as Idempotency-Key. Retry by sending the same request object again (or persist $request->idempotencyKey).
  • Capture, confirm, cancel and refund send Idempotency-Key only when you set one. Without it a retry after a timeout can capture or refund twice: pass a stable key on every call you might retry. Stripe keeps keys for 24 hours.
  • The adapter sets no timeout and retries nothing. Configure a timeout on the PSR-18 client, retry only calls that carry a key (for example with rasuvaeff/retry around the transport), and honour $attempt->requestInfo->retryAfterSeconds / RateLimitedException.
  • A card declined while a create was confirming comes back as HTTP 402 with the intent already created: the ProviderDeclinedException carries its id in details['payment_intent'] and the decline_code. Attach a new payment method to that intent instead of creating a second one.
  • Stripe saves the first response for a key once the endpoint starts executing, errors included (a decline, a refused refund), and answers a retry with the same key from it: a request corrected after such a refusal needs a new key. A request that failed parameter validation, or met a concurrent request with the same key, saves nothing and can be retried with the same key. A key reused with other parameters raises IdempotencyConflictException (providerType idempotency_error) — a caller bug, do not retry it. The same exception with providerCode idempotency_key_in_use (HTTP 409) means the first request with that key is still running: retry later with the same key.

Client-side confirmation

When a PaymentIntent still needs the customer (Pending, RequiresPaymentMethod or RequiresAction, with no more specific provider action), the attempt carries a ConfirmOnClient next action with the intent's client_secret. Stripe designed this value for the customer's browser: stripe.js/Elements needs it to confirm the payment. Hand it to the frontend, never to logs, persistence or webhook payloads:

use Rasuvaeff\PaymentsStripe\ConfirmOnClient;

if ($attempt->nextAction instanceof ConfirmOnClient) {
    echo json_encode(['client_secret' => $attempt->nextAction->clientSecret()]);
}

A more specific action (RedirectToUrl, UseSdk) always wins over ConfirmOnClient; terminal states (Succeeded, Failed, Canceled) and intents created with confirmation_method=manual never expose one. The secret sits behind clientSecret(), so json_encode() of an attempt does not carry it.

Stripe status Payment state
succeeded Succeeded
processing Processing
requires_action RequiresAction
requires_capture RequiresCapture
requires_payment_method RequiresPaymentMethod
canceled Canceled
Any other status Pending

requires_payment_method is not Failed. Stripe returns a declined intent to that status, the customer supplies another card and the same intent reaches succeeded — and PaymentState::Failed is terminal, so mapping it there would make a consumer gating updates on canTransitionTo() discard the later success. The decline itself travels in $attempt->failure.

Deferred intents

Omit paymentMethod from CreatePaymentRequest and the gateway creates the intent with automatic_payment_methods enabled and no method attached, leaving it unconfirmed in requires_payment_method. The attempt comes back with ConfirmOnClient, and the Payment Element collects a method client-side against that client secret:

$attempt = $gateway->createPayment(new CreatePaymentRequest(
    operationId: new OperationId('order-42-charge-1'),
    amount: Money::minorUnits(2_599, 'USD'),
    // no paymentMethod — the customer picks one in the browser
));

Pass a pm_ reference instead when the method already exists — collected client-side beforehand, or stored on file.

Stripe Connect is not supported

A Connect platform receives its connected accounts' events on the same endpoint under the same signing secret; only the event's account field separates them. This package models a single merchant account, so the webhook mapper refuses any event carrying account, reporting it as an unsupported event (HTTP 204, never retried). Mapping it would attach a connected account's payment to this merchant's order. If you enable Connect, you need account-aware routing this package does not provide.

Webhooks

Use the exact request body bytes. Do not decode and re-encode JSON before validation:

use Rasuvaeff\Payments\WebhookInput;
use Rasuvaeff\PaymentsStripe\StripeWebhookEventRecognizer;
use Rasuvaeff\PaymentsStripe\StripeWebhookEventTypeExtractor;
use Rasuvaeff\PaymentsStripe\StripeWebhookPayloadMapper;
use Rasuvaeff\PaymentsStripe\StripeWebhookSecret;
use Rasuvaeff\PaymentsStripe\StripeWebhookValidator;

$input = new WebhookInput(
    rawBody: $rawRequestBody,
    provider: $gateway->provider(),
    headers: ['Stripe-Signature' => $stripeSignatureHeader],
);

$validator = new StripeWebhookValidator(
    secret: new StripeWebhookSecret(value: $_ENV['STRIPE_WEBHOOK_SECRET']),
    clock: $clock,
);
$extractor = new StripeWebhookEventTypeExtractor();
$recognizer = new StripeWebhookEventRecognizer();
$mapper = new StripeWebhookPayloadMapper();

Pass these components to Rasuvaeff\Payments\WebhookProcessor. The validator uses HMAC-SHA256, constant-time comparison, and a 300-second default timestamp tolerance (1 to 86400 seconds; Stripe advises against 0). Supported mappings are payment_intent.* and refund.*. Other syntactically valid Stripe event names are recognized and reported as unsupported, so they can be acknowledged deliberately by the application.

Subscribe the endpoint to the events you reconcile on — typically payment_intent.succeeded, payment_intent.payment_failed, payment_intent.canceled, payment_intent.amount_capturable_updated, refund.created, refund.updated and refund.failed. Disputes (charge.dispute.*) and charge.refunded are not mapped: chargebacks are out of scope for this adapter, and a Dashboard refund is observed through refund.*. An event's shape follows the endpoint's API version, not the version this adapter pins, so create the endpoint with a dahlia API version (2026-07-29.dahlia). An event whose api_version is of another series throws a LogicException naming that version: it escapes the core pipeline, the delivery is answered 5xx and Stripe retries it (for up to three days) until the endpoint is moved to a dahlia version — a 204 would drop every payment event of a misconfigured endpoint for good. A payload the adapter cannot read is MalformedResponseException naming the JSON path, which the core turns into a terminal RejectedWebhookEvent.

Or assemble the same pipeline in one call, providing only the durable boundary (event store and acceptance mode), which stays application-owned:

use Rasuvaeff\Payments\QueuedWebhookEventAcceptance;
use Rasuvaeff\PaymentsStripe\StripeWebhookProcessorFactory;

$processor = StripeWebhookProcessorFactory::create(
    secret: new StripeWebhookSecret(value: $_ENV['STRIPE_WEBHOOK_SECRET']),
    clock: $clock,
    eventStore: $eventStore,
    eventAcceptance: new QueuedWebhookEventAcceptance(queue: $queue),
);

Security

  • Load sk_* and whsec_* values from secret storage; never log or serialize them. StripeCredentials, StripeWebhookSecret and ConfirmOnClient help: each hides its value from __debugInfo() and refuses __serialize(), because #[\SensitiveParameter] redacts stack traces only — not a var_dump(), an error-page dumper or a container dump. 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 property directly — do not use them on these objects.
  • Webhook events belonging to a connected account are refused rather than mapped; see Stripe Connect is not supported above.
  • The PaymentIntent client_secret is safe for the customer's browser and nowhere else: pass it to the frontend through ConfirmOnClient, but keep it out of logs, persistence and webhook payloads.
  • Verify the exact raw webhook body before parsing or persistence.
  • Enforce HTTP body-size limits before constructing WebhookInput.
  • Use a stable, unique idempotency key for every provider-side operation; see Idempotency, timeouts and retries.
  • Treat webhook observations as hints and retrieve authoritative Stripe state before changing business state.
  • The webhook mapper discards raw payloads and secrets. Versioned fixtures are redacted compatibility samples, not production data.

Examples

See examples/ for runnable scripts. Provider response and webhook shapes are versioned under fixtures/v1/.

Development

docker run --rm -v "$PWD":/app -w /app composer:2 composer build
make mutation
make release-check

The sandbox suite (composer test:integration) runs only with a test-mode key (STRIPE_SECRET_KEY=sk_test_… or rk_test_…) and skips otherwise; it never calls live Stripe.

License

BSD-3-Clause