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

esewa-integration-server

v2.2.8

Published

A flexible npm package for integrating eSewa payments.

Downloads

78

Readme

ESewa Integration server pakage

A Node.js package for integrating with the eSewa payment gateway. This package provides an easy way to handle payment success and failure notifications.

Installation

To install the package, run:

    npm install esewa-integration-server

initialize Integration

To set up the integration, use the following code:

const EsewaIntegration = require("esewa-integration-server");

// Initialize with custom configuration
const esewa = new EsewaIntegration({
  secretKey: process.env.ESEWA_SECRET_KEY || "your-esewa-secret-key", // Your eSewa secret key
  successUrl: "https://yourdomain.com/payment/success", // URL to handle successful payments
  failureUrl: "https://yourdomain.com/payment/failure", // URL to handle failed payments
});

you can also change the methods to set cookies, the cookie set are used to track payment when the transaction fails :

const esewa = new EsewaIntegration({
  secretKey: process.env.ESEWA_SECRET_KEY || "your-esewa-secret-key",
  successUrl: "https://yourdomain.com/payment/success",
  failureUrl: "https://yourdomain.com/payment/failure",

  sameSite: "strict",
  secure: "true",
});

Get Your Secret Key

You can get your secret key for testing at "http://developer.esewa.com.np/pages/Epay#integration" Initiate Payment

To intitate payment

app
  .get("/esewa/initiate", async (req, res) => {
    const { total_amount } = req.query; // You can also send these details in req.body
    const uuid=somerandomuuid1231  //uuid generate an unique uuid
    esewa.initiatePayment(
      {
        total_amount, // Total amount to be paid (required)
        transactionUUID: uuid, // Unique transaction identifier (required)
        amount: total_amount, // Amount being passed (required)
        productCode: "EPAYTEST", // Product code (optional)

      //theother optional feilds 
        // productDeliveryCharge = 0,
        // productServiceCharge = 0,
        // taxAmount = 0,
      }
      res 
    );
  })
  .catch((error) => {
    console.error("Error saving order:", error.message);
    res.status(500).json({ error: "Failed to save order." });
  });

if you are using react at frontend

you should do implement function that uses the html file you get as response,then document.open,document.write and document.close to redirect to esewa payment gateaway

import React, { useState } from "react";

export default function YourFunction() {
  const [amt, setAmt] = useState("");

  const initiatePayment = async (e) => {
    e.preventDefault();
    try {
      const response = await fetch(
        `/api/esewa/initiatePayment?total_amount=${amt}`,
        {
          method: "GET", // Adjust the method if necessary
          credentials: "include",
          headers: {
            "Content-Type": "application/json",
          },
        }
      );
      //you can also send the amt and other feilds in req.body its your choice but adjust according in your backend too
      if (!response.ok) {
        throw new Error("Network response was not ok");
      }

      const html = await response.text(); // the response from esewa.initatePayment() is an html file 
      document.open();
      document.write(html);
      document.close();
    } catch (error) {
      // Handle error
      console.error("Error initiating payment:", error);
    }
  };

  return (
    {/*don't copy all these brother, this is my bs example react component */}
    <div>
      <input
        type="text"
        value={amt}
        onChange={(e) => setAmt(e.target.value)}
        placeholder="Enter amount"
      />
      <button onClick={initiatePayment}>Initiate Payment</button>
    </div>
  );
}

Handle Payment Success

Define the endpoint for handling successful payments:

app.get("/payment/success", esewa.processPaymentSuccess, async (req, res) => {
  try {
    const { transaction_uuid, amount, ...otherFields } = req.params; // Use req.params for GET parameters 

    console.log(transaction_uuid)
    console.log(amount)

    // Prepare the redirect URL and optional message properties
    const redirectUrl = "http://your_domain.com/success"; 
    const messageProps = {
      paymentSuccess: "Yay!",
      thanks: "Thank you for your order!",
    };

    // Redirect the client to the specified URL with message properties
    esewa.redirectToClientSite(res, redirectUrl, messageProps);
  } catch (error) {
    console.error("Error handling payment success:", error.message);
    res.status(500).json({ error: "Internal Server Error" });
  }
});

Handle Payment Failure

Define the endpoint for handling failed payments:


app.get("/payment/failure", esewa.processPaymentFailure, async (req, res) => {
  try {
    const redirectUrl = "http://your_domain.com/failure"; // set at url page you want your clent to get when payment fails
    const messageProps = {
      paymentFailed: "Oops!",
      sorry: "Sorry, your payment failed.",
    };
    // Retrieve the transaction UUID from the request object it is set by esewa.processPaymentFailure middleware
    console.log(req.transactionUUID)
    // Redirect the client to the specified URL with message properties

    esewa.redirectToClientSite(res, redirectUrl, messageProps);
  } catch (error) {
    console.error("Error handling payment failure:", error.message);
    res.status(500).json({ error: "Internal Server Error" });
  }
});

Additional Notes

Details of Methods Initialization Class

const esewa = new EsewaIntegration({
  secretKey: process.env.ESEWA_SECRET_KEY || "your-esewa-secret-key",
  successUrl: "https://yourdomain.com/payment/success",
  failureUrl: "https://yourdomain.com/payment/failure",
});

This class has the following methods:

esewa.processPaymentSuccess; //Used as middleware in your success route, it attaches the response from eSewa when the success URL is hit to req.params.
esewa.processPaymentFailure; // Handles payment failure.meant to be used as url

esewa.redirectToClientSite(); // Redirects to the client site with message properties
esewa.initiatePayment(); //sends an html file to the client that  self submits to esewa but on some frontend frame works you may have to manually open the html file 

Important Considerations

Make sure to implement appropriate error handling. Update the success and failure URLs as needed for your production environment. Consider implementing logging for better traceability of issues.

License

This package is licensed under the MIT License. About