medusa-hdfc-payment
v0.0.8
Published
HDFC Payment Gateway Provider Plugin for MedusaJS 2
Maintainers
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:
- A Medusa v2 server set up
- An HDFC Bank merchant account with payment gateway access
- 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_KEYis 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
- Log in to your Medusa Admin
- Go to Settings → Regions
- Select the region where you want to enable HDFC payments
- In the Payment Providers section, ensure
hdfcis enabled - Save changes
Payment Flow
The HDFC payment provider supports the standard Medusa payment flow:
- Initiate Payment: Customer selects HDFC as payment method during checkout
- Redirect: Customer is sent to HDFC’s payment page (
payment_urlfrom initiate) - Return: After payment, HDFC redirects to your
return_urlwith query params (e.g.status,order_id,signature) - 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
- 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/captureis 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:
- Navigate to the order in Medusa Admin
- Go to the payment section
- Click "Refund" and specify the amount
- The refund will be processed through HDFC
Webhook Configuration
To receive real-time payment status updates, configure webhooks in your HDFC merchant dashboard:
- Log in to your HDFC merchant portal
- Navigate to Webhook Settings
- 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 arehdfcwhen the provider is registered withid: "hdfc".)
- 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:
- Environment – Set
HDFC_ENVIRONMENT=productionand use production credentials from HDFC. The plugin will callhttps://smartgateway.hdfc.bank.ininstead of the sandbox URL. - Response key – Configure
HDFC_RESPONSE_KEYso redirect and webhook payloads are verified with HMAC-SHA256. Recommended for production. - Logging – The plugin uses Medusa’s logger when available. In production, set your log level to
infoorwarnso that sensitive request/response payloads are not written to logs (verbose payload logging is atdebugonly). - Secrets – Keep
HDFC_MERCHANT_ID,HDFC_API_KEY,HDFC_PAYMENT_PAGE_CLIENT_ID, andHDFC_RESPONSE_KEYin 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, andHDFC_PAYMENT_PAGE_CLIENT_IDare 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 ascontextor equivalent so the plugin receivesstatus,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
datashapes) - 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 sessionauthorizePayment()- Authorize paymentcapturePayment()- Capture authorized paymentrefundPayment()- Process refundcancelPayment()- Cancel paymentgetPaymentStatus()- Get payment statusretrievePayment()- Retrieve payment detailsupdatePayment()- Update payment sessiondeletePayment()- Delete payment sessiongetWebhookActionAndData()- Process webhook events
Payment Status Values
The plugin returns standard Medusa payment statuses:
authorized- Payment is authorizedpending- Payment is pendingrequires_more- Additional action requirederror- Payment failedcanceled- Payment cancelled
🔒 Security Best Practices
- Never commit credentials: Always use environment variables
- Use HTTPS: Ensure all API calls are over HTTPS
- Validate webhooks: Verify webhook signatures from HDFC
- Monitor transactions: Regularly review payment logs
- Keep credentials secure: Rotate API keys periodically
🤝 Contributing
Contributions are welcome! If you find a bug or want to add a feature:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - 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
