Integrate the latest Razorpay payment APIs
Dear Developers and E-commerce Enthusiasts,
Are you ready to revolutionize the world of online stores with MedusaJS? We have an exciting opportunity that will make payment processing a breeze for our beloved Medusa platform! Introducing the Payment-Razorpay provider, a community-driven project that brings the immensely popular RAZORPAY payment gateway to our MedusaJS commerce stack.
What's in it for You:
🚀 Streamline Payment Processing: With Payment-Razorpay, you can unleash the full potential of Razorpay's features, ensuring seamless and secure payments for your customers.
🌐 Global Reach: Engage with customers worldwide, as Razorpay supports various currencies and payment methods, catering to a diverse audience.
🎉 Elevate Your Medusa Store: By sponsoring this provider, you empower the entire Medusa community, driving innovation and success across the platform.
For support or questions, please contact:
No hassle, no fuss! Install Payment-Razorpay effortlessly with npm:
RAZORPAY an immensely popular payment gateway with a host of features. This provider enables the razorpay payment interface on medusa commerce stack
Use the package manager npm to install Payment-Razorpay.
yarn add medusa-plugin-razorpay-v2Register for a razorpay account and generate the api keys In your environment file (.env) you need to define
1RAZORPAY_ID=<your api key>2RAZORPAY_SECRET=<your api key secret>3RAZORPAY_ACCOUNT=<your razorpay account number/merchant id>4RAZORPAY_WEBHOOK_SECRET=<your web hook secret as defined in the webhook settings in the razorpay dashboard >You need to add the provider into your medusa-config.ts as shown below
1module.exports = defineConfig({2
3...4
5 plugins: ["medusa-plugin-razorpay-v2"],6modules: [7 ...8 {9 resolve: "@medusajs/medusa/payment",10 dependencies: [Modules.PAYMENT, ContainerRegistrationKeys.LOGGER],11 options: {12 providers: [13 {14 resolve:15 "medusa-plugin-razorpay-v2/providers/payment-razorpay/src",16 id: "razorpay",17 options: {18 key_id:19 process?.env?.RAZORPAY_TEST_KEY_ID ??20 process?.env?.RAZORPAY_ID,21 key_secret:22 process?.env?.RAZORPAY_TEST_KEY_SECRET ??23 process?.env?.RAZORPAY_SECRET,24 razorpay_account:25 process?.env?.RAZORPAY_TEST_ACCOUNT ??26 process?.env?.RAZORPAY_ACCOUNT,27 automatic_expiry_period: 30 /* any value between 12minuts and 30 days expressed in minutes*/,28 manual_expiry_period: 20,29 refund_speed: "normal",30 webhook_secret:31 process?.env?.RAZORPAY_TEST_WEBHOOK_SECRET ??32 process?.env?.RAZORPAY_WEBHOOK_SECRET33 }34 },,35 ...] 36 }37 }38 ...]39})For the NextJs start you need to make the following changes
yarn add react-razorpaylike below
1import { Button } from "@medusajs/ui"2import Spinner from "@modules/common/icons/spinner"3import React, { useCallback, useEffect, useState } from "react"4import {useRazorpay, RazorpayOrderOptions } from "react-razorpay"5import { HttpTypes } from "@medusajs/types"6import { placeOrder, } from "@lib/data/cart"7import { CurrencyCode } from "react-razorpay/dist/constants/currency"8export const RazorpayPaymentButton = ({9 session,10 notReady,11 cart12}: {13 session: HttpTypes.StorePaymentSession14 notReady: boolean15 cart: HttpTypes.StoreCart16}) => {17 const [disabled, setDisabled] = useState(false)18 const [submitting, setSubmitting] = useState(false)19 const [errorMessage, setErrorMessage] = useState<string | undefined>(undefined)20 const {Razorpay21 } = useRazorpay();22 23 const [orderData,setOrderData] = useState({razorpayOrder:{id:""}})24
25 26 console.log(`session_data: `+JSON.stringify(session))27 const onPaymentCompleted = async () => {28 await placeOrder().catch(() => {29 setErrorMessage("An error occurred, please try again.")30 setSubmitting(false)31 })32 }33 useEffect(()=>{34 setOrderData(session.data as {razorpayOrder:{id:string}})35 },[session.data])36
37 38
39
40 const handlePayment = useCallback(async() => {41 const onPaymentCancelled = async () => {42 setErrorMessage("PaymentCancelled")43 setSubmitting(false)44 }45 46 const options: RazorpayOrderOptions = {47 key:process.env.NEXT_PUBLIC_RAZORPAY_KEY_ID??process.env.NEXT_PUBLIC_RAZORPAY_TEST_KEY_ID??"your_key_id",48 callback_url: `${process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL}/razorpay/hooks`,49 amount: session.amount*100*100,50 order_id: orderData.razorpayOrder.id,51 currency: cart.currency_code.toUpperCase() as CurrencyCode,52 name: process.env.COMPANY_NAME ?? "your company name ",53 description: `Order number ${orderData.razorpayOrder.id}`,54 remember_customer:true,55 56
57 image: "https://example.com/your_logo",58 modal: {59 backdropclose: true,60 escape: true,61 handleback: true,62 confirm_close: true,63 ondismiss: async () => {64 setSubmitting(false)65 setErrorMessage(`payment cancelled`)66 await onPaymentCancelled()67 },68 animation: true,69 },70 71 handler: async () => {72 onPaymentCompleted()73 },74 "prefill": {75 "name": cart.billing_address?.first_name + " " + cart?.billing_address?.last_name,76 "email": cart?.email,77 "contact": (cart?.shipping_address?.phone) ?? undefined78 },79 80 81 };82 console.log(JSON.stringify(options.amount))83 //await waitForPaymentCompletion();84 85 86 const razorpay = new Razorpay(options);87 if(orderData.razorpayOrder.id)88 razorpay.open();89 razorpay.on("payment.failed", function (response: any) {90 setErrorMessage(JSON.stringify(response.error))91 92 })93 razorpay.on("payment.authorized" as any, function (response: any) {94 const authorizedCart = placeOrder().then(authorizedCart=>{95 JSON.stringify(`authorized:`+ authorizedCart)96 })97 })98 // razorpay.on("payment.captured", function (response: any) {99
100 // }101 // )102 }, [Razorpay, cart.billing_address?.first_name, 103 cart.billing_address?.last_name, cart.currency_code,104 cart?.email, cart?.shipping_address?.phone, orderData.razorpayOrder.id, 105 session.amount, session.provider_id]);106 console.log("orderData"+JSON.stringify(orderData))107 return (108 <>109 <Button110 disabled={submitting || notReady || !orderData?.razorpayOrder?.id||orderData?.razorpayOrder?.id == ''}111 onClick={()=>{112 console.log(`processing order id: ${orderData.razorpayOrder.id}`)113 handlePayment()}114 }115 >116 {submitting ? <Spinner /> : "Checkout"}117 </Button>118 {errorMessage && (119 <div className="text-red-500 text-small-regular mt-2">120 {errorMessage}121 </div>122 )}123 </>124 )125}Step 3.
nextjs-starter-medusa/src/lib/constants.tsx add
1export const isRazorpay = (providerId?: string) => {2 return providerId?.startsWith("pp_razorpay")3}4
5// and the following to the list6export const paymentInfoMap: Record<7 string,8 { title: string; icon: React.JSX.Element }9> = {...10 pp_razorpay_razorpay: {11 title: "Razorpay",12 icon: <CreditCard />,13 },14 ...}step 4.add into the payment element
first
import import {RazorpayPaymentButton} from "./razorpay-payment-button"then
1case "razorpay":2 return <RazorpayPaymentButton session={paymentSession} notReady={notReady} cart={cart} />Step 4. Add environment variables in the client
NEXT_PUBLIC_RAZORPAY_KEY:
Step 6. Caveat the default starter template has an option which says use the same shipping and billing address please ensure you deselect this and enter the phone number manually in the billing section.
Step 7.
In razorpay create a webhook with the following url
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
Please make sure to update tests as appropriate.
These features exists, but without implementing the client it isn't possible to tests these outright
The code was tested on limited number of usage scenarios. There maybe unforseen bugs, please raise the issues as they come, or create pull requests if you'd like to submit fixes.
Dear Medusa Enthusiasts,
I hope this message finds you all in high spirits and enthusiasm for the world of e-commerce! Today, I reach out to our vibrant Medusa community with a heartfelt appeal that will strengthen our collective journey and elevate our online stores to new heights. I am thrilled to present the Payment-Razorpay provider, a community-driven project designed to streamline payment processing for our beloved Medusa platform.
As a dedicated member of this community, I, SGFGOV, have invested my time and passion into crafting this valuable provider that bridges the gap between online retailers and their customers. It is with great humility that I invite you to participate in this open-source initiative by sponsoring the Payment-Razorpay provider through GitHub.
Your sponsorship, no matter the size, will make a world of difference in advancing the Medusa ecosystem. It will empower me to focus on the continuous improvement and maintenance of the Payment-Razorpay provider, ensuring it remains reliable, secure, and seamlessly integrated with Medusa.
Being a community provider, perks are not the focus of this appeal. Instead, I promise to give back to the community by providing fast and efficient support via Discord or any other means. Your sponsorship will help sustain and enhance the provider's development, allowing me to be responsive to your needs and address any concerns promptly.
Let's come together and demonstrate the power of community collaboration. By sponsoring the Payment-Razorpay provider on GitHub, you directly contribute to the success of not only this project but also the broader Medusa ecosystem. Your support enables us to empower developers, merchants, and entrepreneurs, facilitating growth and success in the world of e-commerce.
To show your commitment and be part of this exciting journey, kindly consider sponsoring the Payment-Razorpay provider on GitHub. Your contribution will amplify the impact of our community and foster a supportive environment for all.
Thank you for your time, and thank you for being an integral part of our Medusa community. Together, we will elevate our online stores and create extraordinary experiences for customers worldwide.
With warm regards,
SGFGOV Lead Developer, Payment-Razorpay Provider for Medusa