aqsaahsan301 / laravel-payments
Gateway-agnostic payment and subscription billing for Laravel.
Fund package maintenance!
Requires
- php: ^8.3
- illuminate/support: ^12.0||^13.0
- stripe/stripe-php: ^17.4||^18.0||^19.0||^20.0||^21.0
Requires (Dev)
- larastan/larastan: ^3.9
- laravel/agent-detector: ^2.0
- laravel/chisel: ^0.1
- laravel/pao: ^1.0
- laravel/pint: ^1.29
- laravel/prompts: ^0.3
- orchestra/testbench: ^10.0||^11.0
- pestphp/pest: ^4.6||^5.0
- pestphp/pest-plugin-laravel: ^4.1||^5.0
- pestphp/pest-plugin-type-coverage: ^4.0||^5.0
- phpstan/extension-installer: ^1.4
README
Laravel Payments
Gateway-agnostic payment and subscription billing for Laravel.
Installation
You can install the package via Composer:
composer require aqsaahsan301/laravel-payments
You may publish all of the package's resources at once:
php artisan vendor:publish --tag="laravel-payments"
Or, you may publish each resource individually:
Publishing the Configuration File
php artisan vendor:publish --tag="laravel-payments-config"
Why gateway-agnostic
Laravel Cashier is excellent, but it's Stripe-only by design — it owns a subscriptions table, a Billable Eloquent trait, and a whole persistence layer built around Stripe's model. For clients who need a local gateway instead (Billplz, ToyyibPay, Curlec/Razorpay — common where FPX, GrabPay, or TnG matter), that coupling means starting over.
This package takes a different shape:
- A base contract shaped around what every gateway can do.
PaymentGatewayhas justcharge()(a one-time payment) andhandleWebhook(). It's deliberately not shaped around Stripe's subscription model — plenty of real gateways (FPX, Billplz, ToyyibPay, DuitNow QR) are one-time/invoice-only with no subscription concept at all, and a contract that assumed subscriptions would make them impossible to implement honestly. - Subscriptions are a separate, optional contract. Drivers whose gateway actually supports recurring billing (Stripe, presumably Curlec/Razorpay) additionally implement
SupportsSubscriptions—checkout(),cancelSubscription(),currentPlan(). Host app code checks$gateway instanceof SupportsSubscriptions(or resolvesSupportsSubscriptionsfrom the container directly) before offering recurring-billing UI, rather than assuming every driver has it. PaymentManagerresolves the configured driver the same way Laravel's ownMailManager/QueueManagerdo. SetPAYMENT_GATEWAY=stripein.env; swapping to a different driver later is a config change plus a new driver class, not a rewrite.- No database, no Eloquent models, no opinion on your schema. The package is completely stateless.
charge()/checkout()take and return plain identifiers (strings) that you persist however you like. Inbound webhooks come back out as this package's own Laravel events —PaymentSucceeded,PaymentFailed,SubscriptionCancelled,SubscriptionUpdated— carrying plain data, not gateway SDK objects. You listen for those and update your own tables. This is what makes the package reusable across projects with completely different schemas (aUseris billable in one app, anOrganizationin another — the package doesn't care).
Configuration
php artisan vendor:publish --tag="laravel-payments-config"
PAYMENT_GATEWAY=stripe STRIPE_KEY=pk_test_... STRIPE_SECRET=sk_test_... STRIPE_WEBHOOK_SECRET=whsec_... PAYMENT_GATEWAY_WEBHOOK_PATH=laravel-payments/webhook # optional, this is the default
Map your app's plan slugs to each gateway's own price/plan ids in config/laravel-payments.php:
'plans' => [ 'starter' => [ 'stripe' => 'price_123...', ], 'pro' => [ 'stripe' => 'price_456...', ], ],
The package registers its webhook route automatically at laravel-payments/webhook (or wherever webhook_path points). Exclude it from CSRF verification in your host app's bootstrap/app.php — the gateway calls it directly and can't supply a token:
->withMiddleware(function (Middleware $middleware) { $middleware->validateCsrfTokens(except: [ 'laravel-payments/webhook', ]); })
Then point your gateway's dashboard (Stripe's webhook settings, for example) at https://your-app.test/laravel-payments/webhook, and copy the signing secret it gives you into STRIPE_WEBHOOK_SECRET.
Usage
A one-time payment (every gateway supports this)
use Aqsaahsan301\LaravelPayments\Contracts\PaymentGateway; class CheckoutController { public function pay(Request $request, PaymentGateway $gateway) { $result = $gateway->charge( customerEmail: $request->user()->email, amount: 4900, // smallest currency unit — $49.00 currency: 'usd', options: [ 'success_url' => route('orders.show', $order).'?paid=1', 'cancel_url' => route('orders.show', $order).'?paid=0', ], ); return redirect()->away($result->url); } }
Starting a subscription checkout (only for drivers that support it)
use Aqsaahsan301\LaravelPayments\Contracts\SupportsSubscriptions; class BillingController { public function checkout(Request $request, SupportsSubscriptions $gateway) { $organization = $request->user()->organization; $result = $gateway->checkout( providerCustomerId: $organization->billing_customer_id, // null if they don't have one yet customerEmail: $request->user()->email, plan: 'starter', options: [ 'success_url' => route('billing.show').'?checkout=success', 'cancel_url' => route('billing.show').'?checkout=cancelled', ], ); // Persist the customer id yourself — the package never does this for you. $organization->update(['billing_customer_id' => $result->providerCustomerId]); return redirect()->away($result->url); } }
Type-hinting SupportsSubscriptions (rather than PaymentGateway) means the container throws immediately with a clear message if PAYMENT_GATEWAY is ever pointed at a driver that doesn't support subscriptions — instead of failing later with a "method does not exist" error. If your app needs to conditionally show recurring-billing UI only when it's available, resolve PaymentGateway and check instanceof SupportsSubscriptions instead of hard-depending on it.
Both charge() and checkout() return a URL to redirect the browser to — for hosted-checkout gateways like Stripe, that has to be a real top-level navigation (redirect()->away(...) in a controller, or window.location.href = ... from an SPA/Inertia frontend), not an XHR-driven route visit, since the response goes off-site.
Reacting to webhook events
// In a listener, registered however you normally register listeners: use Aqsaahsan301\LaravelPayments\Events\SubscriptionCancelled; class RevokeAccessOnCancellation { public function handle(SubscriptionCancelled $event): void { Organization::where('billing_customer_id', $event->providerCustomerId) ->update(['plan' => null]); } }
Available events: PaymentSucceeded, PaymentFailed, SubscriptionCancelled, SubscriptionUpdated. Each carries plain scalars (providerCustomerId, providerSubscriptionId, amounts, currency, status) plus a raw array with the full webhook payload for anything not modeled explicitly.
Checking the current plan / cancelling
$gateway->currentPlan($organization->billing_customer_id); // 'starter' | 'pro' | null $gateway->cancelSubscription($organization->billing_subscription_id);
Adding a new driver
Every driver is a class implementing Aqsaahsan301\LaravelPayments\Contracts\PaymentGateway (and SupportsSubscriptions too, only if the gateway genuinely has recurring billing) — StripeDriver (src/Drivers/StripeDriver.php) is the reference implementation to copy the shape of. To add, say, a Billplz driver (one-time/invoice-only, no subscriptions):
- Write the driver.
src/Drivers/BillplzDriver.php implements PaymentGateway. It's the only class allowed to import anything from Billplz's SDK/API client — everything else in the package (and in host apps) depends on the contract, never on your driver directly. Implementcharge()andhandleWebhook(); skipSupportsSubscriptionsentirely if the gateway has no subscription concept — that's the whole point of the split. - Translate provider events into this package's own events. In your
handleWebhook(), map Billplz's webhook payload fields ontoPaymentSucceeded/PaymentFailed(andSubscriptionCancelled/SubscriptionUpdatedtoo, if you implementedSupportsSubscriptions) and dispatch those — don't invent new event classes per driver, or host app listeners have to know which gateway is active, defeating the point. - Register it. Either add a
createBillplzDriver()method toPaymentManager(the built-in, LaravelManager-style way — seecreateStripeDriver()), or call$manager->extendDriver('billplz', BillplzDriver::class)from your own service provider if you're shipping the driver as a separate package. - Test it the same way
StripeDriverTest/StripeWebhookEventsTestdo: install a fake HTTP client for your provider's SDK (or bind a mock client in the container) so tests never hit the network, then assert oncharge()'s returnedChargeResult, on which eventshandleWebhook()dispatches for which payloads, and that an invalid signature is rejected. - Nothing in
PaymentGateway,SupportsSubscriptions,PaymentManager, the routes file, the events, or any host app code should need to change. If it does, that's a sign the new driver needs something the contract doesn't offer yet — widen the contract, not a driver-specific escape hatch.
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
Thank you for considering contributing to Laravel Payments! Please review our contributing guide to get started.
Security Vulnerabilities
Please review our security policy on how to report security vulnerabilities.
Credits
License
Laravel Payments is open-sourced software licensed under the MIT license.