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

phonepe-pg-next-js

v2.0.0

Published

PhonePe Payment Gateway SDK for Next.js. Easily integrate PhonePe payment gateway into your Next.js applications with this SDK. Supports seamless payment processing and checkout experiences. Developed by Techlift Digital.

Downloads

33

Readme

PhonePe Checkout SDK for Node.js & Next.js

npm version License: MIT

A production-ready, highly secure, and strictly-typed SDK for integrating PhonePe Payment Gateway (v2 API) into your Node.js and Next.js applications.


🚀 Why Use This Package?

Unlike generic HTTP wrappers, this SDK is engineered for reliability and security in modern enterprise applications.

🛡️ Enhanced Security

  • Runtime Environment Protection: Automatically detects and blocks execution in browser environments to prevent accidental exposure of your clientSecret.
  • Injection Guard: Built-in regex validation for all Merchant and Refund IDs to neutralize potential injection attacks.
  • Secure Defaults: zero-config usage of PhonePe's recommended security best practices (e.g., specific header handling).

💎 Superior Developer Experience

  • 100% TypeScript: Comprehensive type definitions for every Request and Response object. No more switching between code and documentation.
  • Next.js Optimized: Designed natively for Server Actions and API Routes in the Next.js App Router (13/14+).
  • Zero Guesswork: Logical class-based architecture (PhonePeSDK) with fluent builders (MetaInfoBuilder) makes integration intuitive.

⚡ Performance & Compatibility

  • Lightweight: Minimal dependencies (axios only).
  • Latest APIs: references the newest v2 Checkout and Refund endpoints.

Installation

npm install phonepe-pg-next-js
# or
yarn add phonepe-pg-next-js
# or
pnpm add phonepe-pg-next-js

Quick Start (Next.js App Router)

1. Setup Environment Variables

Create a .env.local file:

PHONEPE_CLIENT_ID=your_client_id
PHONEPE_CLIENT_SECRET=your_client_secret
PHONEPE_ENV=SANDBOX # or PRODUCTION
NEXT_PUBLIC_APP_URL=http://localhost:3000

2. Initialize the SDK

Best practice: Initialize the SDK in a singleton file (e.g., lib/phonepe.ts).

// lib/phonepe.ts
import { PhonePeSDK } from 'phonepe-pg-next-js';

export const phonepe = new PhonePeSDK({
  clientId: process.env.PHONEPE_CLIENT_ID!,
  clientSecret: process.env.PHONEPE_CLIENT_SECRET!,
  clientVersion: "1",
  env: "SANDBOX" // Defaults to SANDBOX if omitted
});

3. Create a Payment (Server Action)

// app/actions/payment.ts
"use server";
import { phonepe } from "@/lib/phonepe";
import { redirect } from "next/navigation";

export async function initiatePayment(amount: number) {
  const merchantOrderId = `ORDER_${Date.now()}`;
  
  const response = await phonepe.createOrder({
    merchantOrderId,
    amount: amount * 100, // SDK mandates paise (e.g., 100 = ₹1)
    paymentFlow: {
      type: "PG_CHECKOUT",
      merchantUrls: {
        redirectUrl: `${process.env.NEXT_PUBLIC_APP_URL}/api/payment/callback`,
      }
    },
    // Optional: Add tracking fields
    metaInfo: PhonePeSDK.MetaInfoBuilder
      .udf1("E-Commerce")
      .udf5("Customer_Premium_Segment")
      .build()
  });

  if (response.success && response.data) {
    // Redirect user to the returned PhonePe Checkout URL
    return response.data.redirectUrl;
  } else {
    throw new Error(response.message || "Payment initiation failed");
  }
}

4. Handle Callback / Webhook

// app/api/payment/callback/route.ts
import { NextResponse, NextRequest } from "next/server";
import { PhonePeSDK } from 'phonepe-pg-next-js';

export async function POST(request: NextRequest) {
  try {
    const payload = await request.json();
    const authHeader = request.headers.get("authorization");

    // 1. Verify Request Signature
    // Checks SHA256(username:password) matches the Authorization header
    const isValid = PhonePeSDK.verifyWebhookSignature(
      authHeader || "",
      process.env.PHONEPE_WEBHOOK_USER!, // Configured Webhook Username
      process.env.PHONEPE_WEBHOOK_PASSWORD! // Configured Webhook Password
    );

    if (!isValid) {
      console.warn("⚠️ Unauthorized PhonePe Webhook Attempt");
      return NextResponse.json({ message: "Unauthorized" }, { status: 401 });
    }

    // 2. Process the Payload
    console.log("✅ Received Valid Webhook:", payload);
    
    // Example: Update database based on payment state
    if (payload.code === "PAYMENT_SUCCESS") {
      // await updateOrderStatus(payload.data.merchantOrderId, "PAID");
    }

    return NextResponse.json({ success: true });
  } catch (error) {
    return NextResponse.json({ success: false }, { status: 500 });
  }
}

API Reference

PhonePeSDK

The main entry point class.

Constructor Config: | Property | Type | Description | | :--- | :--- | :--- | | clientId | string | Your PhonePe Merchant ID / Client ID | | clientSecret | string | Your PhonePe Salt Key / Client Secret | | clientVersion | string | Salt Index (usually "1") | | env | SANDBOX | PRODUCTION | Environment selector |

createOrder(params: CreateOrderRequest)

Initiate a transaction. Validates inputs before sending.

  • params: merchantOrderId (string), amount (number, in paise), paymentFlow (object).
  • returns: Promise<ProcessedResponse>

getOrderStatus(merchantOrderId: string)

Get the real-time status of a transaction.

  • merchantOrderId: The same ID used during creation.

initiateRefund(params: RefundRequest)

Refund a successful transaction.

  • params: originalMerchantOrderId, merchantRefundId, amount.

getRefundStatus(merchantRefundId: string)

Check the status of a pending refund.


Utilities

MetaInfoBuilder

Fluent interface for constructing the tracking metaInfo object without manual JSON errors.

const meta = PhonePeSDK.MetaInfoBuilder
  .udf1("Category:Electronics")
  .udf2("Source:MobileApp")
  .set("custom_tracking_id", "XYZ-999")
  .build();

Security Best Practices

  • Server-Side Only: The SDK proactively throws an error if initialized in a browser environment to prevent credential leaks.
  • Input Sanitization: All IDs are validated against strict regex patterns (^[a-zA-Z0-9_-]+$) to prevent injection.
  • No Sensitive Logging: Internal loggers strip sensitive payload data before printing (or don't print at all).

Security

Credential Management

It is crucial to keep your PhonePe credentials (clientid and clientsecret) secure. Here are some best practices:

  • Do not hardcode credentials: Never store your credentials directly in your source code.
  • Use environment variables: Load your credentials from environment variables. For local development, you can use a .env file and a library like dotenv to load them. Make sure to add the .env file to your .gitignore.
  • Use a secrets management service: For production environments, it is highly recommended to use a dedicated secrets management service like AWS Secrets Manager, Google Cloud Secret Manager, Azure Key Vault, or HashiCorp Vault.

Disclaimer

This is an unofficial SDK for the PhonePe API. It is not affiliated with, endorsed by, or sponsored by PhonePe.

This software is provided "as is", without warranty of any kind, express or implied. The authors and copyright holders are not liable for any claim, damages, or other liability arising from the use of this software.

It is your responsibility to ensure that your use of this SDK and the PhonePe API is compliant with all applicable laws and regulations, as well as PhonePe's terms of service. You are also responsible for your own privacy policy and terms of service for your application.

License

This project is licensed under the MIT License. See the LICENSE file for details.

Feedback and Support

We'd love to hear from you! If you have any ideas, suggestions, or need further assistance, please feel free to reach out.

If you find this package helpful and it has accelerated your development, consider buying us a coffee! Your support helps us maintain and improve this SDK.