rahulthalwal / laravel-razorpay
A Laravel wrapper for the official Razorpay PHP SDK with webhooks, events, payment storage and a Blade checkout component.
Requires
- php: ^8.2
- illuminate/contracts: ^11.0|^12.0|^13.0
- illuminate/database: ^11.0|^12.0|^13.0
- illuminate/http: ^11.0|^12.0|^13.0
- illuminate/routing: ^11.0|^12.0|^13.0
- illuminate/support: ^11.0|^12.0|^13.0
- illuminate/view: ^11.0|^12.0|^13.0
- razorpay/razorpay: ^2.9
Requires (Dev)
- orchestra/testbench: ^9.0|^10.0|^11.0
- pestphp/pest: ^3.0|^4.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
A Laravel integration for Razorpay, built on the official
razorpay/razorpay PHP SDK. It adds:
- 💸 A typed client and
Razorpayfacade that work in rupees and convert to paise for you - ✅ One-line payment signature verification
- 🔔 Verified, idempotent webhooks turned into Laravel events
- 🗄️ Optional storage of payments in your database
- 🧩 A
<x-razorpay-checkout>Blade component
Requirements
| Package | Versions |
|---|---|
| PHP | 8.2, 8.3, 8.4 |
| Laravel | 11.x, 12.x, 13.x |
Installation
composer require rahulthalwal/laravel-razorpay
The service provider and the Razorpay facade are registered automatically.
Publish the config file (optional):
php artisan vendor:publish --tag=razorpay-config
Add your credentials to .env. Find your keys in the Razorpay Dashboard under Account & Settings → API Keys:
RAZORPAY_KEY_ID=rzp_test_xxxxxxxxxxxxxx RAZORPAY_KEY_SECRET=xxxxxxxxxxxxxxxxxxxxxxxx RAZORPAY_WEBHOOK_SECRET=your-webhook-secret # Optional RAZORPAY_CURRENCY=INR RAZORPAY_WEBHOOK_PATH=razorpay/webhook RAZORPAY_STORE_PAYMENTS=false RAZORPAY_CALLBACK_URL=https://your-app.test/payments/callback
Usage
Create an order
Pass amounts in rupees; the package converts them to paise (499.99 → 49999).
use RahulThalwal\LaravelRazorpay\Facades\Razorpay; $order = Razorpay::createOrder( amountInRupees: 499.99, receipt: 'order_rcpt_1001', notes: ['cart_id' => (string) $cart->id], ); $order->id; // "order_N5xyz..." $order->amount; // 49999
You can also inject the client instead of using the facade:
use RahulThalwal\LaravelRazorpay\RazorpayClient; public function store(RazorpayClient $razorpay) { $order = $razorpay->createOrder(1500); }
Show the checkout button
// CheckoutController public function show(Cart $cart) { $order = Razorpay::createOrder($cart->total, receipt: "cart_{$cart->id}"); return view('checkout', ['order' => $order]); }
{{-- resources/views/checkout.blade.php --}} <x-razorpay-checkout :order="$order" :callback-url="route('payments.callback')" description="Order #{{ $cart->id }}" :prefill="['name' => auth()->user()->name, 'email' => auth()->user()->email]" class="btn btn-primary" > Pay ₹{{ number_format($cart->total, 2) }} </x-razorpay-checkout>
The component loads checkout.js once per page and opens Razorpay Checkout when the button is clicked.
After a successful payment it POSTs razorpay_payment_id, razorpay_order_id and razorpay_signature
to the callback URL, together with your CSRF token. A normal web route works; you don't need a CSRF exception.
| Attribute | Default |
|---|---|
order |
required: an Order entity or array |
callback-url |
razorpay.checkout.callback_url |
name |
razorpay.checkout.name (your app name) |
description |
razorpay.checkout.description |
image |
razorpay.checkout.image |
prefill |
[] (name, email, contact) |
notes |
[] |
theme-color |
razorpay.checkout.theme_color |
button-text |
razorpay.checkout.button_text, or use the slot |
The button also dispatches razorpay:success and razorpay:failed DOM events (they bubble).
Without a callback URL, use these events to handle the result in JavaScript:
document.addEventListener('razorpay:success', (e) => console.log(e.detail.razorpay_payment_id)); document.addEventListener('razorpay:failed', (e) => console.warn(e.detail.description));
To customise the markup, publish the view with php artisan vendor:publish --tag=razorpay-views.
Verify the payment in a controller
Always verify the signature on the server before you mark an order as paid:
use Illuminate\Http\Request; use RahulThalwal\LaravelRazorpay\Facades\Razorpay; class PaymentCallbackController { public function __invoke(Request $request) { $data = $request->validate([ 'razorpay_order_id' => ['required', 'string'], 'razorpay_payment_id' => ['required', 'string'], 'razorpay_signature' => ['required', 'string'], ]); $valid = Razorpay::verifyPayment( $data['razorpay_order_id'], $data['razorpay_payment_id'], $data['razorpay_signature'], ); if (! $valid) { return redirect()->route('checkout')->withErrors('Payment verification failed.'); } Order::where('razorpay_order_id', $data['razorpay_order_id'])->update(['status' => 'paid']); return redirect()->route('orders.thank-you'); } }
// routes/web.php Route::post('/payments/callback', PaymentCallbackController::class)->name('payments.callback');
Fetch, capture and refund
$payment = Razorpay::fetchPayment('pay_N5xyz'); Razorpay::capturePayment('pay_N5xyz', 499.99); // for manual-capture payments Razorpay::refund('pay_N5xyz'); // full refund Razorpay::refund('pay_N5xyz', 100); // partial refund of ₹100
For anything not wrapped, use the underlying SDK:
$customer = Razorpay::api()->customer->create(['name' => 'Jane', 'email' => 'jane@example.com']); $link = Razorpay::api()->paymentLink->create([...]);
If RAZORPAY_KEY_ID or RAZORPAY_KEY_SECRET is missing, calls throw
RahulThalwal\LaravelRazorpay\Exceptions\RazorpayException with a message that says what to set.
Webhooks
The package registers POST /razorpay/webhook (route name razorpay.webhook). The route:
- Is excluded from CSRF verification.
- Verifies the
X-Razorpay-Signatureheader againstRAZORPAY_WEBHOOK_SECRETand returns 400 if it is missing or invalid. - Ignores duplicate deliveries of the same
X-Razorpay-Event-Id, so Razorpay's retries are only processed once. If processing throws, the id is released, so the next retry can still succeed. - Dispatches Laravel events.
Set up the webhook in Razorpay
- In the Razorpay Dashboard, go to Account & Settings → Webhooks → Add New Webhook.
- Webhook URL:
https://your-domain.com/razorpay/webhook - Secret: a strong random string. Put the same value in
RAZORPAY_WEBHOOK_SECRET. - Active events: at least
payment.captured,payment.failed,order.paidandrefund.processed. - Save. Test-mode and live-mode webhooks are configured separately.
Razorpay can't reach
localhost. For local development, expose your app with a tunnel such asngrok http 8000or Expose and use the public URL.
Listen to events
| Razorpay event | Laravel event |
|---|---|
| every webhook | RahulThalwal\LaravelRazorpay\Events\WebhookReceived |
payment.captured |
RahulThalwal\LaravelRazorpay\Events\PaymentCaptured |
payment.failed |
RahulThalwal\LaravelRazorpay\Events\PaymentFailed |
order.paid |
RahulThalwal\LaravelRazorpay\Events\OrderPaid |
refund.processed |
RahulThalwal\LaravelRazorpay\Events\RefundProcessed |
Every event has $payload (the full webhook body), $eventId, event() and entity('payment').
The specific events add helpers such as payment(), order() and refund().
namespace App\Listeners; use App\Models\Order; use RahulThalwal\LaravelRazorpay\Events\OrderPaid; class MarkOrderAsPaid { public function handle(OrderPaid $event): void { Order::where('razorpay_order_id', $event->order()['id']) ->update(['status' => 'paid', 'razorpay_payment_id' => $event->payment()['id']]); } }
Laravel discovers listeners in app/Listeners automatically. You can also register them yourself:
// AppServiceProvider::boot() Event::listen(OrderPaid::class, MarkOrderAsPaid::class); Event::listen(WebhookReceived::class, fn (WebhookReceived $e) => logger()->info('Razorpay webhook', [ 'event' => $e->event(), 'id' => $e->eventId, ]));
Make a listener ShouldQueue to keep webhook responses fast.
Webhook configuration
// config/razorpay.php 'webhook' => [ 'path' => env('RAZORPAY_WEBHOOK_PATH', 'razorpay/webhook'), // null disables the route 'middleware' => [], // extra middleware, e.g. ['throttle:60,1'] 'idempotency_ttl' => 60 * 60 * 24 * 7, // seconds to remember processed event ids 'cache_store' => null, // cache store for idempotency keys (null = default) ],
Idempotency uses your cache. In production, use a shared store (Redis, database, …) when you run more than one server.
Storing payments in the database
php artisan vendor:publish --tag=razorpay-migrations php artisan migrate
RAZORPAY_STORE_PAYMENTS=true
Every webhook that contains a payment (payment.*, order.paid, refund.*) then creates or updates a row
in razorpay_payments, keyed by payment_id:
| Column | Description |
|---|---|
order_id |
Razorpay order id |
payment_id |
Razorpay payment id (unique) |
amount |
Amount in paise |
currency |
e.g. INR |
status |
captured, failed, refunded, … |
method |
upi, card, netbanking, … |
email, contact |
Customer details |
notes |
JSON |
payload |
Raw webhook payload (JSON) |
use RahulThalwal\LaravelRazorpay\Models\RazorpayPayment; $payment = RazorpayPayment::where('order_id', $orderId)->latest()->first(); $payment->amountInRupees(); // 499.99 $payment->isCaptured(); // true RazorpayPayment::captured()->sum('amount');
Testing
composer test
The test suite uses Pest and Orchestra Testbench and never calls the Razorpay API.
In your own application you can mock the facade:
use RahulThalwal\LaravelRazorpay\Facades\Razorpay; Razorpay::shouldReceive('verifyPayment')->once()->andReturnTrue();
Changelog
See CHANGELOG.md.
Security
If you find a security issue, email rahulthalwal5@gmail.com instead of opening a public issue.
Credits
- Rahul Thalwal
- Built on the official razorpay/razorpay-php SDK
License
The MIT License (MIT). See LICENSE.md.