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 🙏

© 2024 – Pkg Stats / Ryan Hefner

multigatepay

v1.0.1

Published

unified payment gateway that can help integrate multiple payment gateways using a single library

Downloads

5

Readme

MultiGatePay

A unified and extensible payment package for Node.js that supports multiple payment gateways, including Stripe, Razorpay, and others. This package simplifies the process of creating checkout sessions and verifying payments across different payment gateways with a single, unified interface.

Table of Contents

Features

  • Multiple Gateway Support: Integrates with popular payment gateways like Stripe and Razorpay.
  • Unified API: Provides a single interface for managing payments across different gateways.
  • Extensible: Easily add support for new payment gateways.
  • Customizable: Configure checkout details and payment verification according to your needs.

Installation

Install the package via npm:

npm install multigatepay

Configuration

Stripe Configuration

To use Stripe as your payment gateway, configure it with your Stripe API keys:

import { UnifiedPayment } from 'multigatepay';

const stripeConfig = {
    apiKey: 'your_stripe_api_key',
    environment: 'production' // 'sandbox' for testing
};

const payment = new UnifiedPayment('stripe', stripeConfig);

Razorpay Configuration

For Razorpay, you'll need to provide both the API key and the secret key:

import { UnifiedPayment } from 'multigatepay';

const razorpayConfig = {
    apiKey: 'your_razorpay_api_key',
    secretKey: 'your_razorpay_secret_key',
    environment: 'production' // 'sandbox' for testing
};

const payment = new UnifiedPayment('razorpay', razorpayConfig);

Usage

Creating a Checkout Session

Create a checkout session with the provided details:

const checkoutDetails = {
    amount: 5000, // Amount in smallest currency unit (e.g., cents for USD)
    currency: 'USD',
    description: 'Premium Membership'
};

payment.createCheckoutSession(checkoutDetails)
    .then((sessionId) => {
        console.log('Checkout session created:', sessionId);
    })
    .catch((error) => {
        console.error('Error creating checkout session:', error);
    });

Verifying a Payment

Verify a payment using the session ID:

const sessionId = 'your_checkout_session_id';

payment.verifyPayment(sessionId)
    .then((isVerified) => {
        if (isVerified) {
            console.log('Payment verified successfully!');
        } else {
            console.log('Payment verification failed.');
        }
    })
    .catch((error) => {
        console.error('Error verifying payment:', error);
    });

Supported Gateways

  • Stripe: Widely used payment gateway with global reach.
  • Razorpay: Popular in India, offering a range of payment options.

Extending the Package

Adding a New Gateway

To add support for a new payment gateway, implement the PaymentGateway interface and register it with the GatewayFactory.

Step 1: Implement the New Gateway

Create a new class that implements the PaymentGateway interface:

import { PaymentGateway, CheckoutDetails } from 'multigatepay';

class NewGateway implements PaymentGateway {
    constructor(private config: any) {}

    async createCheckoutSession(details: CheckoutDetails): Promise<string> {
        // Implement the logic to create a checkout session
    }

    async verifyPayment(sessionId: string): Promise<boolean> {
        // Implement the logic to verify the payment
    }
}

Step 2: Register the New Gateway

Update the GatewayFactory to recognize the new gateway:

import { PaymentGateway } from 'multigatepay';
import { NewGateway } from './gateways/NewGateway';

export class GatewayFactory {
    static createGateway(gatewayType: string, config: any): PaymentGateway {
        switch (gatewayType.toLowerCase()) {
            case 'stripe':
                return new StripeGateway(config);
            case 'razorpay':
                return new RazorpayGateway(config);
            case 'newgateway':
                return new NewGateway(config);
            default:
                throw new Error('Unsupported payment gateway');
        }
    }
}

Customizing Checkout Details

Customize the checkout details based on the requirements of the gateway:

const checkoutDetails = {
    amount: 10000,
    currency: 'INR',
    description: 'Purchase of Product XYZ',
    // Additional fields specific to the gateway can be added here
};

API Reference

UnifiedPayment Class

  • constructor(gatewayType: string, config: any)

    • Creates an instance of the UnifiedPayment class.
    • Parameters:
      • gatewayType: The type of payment gateway (e.g., 'stripe', 'razorpay').
      • config: Configuration options for the selected gateway.
  • createCheckoutSession(details: CheckoutDetails): Promise<string>

    • Creates a new checkout session.
    • Parameters:
      • details: Object containing checkout details such as amount, currency, and description.
    • Returns: A promise that resolves with the session ID.
  • verifyPayment(sessionId: string): Promise<boolean>

    • Verifies the payment using the session ID.
    • Parameters:
      • sessionId: The ID of the checkout session.
    • Returns: A promise that resolves with a boolean indicating whether the payment is verified.

PaymentGateway Interface

  • createCheckoutSession(details: CheckoutDetails): Promise<string>

    • Abstract method to be implemented by each gateway for creating a checkout session.
  • verifyPayment(sessionId: string): Promise<boolean>

    • Abstract method to be implemented by each gateway for verifying a payment.

Examples

Using Multiple Gateways

Dynamically switch between different gateways based on your business logic:

const gatewayType = determineGateway(); // Custom logic to choose gateway

const payment = new UnifiedPayment(gatewayType, config[gatewayType]);

payment.createCheckoutSession(details)
    .then((sessionId) => {
        // Handle success
    })
    .catch((error) => {
        // Handle error
    });

Error Handling

The package provides consistent error handling across different gateways. All methods return promises that either resolve successfully or reject with an error message.

payment.createCheckoutSession(details)
    .catch((error) => {
        console.error('An error occurred:', error.message);
    });

Contributing

Contributions are welcome! To contribute:

  1. Fork the repository.
  2. Create a new branch with a descriptive name.
  3. Make your changes and commit them with clear and concise messages.
  4. Submit a pull request to the main repository.

Please ensure your code adheres to the project's coding standards and includes appropriate tests.

License

This project is licensed under the ISC License - see the LICENSE file for details.