npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

medusa-hdfc-payment

v0.0.8

Published

HDFC Payment Gateway Provider Plugin for MedusaJS 2

Readme

Medusa HDFC Payment Provider Plugin

🚀 Overview

The Medusa HDFC Payment Provider Plugin integrates HDFC Bank's payment gateway directly into your Medusa store.

Process payments securely through HDFC's payment gateway with support for authorization, capture, refunds, and payment status tracking—all seamlessly integrated with Medusa's checkout flow.

Compatible with Medusa v2.0+

✨ Key Features

| Feature | Description | | :--- | :--- | | 💳 Payment Authorization | Authorize payments securely through HDFC's payment gateway | | ✅ Payment Capture | Capture authorized payments to complete transactions | | ↩️ Refund Support | Process full or partial refunds for captured payments | | 🚫 Payment Cancellation | Cancel pending payments before completion | | 📊 Status Tracking | Real-time payment status tracking and updates | | 🔐 Secure Integration | Secure API authentication with merchant credentials | | 🌍 Sandbox & Production | Support for both sandbox and production environments | | 📱 Webhook Support | Handle payment webhooks for real-time status updates | | 👤 Account holder stubs | Implements createAccountHolder / deleteAccountHolder so Medusa does not warn; saved payment methods are not supported |

📋 Prerequisites

Before you begin, ensure you have:

  1. A Medusa v2 server set up
  2. An HDFC Bank merchant account with payment gateway access
  3. HDFC API credentials:
    • Merchant ID
    • API Key
    • Payment Page Client ID
    • Response Key (optional; for redirect and webhook signature verification)

🛠️ Installation

Install the plugin using your preferred package manager:

npm install medusa-hdfc-payment
# or
yarn add medusa-hdfc-payment

⚙️ Configuration

1. Environment Variables

Add your HDFC credentials to your .env file.

[!WARNING] Security Note: Never commit your actual API credentials to version control (git).

HDFC_MERCHANT_ID="your_merchant_id"
HDFC_API_KEY="your_api_key"
HDFC_PAYMENT_PAGE_CLIENT_ID="your_payment_page_client_id"
HDFC_RESPONSE_KEY="your_response_key"  # optional; for redirect/webhook signature verification
HDFC_ENVIRONMENT="sandbox"  # or "production"
HDFC_RETURN_URL="https://yourstore.com/payment/return"
HDFC_CANCEL_URL="https://yourstore.com/payment/cancel"

Note: HDFC_RESPONSE_KEY is optional. When set, the plugin verifies redirect and webhook payloads using HMAC-SHA256. Omit it if your HDFC setup does not use response signing.

2. Medusa Config

Register the plugin in your medusa-config.js (or medusa-config.ts) file. Add it to the modules section for the payment provider.

module.exports = defineConfig({
  // ... other config
  modules: [
    {
      resolve: "@medusajs/medusa/payment",
      options: {
        providers: [
          {
            resolve: "medusa-hdfc-payment",
            id: "hdfc",
            options: {
              merchant_id: process.env.HDFC_MERCHANT_ID,
              api_key: process.env.HDFC_API_KEY,
              payment_page_client_id: process.env.HDFC_PAYMENT_PAGE_CLIENT_ID,
              response_key: process.env.HDFC_RESPONSE_KEY,
              environment: process.env.HDFC_ENVIRONMENT || "sandbox",
              return_url: process.env.HDFC_RETURN_URL,
              cancel_url: process.env.HDFC_CANCEL_URL,
            },
          },
        ],
      },
    },
  ],
});

3. TypeScript Configuration

If you're using TypeScript, ensure your medusa-config.ts is properly typed:

import { defineConfig } from "@medusajs/framework"

export default defineConfig({
  // ... other config
  modules: [
    {
      resolve: "@medusajs/medusa/payment",
      options: {
        providers: [
          {
            resolve: "medusa-hdfc-payment",
            id: "hdfc",
            options: {
              merchant_id: process.env.HDFC_MERCHANT_ID!,
              api_key: process.env.HDFC_API_KEY!,
              payment_page_client_id: process.env.HDFC_PAYMENT_PAGE_CLIENT_ID!,
              response_key: process.env.HDFC_RESPONSE_KEY,
              environment: (process.env.HDFC_ENVIRONMENT as "sandbox" | "production") || "sandbox",
              return_url: process.env.HDFC_RETURN_URL,
              cancel_url: process.env.HDFC_CANCEL_URL,
            },
          },
        ],
      },
    },
  ],
})

💻 Usage Guide

Enabling the Provider

  1. Log in to your Medusa Admin
  2. Go to SettingsRegions
  3. Select the region where you want to enable HDFC payments
  4. In the Payment Providers section, ensure hdfc is enabled
  5. Save changes

Payment Flow

The HDFC payment provider supports the standard Medusa payment flow:

  1. Initiate Payment: Customer selects HDFC as payment method during checkout
  2. Redirect: Customer is sent to HDFC’s payment page (payment_url from initiate)
  3. Return: After payment, HDFC redirects to your return_url with query params (e.g. status, order_id, signature)
  4. Authorize: Your frontend must call the Medusa authorize endpoint and pass those redirect params in the request body so the plugin can verify the payment without calling the Order Status API
  5. Capture / Refund: Capture after order confirmation; refunds via admin or API

Important: If authorize is called with an empty context (no redirect params), the plugin falls back to the HDFC Order Status API. If that returns “Order Not Found”, the plugin may still mark the session as authorized using stored data, but for reliable verification you should pass the redirect params from the HDFC return URL into the authorize request.

Processing Payments

Authorization

When a customer selects HDFC as their payment method, the plugin will:

  • Create a payment session with HDFC
  • Redirect customer to HDFC payment page (if required)
  • Authorize the payment amount

Capture (auto-capture, no manual step)

For HDFC online payments the plugin uses auto-capture: when the customer completes payment on HDFC’s page, the gateway reports CHARGED. The plugin reports this to Medusa as captured in authorizePayment, so:

  • The payment is not left in “authorized” state.
  • No manual “Capture payment” in Admin and no call to POST /admin/payments/:id/capture is required.
  • Order is marked paid as soon as authorization succeeds (CHARGED).

This matches Option 1 (authorize + capture in one step at gateway; return captured from the provider). Webhooks can still be used for reliability; the plugin does not depend on the admin capture API.

Refunds

To process a refund:

  1. Navigate to the order in Medusa Admin
  2. Go to the payment section
  3. Click "Refund" and specify the amount
  4. The refund will be processed through HDFC

Webhook Configuration

To receive real-time payment status updates, configure webhooks in your HDFC merchant dashboard:

  1. Log in to your HDFC merchant portal
  2. Navigate to Webhook Settings
  3. Add your webhook URL. Medusa exposes payment provider webhooks at:
    • https://your-backend.com/hooks/payment/hdfc_hdfc
      (Use your API base URL; the path is /hooks/payment/[identifier]_[provider] — both are hdfc when the provider is registered with id: "hdfc".)
  4. Select events to receive (e.g. payment completed, refunded, failed).

No code or env changes are required in your backend to receive webhooks: the plugin already implements getWebhookActionAndData. Optional: set HDFC_RESPONSE_KEY in env (and in plugin options) if HDFC signs webhook payloads so the plugin can verify them.

Production

The plugin is suitable for production use. When going live:

  1. Environment – Set HDFC_ENVIRONMENT=production and use production credentials from HDFC. The plugin will call https://smartgateway.hdfc.bank.in instead of the sandbox URL.
  2. Response key – Configure HDFC_RESPONSE_KEY so redirect and webhook payloads are verified with HMAC-SHA256. Recommended for production.
  3. Logging – The plugin uses Medusa’s logger when available. In production, set your log level to info or warn so that sensitive request/response payloads are not written to logs (verbose payload logging is at debug only).
  4. Secrets – Keep HDFC_MERCHANT_ID, HDFC_API_KEY, HDFC_PAYMENT_PAGE_CLIENT_ID, and HDFC_RESPONSE_KEY in environment variables or a secrets manager; never commit them.

🐛 Troubleshooting

Payment Authorization Issues

"Authentication failed with HDFC payment gateway"

  • Verify your HDFC_MERCHANT_ID, HDFC_API_KEY, and HDFC_PAYMENT_PAGE_CLIENT_ID are correct
  • Ensure credentials match your environment (sandbox vs production)
  • Check that your HDFC merchant account is active

"Missing required fields: order_id, amount, currency"

  • Ensure the payment context includes all required fields
  • Verify the order data is properly formatted
  • Check Medusa logs for detailed error messages

Payment Capture Issues

"Order Not Found" when authorizing (API fallback)

  • Cause: Authorize was called without the redirect params that HDFC sends to your return URL (e.g. status, order_id, signature). The plugin then calls the HDFC Order Status API, which may return 400 "Order Not Found" depending on environment or ID format.
  • Fix: On the page HDFC redirects to (your return_url), read the query params and pass them into the Medusa authorize payment-session request (e.g. in the request body as context or equivalent so the plugin receives status, order_id, etc.). Then the plugin can authorize from the redirect data and does not need to call the status API.
  • The plugin will still authorize using stored session data if the API returns Order Not Found (fallback), but passing redirect params is the recommended approach.

"Missing transaction_id in payment session data"

  • Ensure payment was successfully authorized before attempting capture
  • Verify payment session data is properly stored (the plugin reads from both flat and nested data shapes)
  • Check that the transaction ID or order ID is returned from authorization

"Failed to capture payment with HDFC"

  • Verify the payment is in an authorized state
  • Check if the authorization has expired
  • Ensure sufficient funds are available
  • Review HDFC API logs for specific error codes

Refund Issues

"Payment declined: [error message]"

  • Verify the payment was successfully captured before refunding
  • Check refund amount doesn't exceed captured amount
  • Ensure refund is within the allowed time window
  • Review HDFC refund policies

Environment Issues

Sandbox vs Production

  • Sandbox: Use for testing with test credentials
  • Production: Use for live transactions with production credentials
  • Ensure you're using the correct credentials for your selected environment
  • API endpoints differ between environments

API Connection Issues

Cancel returns 404 when switching payment method

  • When the customer switches from HDFC to another method (or creates a new session), Medusa cancels the previous HDFC session. The plugin calls HDFC’s cancel endpoint; HDFC UAT/production may return 404 (order not found or cancel not supported). This is treated as success so the flow continues; only non-404 errors are logged as warnings.

"Rate limit exceeded"

  • HDFC API has rate limits per merchant
  • Implement retry logic with exponential backoff
  • Contact HDFC support to increase rate limits if needed

"Network timeout"

  • Check your server's internet connectivity
  • Verify HDFC API endpoints are accessible
  • Increase timeout values if needed (default: 30 seconds)

📚 API Reference

Payment Provider Methods

The plugin implements all required Medusa payment provider methods:

  • initiatePayment() - Initialize payment session
  • authorizePayment() - Authorize payment
  • capturePayment() - Capture authorized payment
  • refundPayment() - Process refund
  • cancelPayment() - Cancel payment
  • getPaymentStatus() - Get payment status
  • retrievePayment() - Retrieve payment details
  • updatePayment() - Update payment session
  • deletePayment() - Delete payment session
  • getWebhookActionAndData() - Process webhook events

Payment Status Values

The plugin returns standard Medusa payment statuses:

  • authorized - Payment is authorized
  • pending - Payment is pending
  • requires_more - Additional action required
  • error - Payment failed
  • canceled - Payment cancelled

🔒 Security Best Practices

  1. Never commit credentials: Always use environment variables
  2. Use HTTPS: Ensure all API calls are over HTTPS
  3. Validate webhooks: Verify webhook signatures from HDFC
  4. Monitor transactions: Regularly review payment logs
  5. Keep credentials secure: Rotate API keys periodically

🤝 Contributing

Contributions are welcome! If you find a bug or want to add a feature:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

📄 License

This project is licensed under the MIT License.

📞 Support

For issues and questions:

  • Plugin Issues: Open an issue on GitHub
  • HDFC API Support: Contact HDFC merchant support
  • Medusa Support: Visit Medusa Discord