---
title: Writing a custom payment gateway
sidebar:
  label: Custom Gateways
---

To use a payment provider Resrv doesn't support yet, write a class that implements `Reach\StatamicResrv\Http\Payment\PaymentInterface` and add it to the `payment_gateways` config array. Surcharges and amount limits come from config, so your gateway doesn't need any code for them (see [Payment gateways](/payment-gateways)).

The examples on this page use a made-up provider, AcmePay.

## Inline or redirect

A gateway is one of two types:

- **Inline** gateways, like Stripe and [PayPal](/paypal), show their payment form on your checkout page. `redirectsForPayment()` returns `false`.
- **Redirect** gateways, like [Mollie](/mollie), send the customer to the provider's payment page and back. `redirectsForPayment()` returns `true`.

## The PaymentInterface

```php
interface PaymentInterface
{
    public function name(): string;
    public function label(): string;
    public function paymentView(): string;
    public function paymentIntent($amount, Reservation $reservation, $data, ?string $returnUrl = null);
    public function retrievePaymentIntent(string $paymentId, Reservation $reservation): ?object;
    public function cancelPaymentIntent(string $paymentId, Reservation $reservation): void;
    public function refund(Reservation $reservation);
    public function getPublicKey(Reservation $reservation);
    public function getSecretKey(Reservation $reservation);
    public function getWebhookSecret(Reservation $reservation);
    public function supportsWebhooks(): bool;
    public function supportsManualConfirmation(): bool;
    public function supportsAutomaticRefunds(): bool;
    public function redirectsForPayment(): bool;
    public function handleRedirectBack(): array;
    public function handlePaymentPending(): bool|array;
    public function verifyPayment($request);
    public function verifyWebhook();
}
```

Implement every method, and declare `paymentIntent()`'s `$returnUrl` parameter even if you don't use it. A missing method is a fatal error that breaks checkout for every gateway. Methods your provider doesn't need can do nothing.

## Name, label and view

```php
public function name(): string
{
    return 'acmepay'; // a lowercase slug
}

public function label(): string
{
    return 'AcmePay'; // the checkout picker label, unless the config sets one
}

public function paymentView(): string
{
    // Inline gateways: your Blade view.
    return 'acmepay::livewire.acmepay-payment';

    // Redirect gateways: Resrv's default, which never renders.
    // return 'statamic-resrv::livewire.checkout-payment';
}

public function supportsManualConfirmation(): bool
{
    return false;
}
```

`supportsManualConfirmation()` returns `true` only when no provider checks the payment, as with bank transfer. Checkout then shows a **Confirm reservation** button and never calls `paymentIntent()`. From v6.6.0 the button places the booking in **Awaiting payment** until you mark it as paid. Before, it confirmed the booking straight away.

## Creating the payment intent

`paymentIntent()` starts the payment at the provider. `$amount` is a `Price` that includes any surcharge, and `$amount->raw()` gives it in cents. Save the reservation's id and reference in the provider's metadata, so a late webhook can still find it.

Inline gateways return an `->id` and a `->client_secret` for your payment form:

```php
public function paymentIntent($amount, Reservation $reservation, $data, ?string $returnUrl = null)
{
    $session = AcmePay::createSession([
        'amount' => $amount->raw(),
        'currency' => Str::lower(config('resrv-config.currency_isoCode')),
        'metadata' => [
            'reservation_id' => $reservation->id,
            'reservation_reference' => $reservation->reference,
        ],
    ]);

    $result = new \stdClass;
    $result->id = $session->id; // saved as the reservation's payment_id
    $result->client_secret = $session->client_secret;

    return $result;
}
```

Redirect gateways return an `->id` and a `->redirectTo`, the provider's payment page. Pass the provider a return URL built as below:

```php
$result->id = $session->id;
$result->redirectTo = $session->checkout_url;
```

### The return URL

`$returnUrl` is where the customer comes back to: your checkout complete page, or the customer's payment link on the [payment page](/payment-page). When it's `null`, use the checkout complete page. Add `resrv_gateway` with your config key, and use `&` when the URL already has a `?`, since the payment link does:

```php
use Statamic\Facades\Entry;

protected function buildReturnUrl(Reservation $reservation, ?string $returnUrl = null): string
{
    $base = $returnUrl ?? Entry::find(config('resrv-config.checkout_completed_entry'))->absoluteUrl();
    $separator = str_contains($base, '?') ? '&' : '?';

    return $base.$separator.http_build_query([
        'id' => $reservation->id,
        'resrv_gateway' => 'acmepay', // your config key
    ]);
}
```

## The inline payment view

An inline gateway's view renders inside checkout's payment step and on the [payment page](/payment-page). It gets:

| Property | Description |
| --- | --- |
| `$wire.clientSecret` | The `client_secret` from `paymentIntent()` |
| `$wire.publicKey` | From `getPublicKey()` |
| `$wire.checkoutCompletedUrl` | Where to send the customer after they pay |
| `$amount` | The amount, as a Blade variable. Print it with `\Reach\StatamicResrv\Facades\Price::create($amount)->format()` to show the currency's decimals. |

Load your provider's JavaScript in your layout, and in your payment page layout too.

After the customer pays, send them to `checkoutCompletedUrl` with `redirect_status=succeeded` added (or `processing`, or `failed` when they can try again). Use `&` when the URL already has a `?`.

```blade
<div>
    <div x-data="acmepayPayment">
        <div class="my-6 xl:my-8">
            <div class="text-lg xl:text-xl font-medium mb-2">
                {{ trans('statamic-resrv::frontend.payment') }}
            </div>
        </div>
        <div id="acmepay-form"></div>
        <p x-show="errors" x-cloak class="mt-6 text-red-600"><span x-html="errors"></span></p>
    </div>
</div>

@script
<script>
Alpine.data('acmepayPayment', () => ({
    errors: false,

    init() {
        // Load AcmePay's form with $wire.publicKey and $wire.clientSecret. When it's paid:
        // const url = $wire.checkoutCompletedUrl;
        // window.location.href = url + (url.includes('?') ? '&' : '?') + 'redirect_status=succeeded';
    },
}));
</script>
@endscript
```

Make the view publishable and return its namespaced name from `paymentView()`, so a published copy overrides it.

## Handling the redirect back

When the customer comes back from a redirect gateway, Resrv calls `handleRedirectBack()`. Return an array with a `status`:

- `true`: the payment succeeded.
- `'pending'`: the customer is done, but the payment is still completing, like a bank transfer.
- `false`: the payment didn't go through and the customer has to try again, like a declined card. The checkout stays open for them.

```php
public function handleRedirectBack(): array
{
    if ($pending = $this->handlePaymentPending()) {
        return $pending;
    }

    $sessionId = request()->input('session_id');
    $reservation = Reservation::findByPaymentId($sessionId)->first();

    if (! $reservation) {
        return ['status' => false, 'reservation' => []];
    }

    return [
        'status' => match (AcmePay::getSession($sessionId)->status) {
            'paid' => true,
            'processing' => 'pending',
            default => false,
        },
        'reservation' => $reservation->toArray(),
    ];
}

public function handlePaymentPending(): bool|array
{
    return PendingPayment::fromRequest();
}
```

:::warning[FIND THE RESERVATION BY THE PROVIDER'S ID]
Look the reservation up with a value your provider issued, like the payment id above. Never use a reservation id from the URL: ids are sequential, so anyone could read other customers' bookings. For the same reason, `handlePaymentPending()` should return `PendingPayment::fromRequest()` rather than look the id up itself.
:::

The [payment page](/payment-page) calls `handleRedirectBack()` too, only to choose its message. The webhook still confirms the booking.

## Verifying webhooks v6.6.0 [#verifying-webhooks]

Gateways that confirm bookings through a webhook return `true` from `supportsWebhooks()` and implement `verifyPayment()`. Their webhook URL ends in the config key, like `https://your-site.com/resrv/api/webhook/acmepay` (see [Webhook routes](/payment-gateways#webhook-routes)).

Your gateway only talks to the provider. Resrv decides what a successful payment does to the booking: add the `Reach\StatamicResrv\Http\Payment\ConfirmsGatewayPayments` trait to your class, as the [starter gateway](#a-redirect-gateway-to-start-from) does, and pass the payment to its `confirmFromGateway()` method.

`verifyPayment()` should:

1. Check the signature against `getWebhookSecret()`, and reject the request if it doesn't match.
2. Find the reservation by its payment id. If Resrv has already dropped the payment, find it by the id and reference in the metadata, and mark the payment stale.
3. When the payment succeeded, call `confirmFromGateway()`.
4. When the payment was cancelled and isn't stale, call `$reservation->expire()`. Leave failed attempts alone, since the customer can try again.
5. Return a 200 response.

```php
public function verifyPayment($request)
{
    // Check the signature first.
    $event = json_decode($request->getContent(), true);
    $data = $event['data'];

    $reservation = Reservation::findByPaymentId($data['id'])->first();

    // The customer left this payment (went back, switched gateway) before it succeeded.
    $isStale = false;
    if (! $reservation && isset($data['metadata']['reservation_id'])) {
        $reservation = Reservation::find($data['metadata']['reservation_id']);

        // Another site on the same AcmePay account can have a reservation with this id.
        if ($reservation && ($data['metadata']['reservation_reference'] ?? null) !== $reservation->reference) {
            $reservation = null;
        }

        $isStale = (bool) $reservation;
    }

    if (! $reservation) {
        return response()->json([], 200);
    }

    if ($data['status'] === 'succeeded') {
        $this->confirmFromGateway(
            $reservation,
            $data['id'],
            stale: $isStale,
            amount: $data['amount'], // in cents
            eventId: $event['id'],
        );
    }

    if ($data['status'] === 'canceled' && ! $isStale) {
        $reservation->expire(); // only ends checkouts, never a manual reservation awaiting payment
    }

    return response()->json([], 200);
}
```

`confirmFromGateway()` confirms the reservation and fires `ReservationConfirmed`, so the [activity log](/activity-log) shows "Confirmed by payment webhook". It confirms checkouts and manual reservations awaiting payment alike, so don't check the status first. A repeat delivery of the payment that confirmed the booking does nothing. When the payment can't confirm the booking, it emails your admins instead (see below).

| Argument | Description |
| --- | --- |
| `reservation` | The reservation you found. |
| `paymentId` | The provider's id for this payment, the one saved as the reservation's payment id. |
| `stale` | `true` for a payment you found through its metadata. |
| `amount` | What the provider charged, in cents. Resrv confirms only when it matches the booking amount plus any surcharge. If your provider reports a decimal like `49.90`, pass `\Reach\StatamicResrv\Facades\Price::create('49.90')->raw()`. Leave it out if your provider doesn't report the amount. |
| `eventId` | The provider's event id, which the admin email shows. |
| `inTransaction` | A closure that changes the reservation in the same write that confirms it, or not at all. Use it when the id you confirm with replaces the one Resrv saved, such as a capture id that replaces an order id: `fn (Reservation $fresh) => $fresh->payment_id = $captureId`. |

A few rules the example follows:

- **Don't confirm abandoned payments.** Pass `stale: true`, and Resrv emails your admins to settle the payment with the provider by hand. Confirming it could charge an amount or gateway the booking no longer matches.
- **Don't end a manual reservation that's awaiting payment** when a payment fails or is cancelled. The customer can still pay from the same link.

`verifyWebhook()` answers the webhook's GET route. Return `true`.

:::info
`confirmFromGateway()` is new in v6.6.0. Gateways that confirm bookings themselves with `transitionTo()` keep working. Moving them to `confirmFromGateway()` means Resrv's fixes to this code reach them with each Resrv update. The [upgrade guide](https://github.com/reachweb/statamic-resrv/blob/main/UPGRADE-PAYMENT-GATEWAYS.md) shows how. When you move one, check the reference before you pass `stale: true`, as the example above does. `confirmFromGateway()` emails your admins about every stale payment, even for a confirmed booking, so a payment matched on the reservation id alone could ask them to refund another site's customer.
:::

### The orphan-payment race

A payment can succeed just as Resrv ends the booking, for example when its hold runs out, or just as another payment confirms it. `confirmFromGateway()` reads the reservation again when that happens. It emails your admins if money arrived for a booking that's no longer active, or that the customer paid another way first, such as with the offline gateway or through [**Mark as paid**](/manual-reservations#mark-as-paid). You can then refund it.

It sends the same email for the other payments it won't confirm:

- A stale payment, even when the booking is confirmed: the customer may then have paid twice.
- A payment the customer completes after you [marked the booking as paid](/manual-reservations#mark-as-paid), when Resrv couldn't cancel it at the time.
- A payment for a booking that already expired, was refunded or was cancelled. A cancelled booking that kept its payment on purpose is the exception.
- A payment whose amount doesn't match.

Each payment is reported once, however often the provider sends the webhook again.

## Cancelling abandoned intents

Resrv calls `cancelPaymentIntent()` when the customer leaves a payment behind: they change payment method, change the amount (with a coupon, for example) or let the checkout time out. It also calls it when a manual reservation is cancelled or marked as paid while its payment is still open. Except when a checkout times out, Resrv then checks the result with [`retrievePaymentIntent()`](#retrieving-a-payment-intent). From v6.6.0, checkout starts another payment only once the old one reports `canceled`.

```php
public function cancelPaymentIntent(string $paymentId, Reservation $reservation): void
{
    try {
        AcmePay::cancel($paymentId);
    } catch (\Throwable $e) {
        Log::warning('Could not cancel the AcmePay payment: '.$e->getMessage(), [
            'payment_id' => $paymentId,
            'reservation_id' => $reservation->id,
        ]);
    }
}
```

Cancel only payments that can still be cancelled, and log errors instead of throwing them. Gateways with nothing to cancel, like the offline gateway, leave the method empty.

## Retrieving a payment intent [#retrieving-a-payment-intent]

`retrievePaymentIntent()` reads a payment's current state. [Manual reservations](/manual-reservations) use it to resume a payment on the [payment page](/payment-page), to check a cancellation went through, and before marking a booking as paid or refunding it. From v6.6.0, checkout uses it too: to continue a payment the customer started, and to check that the old payment is cancelled before it starts another.

Return an object with a `->status`, using Stripe's names:

| Status | Meaning |
| --- | --- |
| `succeeded`, `processing` or `requires_capture` | The money is taken, on its way or held. |
| `canceled` | The payment is dead. Report this after `cancelPaymentIntent()` cancels it. |
| Anything else, like `requires_payment_method` | It can still be paid. Add `->redirectTo` or `->client_secret` so Resrv can resume it. |

Return `null` only when the provider says the payment doesn't exist, like a 404. For timeouts, rate limits, server and login errors, throw: returning `null` there could lead to a second charge.

If your provider can't cancel a payment the bank hasn't answered yet, report it as payable without `->redirectTo`, and add `->expires_at` with the time the provider stops accepting it. The payment page and, from v6.6.0, checkout then tell the customer when they can try again. Without it, they see "We could not start the payment process" until your gateway reports the payment `canceled`.

The Stripe gateway returns Stripe's own payment intent, which already has `->status` and `->client_secret`:

```php
public function retrievePaymentIntent(string $paymentId, Reservation $reservation): ?object
{
    try {
        return $this->getClient($reservation)->paymentIntents->retrieve($paymentId);
    } catch (InvalidRequestException $e) {
        if ($e->getError()?->code === 'resource_missing' || $e->getHttpStatus() === 404) {
            return null;
        }

        throw $e;
    }
}
```

Gateways with no provider, like the offline gateway, return `null`.

## Refunds

Resrv calls `refund()` when you refund a reservation in the Control Panel. If the refund fails, throw `RefundFailedException`, and the Control Panel shows the error:

```php
public function refund(Reservation $reservation)
{
    try {
        return AcmePay::refund($reservation->payment_id);
    } catch (\Exception $e) {
        throw new \Reach\StatamicResrv\Exceptions\RefundFailedException($e->getMessage());
    }
}

public function supportsAutomaticRefunds(): bool
{
    return true;
}
```

`supportsAutomaticRefunds()` returns `true` when `refund()` sends the money back through the provider. Only then can customers cancel their own bookings on the [reservation status page](/reservation-status#cancelling-a-reservation). Gateways that move no money, like bank transfer, return `false`.

For a booking you [marked as paid](/manual-reservations#mark-as-paid), you return the money yourself. Resrv only calls `refund()` if the customer's online payment went through as well.

## Provider keys

`getPublicKey()`, `getSecretKey()` and `getWebhookSecret()` return your provider's keys. They get the reservation, so you can use different keys per collection, as [Stripe](/stripe#per-collection-stripe-accounts) does.

```php
public function getPublicKey(Reservation $reservation)
{
    return config('services.acmepay.public_key');
}
```

## Registering the gateway

Add your class under `payment_gateways` in `config/resrv-config.php`:

```php
'payment_gateways' => [
    'acmepay' => [
        'class' => \App\Payment\AcmePayPaymentGateway::class,
        'label' => 'AcmePay',
    ],
],
```

The key (`acmepay`) is saved with each booking and is part of the webhook URL, so don't change it once you have bookings. See [Payment gateways](/payment-gateways) for the other options.

## A redirect gateway to start from

```php
<?php

namespace App\Payment;

use Illuminate\Support\Facades\Log;
use Reach\StatamicResrv\Exceptions\RefundFailedException;
use Reach\StatamicResrv\Http\Payment\ConfirmsGatewayPayments;
use Reach\StatamicResrv\Http\Payment\PaymentInterface;
use Reach\StatamicResrv\Http\Payment\PendingPayment;
use Reach\StatamicResrv\Models\Reservation;
use Statamic\Facades\Entry;

class AcmePayPaymentGateway implements PaymentInterface
{
    use ConfirmsGatewayPayments;

    public function name(): string
    {
        return 'acmepay';
    }

    public function label(): string
    {
        return 'AcmePay';
    }

    public function paymentView(): string
    {
        return 'statamic-resrv::livewire.checkout-payment';
    }

    public function supportsManualConfirmation(): bool
    {
        return false;
    }

    public function redirectsForPayment(): bool
    {
        return true;
    }

    public function paymentIntent($amount, Reservation $reservation, $data, ?string $returnUrl = null)
    {
        // TODO: create the payment at AcmePay for $amount->raw() cents,
        // with $this->buildReturnUrl($reservation, $returnUrl) as its return URL.
        $result = new \stdClass;
        $result->id = 'ACMEPAY_PAYMENT_ID';
        $result->redirectTo = 'https://acmepay.example/pay/...';

        return $result;
    }

    public function retrievePaymentIntent(string $paymentId, Reservation $reservation): ?object
    {
        // TODO: fetch the payment and map its status to Stripe's names.
        // Return null only when AcmePay says it doesn't exist.
        $result = new \stdClass;
        $result->id = $paymentId;
        $result->status = 'requires_payment_method';
        $result->redirectTo = 'https://acmepay.example/pay/...';

        return $result;
    }

    protected function buildReturnUrl(Reservation $reservation, ?string $returnUrl = null): string
    {
        $base = $returnUrl ?? Entry::find(config('resrv-config.checkout_completed_entry'))->absoluteUrl();
        $separator = str_contains($base, '?') ? '&' : '?';

        return $base.$separator.http_build_query([
            'id' => $reservation->id,
            'resrv_gateway' => 'acmepay',
        ]);
    }

    public function handleRedirectBack(): array
    {
        if ($pending = $this->handlePaymentPending()) {
            return $pending;
        }

        $reservation = Reservation::findByPaymentId(request()->input('payment_id'))->first();

        if (! $reservation) {
            return ['status' => false, 'reservation' => []];
        }

        // TODO: ask AcmePay for the payment's status: true, 'pending' or false.
        return ['status' => true, 'reservation' => $reservation->toArray()];
    }

    public function handlePaymentPending(): bool|array
    {
        return PendingPayment::fromRequest();
    }

    public function cancelPaymentIntent(string $paymentId, Reservation $reservation): void
    {
        try {
            // TODO: cancel the payment at AcmePay.
        } catch (\Throwable $e) {
            Log::warning('Could not cancel the AcmePay payment: '.$e->getMessage());
        }
    }

    public function supportsWebhooks(): bool
    {
        return true;
    }

    public function verifyWebhook()
    {
        return true;
    }

    public function verifyPayment($request)
    {
        // TODO: check the signature and call $this->confirmFromGateway(), see "Verifying webhooks".
        return response()->json([], 200);
    }

    public function supportsAutomaticRefunds(): bool
    {
        return true;
    }

    public function refund(Reservation $reservation)
    {
        try {
            // TODO: refund $reservation->payment_id at AcmePay.
        } catch (\Exception $e) {
            throw new RefundFailedException($e->getMessage());
        }

        return true;
    }

    public function getPublicKey(Reservation $reservation)
    {
        return config('services.acmepay.public_key');
    }

    public function getSecretKey(Reservation $reservation)
    {
        return config('services.acmepay.secret_key');
    }

    public function getWebhookSecret(Reservation $reservation)
    {
        return config('services.acmepay.webhook_secret');
    }
}
```

For an inline gateway, return `false` from `redirectsForPayment()`, return `->client_secret` instead of `->redirectTo`, and return your view from `paymentView()` (see [The inline payment view](#the-inline-payment-view)).

## Related

- [Payment gateways](/payment-gateways): the gateway picker, surcharges, amount limits and webhook routes.
- [Stripe](/stripe): the built-in inline gateway.
- [Mollie](/mollie) and [PayPal](/paypal): Reach's gateway add-ons.
- [Manual reservations](/manual-reservations) and the [payment page](/payment-page): bookings you create in the Control Panel, paid through your gateway.
