Skip to content

Commit

Permalink
fixed: auto-capture, hooks, added additional debug logging
Browse files Browse the repository at this point in the history
  • Loading branch information
Govind Diwakar committed Sep 1, 2024
1 parent fc5d1eb commit 8b9730c
Show file tree
Hide file tree
Showing 7 changed files with 148 additions and 349 deletions.
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ In your environment file (.env) you need to define
RAZORPAY_ID=<your api key>
RAZORPAY_SECRET=<your api key secret>
RAZORPAY_ACCOUNT=<your razorpay account number/merchant id>
RAZORPAY_WEBHOOK_SECRET=<your web hook secret as defined in the webhook settings in the razorpay dashboard >
```
You need to add the plugin into your medusa-config.js as shown below
Expand All @@ -58,8 +59,8 @@ const plugins = [
automatic_expiry_period: 30, /*any value between 12 minutes and 30 days expressed in minutes*/
manual_expiry_period: 7200,
refund_speed: "normal",
webhook_secret: process.env.RAZORPAY_SECRET,
capture:"automatic"
webhook_secret: process.env.RAZORPAY_WEBHOOK_SECRET,
auto_capture: true // if you want to automatically capture,
}
},
...]
Expand Down
7 changes: 4 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "medusa-payment-razorpay",
"version": "7.2.4",
"version": "7.3.0",
"description": "Razorpay Payment provider for Medusa Commerce",
"main": "dist/index.js",
"repository": {
Expand All @@ -21,6 +21,7 @@
},
"devDependencies": {
"@medusajs/medusa": "^1.12.2",
"@types/body-parser": "^1.19.5",
"@types/jest": "^29.5.3",
"@typescript-eslint/eslint-plugin": "^5.41.0",
"@typescript-eslint/parser": "^5.41.0",
Expand All @@ -43,11 +44,11 @@
"typeorm": "^0.3.16"
},
"dependencies": {
"body-parser": "^1.19.0",
"body-parser": "1.19.2",
"express": "^4.17.1",
"medusa-core-utils": "^1.2.0",
"medusa-interfaces": "^1.3.7",
"razorpay": "^2.9.1"
"razorpay": "^2.9.4"
},
"gitHead": "81a7ff73d012fda722f6e9ef0bd9ba0232d37808",
"keywords": [
Expand Down
17 changes: 13 additions & 4 deletions src/api/hooks/razorpay.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
import { NotificationService } from "medusa-interfaces";
import Razorpay from "razorpay";
import { Logger } from "@medusajs/medusa";

export default async (req, res) => {
const webhookSignature = req.headers["x-razorpay-signature"];

const webhookSecret = process.env.RAZORPAY_WEBHOOK_SECRET;

const logger = req.scope.resolve("logger") as Logger;
logger.info(
`Received Razorpay webhook body : ${req.body} rawBody : ${req.rawBody}`
);

const validationResponse = Razorpay.validateWebhookSignature(
req.rawBody,
req.rawBody ?? req.body,
webhookSignature,
webhookSecret!
);
Expand All @@ -17,9 +22,13 @@ export default async (req, res) => {
return;
}

const event = req.body.event;
const data = JSON.parse(req.body);

const event = data.event;

const cartId = req.body.payload.payment.entity.notes.cart_id;
const cartId =
data.payload.payment.entity.notes.cart_id ??
data.payload.payment.entity.notes.resource_id;

// const razorpayProviderService = req.scope.resolve('pp_razorpay');
const orderService = req.scope.resolve("orderService");
Expand Down
7 changes: 6 additions & 1 deletion src/core/__tests__/razorpay-base.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,12 @@ if (!isMocksEnabled()) {
dotenv.config();
}
const container = {
logger: { error: console.error, info: console.log, warn: console.log },
logger: {
error: console.error,
info: console.info,
warn: console.warn,
debug: console.log,
},
cartService: {
retrieve(id: string): any {
return { id: "test-cart", billing_address: { phone: "12345" } };
Expand Down
34 changes: 22 additions & 12 deletions src/core/razorpay-base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -255,11 +255,11 @@ abstract class RazorpayBase extends AbstractPaymentProcessor {
(cart?.billing_address as any)?.gstin ??
(customer?.metadata?.gstin as string) ??
undefined;
if (!phone || !email) {
throw new Error(
"Razorpay-Provider didn't receive email or " +
"phone number to create razorpay customer"
);
if (!phone) {
throw new Error("phone number to create razorpay customer");
}
if (!email) {
throw new Error("email to create razorpay customer");
}
const firstName =
cart?.billing_address.first_name ?? customer.first_name ?? "";
Expand Down Expand Up @@ -396,7 +396,7 @@ abstract class RazorpayBase extends AbstractPaymentProcessor {
} catch (e) {
// if customer already exists in razorpay but isn't associated with a customer in medsusa
try {
this.logger.info("the relinking customer in razopay by polling");
this.logger.info("relinking customer in razorpay by polling");

razorpayCustomer = await this.fetchOrPollForCustomer(customer);
} catch (e) {
Expand Down Expand Up @@ -426,16 +426,24 @@ abstract class RazorpayBase extends AbstractPaymentProcessor {
} = context;

const sessionNotes = paymentSessionData.notes as Record<string, string>;
const intentRequest: Orders.RazorpayOrderCreateRequestBody = {
const intentRequest: Orders.RazorpayOrderCreateRequestBody & {
payment_capture?: Orders.RazorpayCapturePayment;
} = {
amount: Math.round(amount),
currency: currency_code.toUpperCase(),
notes: { ...sessionNotes, resource_id },
payment: {
capture: this.options_.capture ? "automatic" : "manual",
capture: this.options_.auto_capture ? "automatic" : "manual",
capture_options: {
refund_speed: this.options_.refund_speed ?? "normal",
automatic_expiry_period: this.options_.automatic_expiry_period ?? 5,
manual_expiry_period: this.options_.manual_expiry_period ?? 10,
automatic_expiry_period: Math.max(
this.options_.automatic_expiry_period ?? 20,
12
),
manual_expiry_period: Math.max(
this.options_.manual_expiry_period ?? 10,
7200
),
},
},
...intentRequestData,
Expand All @@ -450,19 +458,21 @@ abstract class RazorpayBase extends AbstractPaymentProcessor {
);
try {
if (razorpayCustomer) {
this.logger.debug(`the intent: ${JSON.stringify(intentRequest)}`);
session_data = await this.razorpay_.orders.create(intentRequest);
} else {
this.logger.error("unable to find razorpay customer");
}
} catch (e) {
return this.buildError(
"An error occurred in InitiatePayment during the creation of the razorpay payment intent",
"An error occurred in InitiatePayment during the creation of the razorpay payment intent: " +
JSON.stringify(e),
e
);
}
} catch (e) {
return this.buildError(
"An error occurred in creating customer request",
"An error occurred in creating customer request:" + e.message,
e
);
}
Expand Down
2 changes: 1 addition & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export interface RazorpayOptions {
/**
* Use this flag to capture payment immediately (default is false)
*/
capture?: string;
auto_capture?: boolean;
/**
* set `automatic_payment_methods` to `{ enabled: true }`
*/
Expand Down
Loading

0 comments on commit 8b9730c

Please sign in to comment.