Giter Club home page Giter Club logo

medusa-payment-razorpay's Introduction

MEDUSA-PAYMENT-RAZORPAY

Support the Medusa-Payment-Razorpay Plugin - Elevate Our Medusa Community!

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 Medusa-Payment-Razorpay plugin, 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 Medusa-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 plugin, you empower the entire Medusa community, driving innovation and success across the platform.

Installation Made Simple

No hassle, no fuss! Install Medusa-Payment-Razorpay effortlessly with npm:

npm install medusa-payment-razorpay



[RAZORPAY](https://razorpay.com) an immensely popular payment gateway with a host of features. 
This plugin enables the razorpay payment interface on [medusa](https://medusajs.com) commerce stack

## Installation

Use the package manager npm to install medusa-payment-razorpay.

```bash
npm install medusa-payment-razorpay

Usage

Register for a razorpay account and generate the api keys 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>

You need to add the plugin into your medusa-config.js as shown below

const plugins = [
  ...,
  {
    resolve:`medusa-payment-razorpay`,
    options:{
         key_id: process.env.RAZORPAY_ID,
                key_secret: process.env.RAZORPAY_SECRET,
                razorpay_account: process.env.RAZORPAY_ACCOUNT,                
                automatic_expiry_period: 30, /*any value between 12 minutes and 30 days expressed in minutes*/
                manual_expiry_period: 20,
                refund_speed: "normal", 
                webhook_secret: process.env.RAZORPAY_SECRET,
    }
  },
  ...]

Client side configuration

For the NextJs start you need to make the following changes

  1. Install package to your next starter. This just makes it easier, importing all the scripts implicitly
yarn add react-razorpay

  1. Create a button for Razorpay /src/modules/checkout/components/payment-button/razorpay-payment-button.tsx

like below

import { Button } from "@medusajs/ui"
import { Cart,PaymentSession } from "@medusajs/medusa"
import Spinner from "@modules/common/icons/spinner"
import React, { useCallback, useState } from "react"
import useRazorpay, { RazorpayOptions } from "react-razorpay"

export const RazorpayPaymentButton = ({
  session,
  notReady,
  cart
}: {
  session: PaymentSession
  notReady: boolean
  cart: Omit<Cart, "refundable_amount" | "refunded_total">
}) => {
  const [disabled, setDisabled] = useState(false)
  const [submitting, setSubmitting] = useState(false)
  const [errorMessage, setErrorMessage] = useState<string | undefined>(undefined)
  const [Razorpay] = useRazorpay();

  const orderData = session.data as Record<string, string>
  const onPaymentCompleted = async () => {
    await placeOrder().catch(() => {
      setErrorMessage("An error occurred, please try again.")
      setSubmitting(false)
    })
  }


  const handlePayment = useCallback(() => {
    const options: RazorpayOptions = {
      callback_url: `${process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL}/razorpay/hooks`,
      key: process.env.NEXT_PUBLIC_RAZORPAY_KEY ?? '',
      amount: session.amount.toString(),
      order_id: orderData.id,
      currency: cart.region.currency_code.toLocaleUpperCase(),
      name: process.env.COMPANY_NAME ?? "your company name ",
      description: `Order number ${orderData.id}`,

      image: "https://example.com/your_logo",
      modal: {
        backdropclose: true,
        escape: true,
        handleback: true,
        confirm_close: true,
        ondismiss: () => {
          setSubmitting(false)
        },
        animation: true,
      },
      handler: async (args) => {
        onPaymentCompleted()
      },
      "prefill": {
        "name": cart?.billing_address.first_name + " " + cart?.billing_address.last_name,
        "email": cart?.email,
        "contact": (cart?.shipping_address?.phone) ?? undefined
      },
      "notes": {
        "address": cart?.billing_address,
        "order_notes": session.data.notes
      },
      
    };

    const razorpay = new Razorpay(options);
    razorpay.open();
    razorpay.on("payment.failed", function (response: any) {
      setErrorMessage(JSON.stringify(response.error))
    })
    razorpay.on("payment.authorized", function (response: any) {

    })
    razorpay.on("payment.captured", function (response: any) {

    }
    )
  }, [Razorpay]);
  return (
    <>
      <Button
        disabled={submitting || notReady}
        onClick={handlePayment}
      >
        {submitting ? <Spinner /> : "Checkout"}
      </Button>
      {errorMessage && (
        <div className="text-red-500 text-small-regular mt-2">
          {errorMessage}
        </div>
      )}
    </>
  )
}

Step 3.

nextjs-starter-medusa/src/lib/constants.tsx add


  razorpay: {
    title: "Razorpay",
    icon: <CreditCard />,
  },

step 4.add into the payment element /src/modules/checkout/components/payment-button/index.tsx

first

import import {RazorpayPaymentButton} from "./razorpay-payment-button"

then

case "razorpay":
         return <RazorpayPaymentButton session={paymentSession} notReady={notReady} cart={cart} />

Step 4. Add environment variables in the client

NEXT_PUBLIC_RAZORPAY_KEY: NEXT_PUBLIC_SHOP_NAME: NEXT_PUBLIC_SHOP_DESCRIPTION:

watch out

Step 5. 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.

Contributing

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.

License

MIT

Untested features

These features exists, but without implementing the client it isn't possible to tests these outright

  1. Capture Payment
  2. Refund

Disclaimer

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.

Support the Medusa-Payment-Razorpay Plugin - Strengthen Our Medusa Community!

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 Medusa-Payment-Razorpay plugin, 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 plugin 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 Medusa-Payment-Razorpay plugin 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 Medusa-Payment-Razorpay plugin, ensuring it remains reliable, secure, and seamlessly integrated with Medusa.

Being a community plugin, 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 plugin'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 Medusa-Payment-Razorpay plugin 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 Medusa-Payment-Razorpay plugin 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, Medusa-Payment-Razorpay Plugin for Medusa

medusa-payment-razorpay's People

Contributors

hemann55 avatar sgfgov avatar suganyasai1026 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

medusa-payment-razorpay's Issues

order_id is missing in initiatePayment & updatePayment methods

order_id is required to pass in methodsinitiatePayment & updatePayment through PaymentProcessorContext which is coming from @medusajs/medusa library.
As of current, @medusajs/medusa interface PaymentProcessorContext does not hold the field order_id.
Is there way it can be override and pass through the mentioned method.

Please refer the open ticket in medusa Bug:6511

Unable to refund payment

while trying to refund payment from medusa admin i get following error

error: 'order_id' is mandatory Error: order_id is mandatory at Object.fetch (/project/node_modules/razorpay/dist/resources/orders.js:57:15) at RazorpayProviderService._callee17$ (/project/node_modules/medusa-payment-razorpay/services/razorpay-provider.js:455:41)

I believe below line causing the error
code

i checked the cart data of payment and found that it has payment.data.id not paymentData.data.order_id,
now i would have made a PR but i'm not familiar much with packages because i never did but ill try after buying some time

404 after completing an order

Bug report

Describe the bug

Medusa store redirects to 'http://localhost:8000/order/confirmed/cart_xxxx....' after the completion of the order. Hence, the cart doesn't convert into an order despite running the completeCheckout mutation.

I am using the razorpay plugin for medusa (https://github.com/SGFGOV/medusa-payment-razorpay)

System information

Medusa version (including plugins):

    "@medusajs/admin": "6.0.3",
    "@medusajs/cache-inmemory": "1.8.8",
    "@medusajs/cache-redis": "1.8.8",
    "@medusajs/event-bus-local": "1.9.6",
    "@medusajs/event-bus-redis": "1.8.9",
    "@medusajs/medusa": "1.12.3",
    "body-parser": "1.20.2",
    "cors": "^2.8.5",
    "dotenv": "16.3.1",
    "express": "4.18.2",
    "medusa-file-spaces": "^1.3.7",
    "medusa-fulfillment-manual": "1.1.38",
    "medusa-interfaces": "^1.3.7",
    "medusa-payment-manual": "1.0.24",
    "medusa-payment-razorpay": "^3.0.2",
    "medusa-plugin-algolia": "^0.2.19",
    "typeorm": "0.3.17"

Node.js version: v20.2.0
Database: Postgres (supabase)
Operating system: MacOS 13.2.1
Browser (if relevant): Arc

Steps to reproduce the behavior

  1. Select the product and checkout, filling all the details. Since I am using the razorpay, so fill the test cards and complete the checkout.
  2. When the payment is complete, storefront redirects to a confirm page with a cart id instead of an order id, and the order is not created in the database.

Expected behavior

Order should have been created in the database and the redirect URL should contain the order ID starting with order_xxx.., instead of a cart id cart_xxx...

Screenshots

If applicable, add screenshots to help explain your problem

Code snippets

Checkout-Context- https://gist.github.com/imprakharshukla/3b3b819aa32da89051dae410b6a0137f
payment-button: - https://gist.github.com/imprakharshukla/4150620a3a32b5a62bffd0477a0925b2

Additional context

Server Logs- https://gist.github.com/imprakharshukla/96d03fde9ddbb535b52c87147148948c
Frontend Logs- https://gist.github.com/imprakharshukla/3cea82e6929bfe746823133c5b7ecb5f
Frontend Console output- https://gist.github.com/imprakharshukla/d63e4d54d7c0ab0646ba11236875552e

I am using the razorpay plugin for medusa (https://github.com/SGFGOV/medusa-payment-razorpay)

Capturing payments

Heyy,
So I have been testing this plugin for couple of days now and i found out that after a successful payment the store admin have to manually capture the payment from the dashboard. The work around i did was just calling the capturePayment method inside the authorizePayment , this would change the status to captured in the razorpay dashboard but it is still Awaiting payment in the admin dashboard and the button to capture still exists.

I'm not sure but I'm guessing it has to do with events and subscription

Have you found a way to work it out?

implementation of razorpay in client side is missing the file useCheckout' and An error occurred in updatePayment:\r\n`order_id` is mandatory'

my plugin on server side
const plugins = [
{
resolve: medusa-payment-razorpay,
options: {
key_id:RAZORPAY_ID?? "",
key_secret: process.env.RAZORPAY_SECRET ?? "",
razorpay_account: process.env.RAZORPAY_ACCOUNT ?? "",
automatic_expiry_period: 30,
// /any value between 12minuts and 30 days expressed in minutes/
manual_expiry_period: 20,
refund_speed: "normal",
// webhook_secret: process.env.RAZORPAY_SECRET,
}
},
implementation document : https://medusajs.com/plugins/medusa-payment-razorpay/
and also implementation of razorpay in client side is missing the file useCheckout (` import { useCheckout } from "@lib/context/checkout-context")

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.