Skip to content

Commit

Permalink
Fix the error in the Razorpay
Browse files Browse the repository at this point in the history
  • Loading branch information
swarnendu19 committed Sep 29, 2024
1 parent e94598c commit fcc029e
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 94 deletions.
86 changes: 28 additions & 58 deletions packages/node/src/lib/razorpay.ts
Original file line number Diff line number Diff line change
@@ -1,66 +1,36 @@
import { IRazorpayAuthResponse, IRazorpayOptions, IRazorpayOrderResponse, IRazorpayPayload } from "../types/razorpayTypes";
import { PayFetch } from "../utils/fetch";
import axios from 'axios';
import { PaymentGateway, PaymentConfig } from '../types/razorpayTypes';

export class Razorpay extends PayFetch {
constructor(private options: IRazorpayOptions) {
super();
}

private getApiBaseUrl() {
if (this.options.sandbox) {
return "https://api.sandbox.razorpay.com";
}
return "https://api.razorpay.com";
}

private getKeyId() {
return this.options.keyId;
}

private getKeySecret() {
return this.options.keySecret;
}
export class Razorpay implements PaymentGateway {
private apiKey: string = '';
private secretKey: string = '';

private getApiOrderUrl() {
return `${this.getApiBaseUrl()}/v1/orders`;
initialize(config: PaymentConfig): void {
this.apiKey = config.apiKey || '';
this.secretKey = config.secretKey || '';
}

async getAccessToken() {
const url = `${this.getApiBaseUrl()}/v1/auth`;

const auth = btoa(`${this.getKeyId()}:${this.getKeySecret()}`);

const [response] = await this.jsonFetch<IRazorpayAuthResponse>(url, {
method: "POST",
headers: {
Authorization: `Basic ${auth}`,
"Content-Type": "application/x-www-form-urlencoded",
},
body: "grant_type=client_credentials",
});

return response.access_token;
}

async createOrder(payload: IRazorpayPayload) {
const accessToken = await this.getAccessToken();

const [res] = await this.jsonFetch<IRazorpayOrderResponse>(
this.getApiOrderUrl(),
{
method: "POST",
body: JSON.stringify(payload),
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
async charge(amount: number, currency: string, customerDetails: any): Promise<any> {
try {
const response = await axios.post(
'https://api.razorpay.com/v1/orders',
{
amount: amount * 100,
currency: currency,
receipt: `receipt#${Math.floor(Math.random() * 100)}`,
payment_capture: 1,
},
}
);

if (!res.id) {
throw new Error("Failed to create order");
{
auth: {
username: this.apiKey,
password: this.secretKey,
},
}
);
return response.data;
} catch (error) {
//@ts-ignore
throw new Error(`Razorpay charge failed: ${error.response?.data?.error?.description || error.message}`);
}

return res;
}
}
47 changes: 11 additions & 36 deletions packages/node/src/types/razorpayTypes.ts
Original file line number Diff line number Diff line change
@@ -1,36 +1,11 @@
// Auth response after obtaining access token or API authentication
export interface IRazorpayAuthResponse {
access_token: string;
expires_in: number;
token_type: string;
}

// Options for initializing Razorpay client
export interface IRazorpayOptions {
keyId: string; // Razorpay API Key ID
keySecret: string; // Razorpay API Key Secret
sandbox?: boolean; // Whether to use sandbox environment or not
}

// Payload required to create a Razorpay order
export interface IRazorpayPayload {
amount: number; // Amount in the smallest currency unit (e.g., 100 for INR 1.00)
currency: string; // The currency in which the payment is to be made (e.g., "INR")
receipt?: string; // Receipt number for tracking
payment_capture?: number; // Auto capture (1) or manual capture (0)
notes?: Record<string, string>; // Additional notes
}

// Response after creating an order in Razorpay
export interface IRazorpayOrderResponse {
id: string; // Order ID
entity: string; // Entity type (e.g., "order")
amount: number; // Amount in the smallest currency unit
currency: string; // Currency used (e.g., "INR")
receipt: string; // Receipt number
status: string; // Status of the order (e.g., "created")
attempts: number; // Number of attempts for the payment
created_at: number; // Timestamp of when the order was created
notes?: Record<string, string>; // Any additional notes
}

export interface PaymentConfig {
apiKey?: string;
secretKey?: string;
clientId?: string;
secret?: string;
}

export interface PaymentGateway {
initialize(config: PaymentConfig): void;
charge(amount: number, currency: string, customerDetails: any): Promise<any>;
}

0 comments on commit fcc029e

Please sign in to comment.