Razorpay
Collect payments.
import crypto from 'crypto';
import RazorpaySdk from 'razorpay';
import payment from '@/constants/payment';
type RazorpayPaymentDataInput {
razorpay_payment_id: string;
razorpay_order_id: string;
razorpay_signature: string;
}
type PaymentResponse = {
id: string;
entity: string;
amount: number;
currency: string;
status: string;
order_id: string;
invoice_id?: string | null;
international: boolean;
method: string;
amount_refunded: number;
refund_status?: null | string;
captured: boolean;
description: string;
error_code?: string | null;
error_description?: string | null;
error_source?: string | null;
error_step?: string | null;
error_reason?: string | null;
created_at: number;
};
type OrderResponse = {
id: string;
entity: string;
amaount: number;
currency: string;
receipt: string;
status: string;
attempts: number;
created_at: number;
};
class Razorpay {
#client;
constructor(config = payment.RAZORPAY_CLIENT_CONFIG) {
this.#client = new RazorpaySdk(config);
}
async createOrder({
amount,
receipt,
currency = payment.RAZORPAY_DEFAULT_CURRENCY,
}: {
amount: number;
receipt: string;
currency?: string;
}): Promise<OrderResponse> {
return this.#client.orders.create({
amount,
receipt,
currency,
});
}
async fetchPayment(paymentId: string): Promise<PaymentResponse> {
return this.#client.payments.fetch(paymentId);
}
static isPaymentLegit(
orderId: string,
paymentData: RazorpayPaymentDataInput,
): boolean {
const shasum = crypto.createHmac(
'sha256',
payment.RAZORPAY_CLIENT_CONFIG.key_secret,
);
shasum.update(`${orderId}|${paymentData.razorpay_payment_id}`);
const digest = shasum.digest('hex');
return digest === paymentData.razorpay_signature;
}
}
export default Razorpay;