Laravel Rust Razorpay
Take payments through Razorpay in a Laravel-Rust app: UPI, cards, netbanking, subscriptions and payment links.
Razorpay for Laravel for Rust
Accept payments through Razorpay in a Laravel for Rust application:
- An API client,
Inject<Razorpay>, for orders, payments, refunds, customers, payment links, plans and subscriptions. - Checkout: a ready-made payment page, or a
razorpay::buttonpartial for your own pages, with a callback route that verifies the payment and dispatchesPaymentVerified. - Webhooks: a route that verifies
X-Razorpay-Signatureand dispatches typed events such asOrderPaid,RefundProcessedandSubscriptionCharged. - Signature helpers for payments, subscriptions, payment links and webhooks, all compared in constant time.
razorpay:check: a command that checks your keys.
Every request goes through Laravel's HTTP client, so client::fake() intercepts it in your tests.
- Installation
- Configuration
- Taking a payment with Checkout
- Webhooks
- The API client
- Subscriptions
- Payment links
- Errors
- Testing
Installation
Add the crate:
cargo add laravel-rust-razorpay
Then register its service provider in src/app.rs:
use laravel::prelude::*;
Application::configure()
.with_providers(|providers| {
providers.add(razorpay::RazorpayServiceProvider);
})
Check your keys:
cargo run -- razorpay:check
Configuration
Add your keys to .env. Find them in the Razorpay Dashboard under Account & Settings → API Keys:
RAZORPAY_KEY_ID=rzp_test_xxxxxxxxxxxxxx
RAZORPAY_KEY_SECRET=xxxxxxxxxxxxxxxxxxxxxxxx
# Turns on the webhook route. Use the secret you enter when creating the webhook.
RAZORPAY_WEBHOOK_SECRET=
# Where Checkout sends the customer afterwards.
RAZORPAY_SUCCESS_URL=/orders/thanks
RAZORPAY_FAILURE_URL=/cart
| Variable | Default | Purpose |
|---|---|---|
RAZORPAY_KEY_ID |
unset | The public key ID (rzp_test_… or rzp_live_…). |
RAZORPAY_KEY_SECRET |
unset | The key secret. Never sent to the browser. |
RAZORPAY_WEBHOOK_SECRET |
unset | The webhook secret. The webhook route only exists when it's set. |
RAZORPAY_WEBHOOK_PATH |
/razorpay/webhook |
Where Razorpay posts webhooks. |
RAZORPAY_CALLBACK_ENABLED |
true |
Whether to register the callback route. Turn it off if you verify payments in your own handler. |
RAZORPAY_CALLBACK_PATH |
/razorpay/callback |
Where the checkout page posts a successful payment. |
RAZORPAY_SUCCESS_URL |
/ |
Where the customer goes after a verified payment. |
RAZORPAY_FAILURE_URL |
/ |
Where the customer goes when a payment can't be verified, or cancels. |
RAZORPAY_CHECKOUT_NAME |
APP_NAME |
The business name Checkout shows. |
RAZORPAY_CHECKOUT_IMAGE |
unset | A logo URL for Checkout. |
RAZORPAY_CHECKOUT_COLOR |
unset | Checkout's theme color, such as #3399cc. |
RAZORPAY_TIMEOUT |
30 |
Seconds to wait for the API. |
RAZORPAY_BASE_URL |
https://api.razorpay.com/v1 |
The API's base URL. |
Running without keys
Payments are optional. With neither RAZORPAY_KEY_ID nor RAZORPAY_KEY_SECRET set, the application starts normally and payments are off. This suits self-hosted installs, local development, CI and tests. API calls and signature checks then return RazorpayError::NotConfigured (503) without sending anything. Check first to hide payment features:
if razorpay.is_configured() {
// Show the "Upgrade" button...
}
The application refuses to start when only one of the two is set, or when the key ID doesn't start with rzp_.
To change a setting in code, use with_config:
use razorpay::RazorpayConfig;
Application::configure()
.with_config(|config, _| {
config.section_mut::<RazorpayConfig>().checkout_color = Some("#0f766e".into());
})
Taking a payment with Checkout
Create an order on the server, then return its Checkout page:
use laravel::prelude::*;
use laravel::view::View;
use razorpay::{CreateOrder, Razorpay};
pub async fn pay(razorpay: Inject<Razorpay>, user: Authenticated<User>) -> laravel::Result<View> {
let order = razorpay
.orders()
.create(CreateOrder::inr(49900).receipt("order-1234").note("user_id", user.id.to_string()))
.await?;
Ok(razorpay
.checkout(&order)
.description("Pro plan, 1 year")
.customer_name(&user.name)
.customer_email(&user.email)
.view())
}
Amounts are in paise: 49900 is ₹499.00.
The page opens Checkout as it loads. Once the customer pays, it posts the payment to RAZORPAY_CALLBACK_PATH, which:
- checks the
razorpay_signatureagainst your key secret, - dispatches
razorpay::PaymentVerified, - redirects to
RAZORPAY_SUCCESS_URL?razorpay_payment_id=…&razorpay_order_id=….
A signature that doesn't check out redirects to RAZORPAY_FAILURE_URL?razorpay_error=invalid_signature instead, without dispatching anything.
Listen for the verified payment:
use laravel::event::{Event, listener};
use razorpay::PaymentVerified;
#[listener]
pub async fn mark_order_paid(event: Event<PaymentVerified>) -> laravel::Result<()> {
// Find the order by `event.order_id` and mark it paid...
Ok(())
}
[!IMPORTANT] The browser can close before the callback runs. Fulfil orders from the
OrderPaidwebhook too, and make both paths idempotent.
Using your own page
To put the button on a page of your own, pass checkout.data() to your view and include the partial:
Ok(view("orders.pay", razorpay.checkout(&order).data()))
<!-- resources/views/orders/pay.html -->
{% extends "layouts.app" %}
{% block content %}
<h1>Complete your order</h1>
{% include "razorpay::button" %}
{% endblock %}
Set {% set razorpay_auto_open = true %} before the include to open Checkout as the page loads, or razorpay_button_label to change the button's text. To change the markup, copy either view to resources/views/vendor/razorpay/.
The inline scripts carry csp_nonce(), so they work under a nonce-based Content Security Policy.
Verifying payments yourself
To tie each payment to your own records, set RAZORPAY_CALLBACK_ENABLED=false, point Checkout at your route with .callback_url("/billing/verify"), and verify there with razorpay.verify_payment(..).
Building a front end yourself
With Inertia or another front end, pass checkout.options() (the JSON for new Razorpay(..), holding only the public key ID) to the page, and post Checkout's response to RAZORPAY_CALLBACK_PATH with your CSRF token. Or verify it in your own handler:
razorpay.verify_payment(&order_id, &payment_id, &signature)?; // responds 400 if forged
Webhooks
In the Razorpay Dashboard, go to Account & Settings → Webhooks, add https://your-app.com/razorpay/webhook, choose a secret and pick your events. Put the same secret in RAZORPAY_WEBHOOK_SECRET.
The route sits outside the web and api middleware groups, so no session, CSRF check or /api prefix applies. The signature authenticates each request: a missing or wrong signature gets a 400.
Every verified webhook dispatches razorpay::WebhookReceived. These events also dispatch a typed event from razorpay::events:
| Webhook | Event | Fields |
|---|---|---|
payment.authorized |
PaymentAuthorized |
payment |
payment.captured |
PaymentCaptured |
payment |
payment.failed |
PaymentFailed |
payment |
order.paid |
OrderPaid |
order, payment |
refund.created |
RefundCreated |
refund |
refund.processed |
RefundProcessed |
refund |
refund.failed |
RefundFailed |
refund |
payment_link.paid |
PaymentLinkPaid |
payment_link, payment |
payment_link.partially_paid |
PaymentLinkPartiallyPaid |
payment_link, payment |
payment_link.expired |
PaymentLinkExpired |
payment_link |
payment_link.cancelled |
PaymentLinkCancelled |
payment_link |
subscription.authenticated |
SubscriptionAuthenticated |
subscription |
subscription.activated |
SubscriptionActivated |
subscription |
subscription.charged |
SubscriptionCharged |
subscription, payment |
subscription.pending |
SubscriptionPending |
subscription |
subscription.halted |
SubscriptionHalted |
subscription |
subscription.paused |
SubscriptionPaused |
subscription |
subscription.resumed |
SubscriptionResumed |
subscription |
subscription.cancelled |
SubscriptionCancelled |
subscription |
subscription.completed |
SubscriptionCompleted |
subscription |
subscription.updated |
SubscriptionUpdated |
subscription |
Every typed event also has event_id (the X-Razorpay-Event-Id header) and webhook, the whole body.
use laravel::event::{Event, listener};
use razorpay::events::{OrderPaid, SubscriptionCharged};
#[listener]
pub async fn fulfil(event: Event<OrderPaid>) -> laravel::Result<()> {
let receipt = event.order.receipt.as_deref();
let user_id = event.payment.notes.get("user_id");
// Fulfil the order, once...
Ok(())
}
#[listener(queued)]
pub async fn extend_access(event: Event<SubscriptionCharged>) -> laravel::Result<()> {
// Extend `event.subscription.id` until `event.subscription.current_end`...
Ok(())
}
For any other webhook, listen to WebhookReceived and read entities with event.webhook.entity::<T>("name"), or read_entity to learn why one can't be read.
WebhookReceived is dispatched first, then the typed event. If a typed event's entity can't be read, such as a payment with no amount, the route reports RazorpayError::UnreadableWebhook and responds 500. The delivery isn't lost: Razorpay retries it, and WebhookReceived listeners have already seen the payload. Apart from id and amount, fields that Razorpay leaves out fall back to defaults (an empty string, or an Unknown status) rather than failing.
Razorpay retries a webhook until it gets a 2xx, and may deliver one more than once. A listener that returns an error makes the route respond 500 so Razorpay retries it later. Keep listeners idempotent, keyed on event_id or the entity's ID.
The API client
Inject Razorpay anywhere: handlers, listeners, jobs and commands. Every method returns razorpay::Result<T>.
use razorpay::{CreateRefund, ListParams, Razorpay};
// Orders
let order = razorpay.orders().fetch("order_EKwxwAgItmmXdp").await?;
let payments = razorpay.orders().payments(&order.id).await?;
let recent = razorpay.orders().all(&ListParams::new().count(20)).await?;
// Payments
let payment = razorpay.payments().fetch("pay_29QQoUBi66xm2f").await?;
razorpay.payments().capture(&payment.id, payment.amount, &payment.currency).await?;
// Refunds
let refund = razorpay.payments().refund(&payment.id, CreateRefund::full()).await?;
let refund = razorpay.payments().refund(&payment.id, CreateRefund::partial(10000).instant()).await?;
let refund = razorpay.refunds().fetch(&refund.id).await?;
// Customers
use razorpay::CreateCustomer;
let customer = razorpay
.customers()
.create(CreateCustomer::new("Gaurav Kumar", "gaurav@example.com", "+919000090000").or_existing())
.await?;
Statuses are enums, such as PaymentStatus::Captured. Each entity keeps fields this crate doesn't model in extra.
For an endpoint this crate doesn't wrap, use the authenticated request template:
let settlements: serde_json::Value = razorpay.send(razorpay.request().get("/settlements")).await?;
Subscriptions
use razorpay::{CreatePlan, CreateSubscription};
let plan = razorpay.plans().create(CreatePlan::monthly("Pro", 49900)).await?;
let subscription = razorpay
.subscriptions()
.create(CreateSubscription::new(&plan.id, 12).note("user_id", "42"))
.await?;
// Open Checkout to authorize it...
Ok(razorpay.checkout_subscription(&subscription).view())
// ...or send the customer to `subscription.short_url`.
razorpay.subscriptions().pause(&subscription.id).await?;
razorpay.subscriptions().resume(&subscription.id).await?;
razorpay.subscriptions().cancel(&subscription.id, true).await?; // at the end of the cycle
The callback route verifies subscription payments too, and PaymentVerified carries the subscription_id.
Payment links
use razorpay::{CreatePaymentLink, LinkCustomer, NotifyBy};
let link = razorpay
.payment_links()
.create(
CreatePaymentLink::inr(100000)
.description("Invoice #42")
.reference_id("INV-42")
.customer(LinkCustomer {
name: Some("Gaurav Kumar".into()),
email: Some("gaurav@example.com".into()),
contact: Some("+919000090000".into()),
})
.notify(true, true)
.callback_url("https://your-app.com/invoices/42/paid"),
)
.await?;
// Share `link.short_url`...
razorpay.payment_links().notify(&link.id, NotifyBy::Sms).await?;
razorpay.payment_links().cancel(&link.id).await?;
Razorpay adds the payment's details and a signature to the callback URL. Verify them before trusting them:
razorpay.verify_payment_link(&link_id, &reference_id, &status, &payment_id, &signature)?;
Errors
RazorpayError responds with a fitting status when a handler returns it with ?:
| Variant | Status | When |
|---|---|---|
Api(ApiError) |
502 |
Razorpay answered with an error. ApiError holds its status, code, description, field, source, step and reason. |
Connection |
503 |
Razorpay was unreachable or timed out. |
Decode |
502 |
Razorpay's answer wasn't the expected JSON. |
InvalidSignature |
400 |
A signature didn't match. |
NotConfigured |
503 |
RAZORPAY_KEY_ID or RAZORPAY_KEY_SECRET isn't set. |
UnreadableWebhook |
500 |
A verified webhook's entity couldn't be read. |
MissingSecret |
500 |
A check needs a secret that isn't set. |
match razorpay.payments().capture(id, amount, "INR").await {
Ok(payment) => { /* ... */ }
Err(error) if error.code() == Some("BAD_REQUEST_ERROR") => { /* ... */ }
Err(error) => return Err(error.into()),
}
Testing
Fake Razorpay with Laravel's HTTP client fake, and sign webhooks with razorpay::signature::sign:
use laravel::event;
use laravel::http::client;
use laravel::testing::prelude::*;
use razorpay::events::OrderPaid;
use serde_json::json;
#[laravel::test]
async fn checkout_creates_an_order(app: Application) {
let http = client::fake().with(
"api.razorpay.com/v1/orders",
json!({ "id": "order_1", "amount": 49900, "currency": "INR", "status": "created", "notes": [] }),
);
app.get("/pay").await.assert_ok().assert_see("order_1");
http.assert_sent(|request| request.data()["amount"] == 49900);
}
#[laravel::test]
async fn paid_orders_are_fulfilled(app: Application) {
let events = event::fake();
let body = json!({ "event": "order.paid", "payload": { /* ... */ } }).to_string();
app.post("/razorpay/webhook")
.header("content-type", "application/json")
.header("x-razorpay-signature", razorpay::signature::sign(&body, "your-test-webhook-secret"))
.body(body)
.await
.assert_ok();
events.assert_dispatched::<OrderPaid>();
}
Run the package's own tests with cargo test.
License
MIT.