KiraPay API with Next.js

A simple guide to integrate KiraPay API into your Next.js application.


1. Setup Next.js Project

npx create-next-app@latest kirapay-api
cd kirapay-api

When prompted, select: ✅ TypeScript ✅ Tailwind CSS ✅ App Router


2. 🔑 API Key Configuration

Create a .env.local file in your project root:

NEXT_PUBLIC_KIRAPAY_API_KEY=your_api_key_here

You can get your API key from the KiraPay Dashboard.


3. 📦 Create Type Definitions

Create a new file: src/types/kirapay.ts

export interface CreateLinkRequest {
  currency: string;
  receiver: string;
  price: number;
  name: string;
  redirectUrl?: string;
}

export interface CreateLinkResponse {
  message: string;
  data: {
    url: string;
  };
}

export interface PaymentLink {
  _id: string;
  code: string;
  price: number;
  name: string;
  url: string;
  receiver: string;
  createdAt: string;
}

export interface GetLinksResponse {
  message: string;
  data: {
    links: PaymentLink[];
    total: number;
    page: number;
    totalPages: number;
  };
}

export interface GetLinkByCodeResponse {
  message: string;
  data: PaymentLink;
}

export interface Transaction {
  _id: string;
  transaction_hash: string;
  status: "PENDING" | "COMPLETED" | "FAILED" | "CANCELLED";
  amount: number;
  createdAt: string;
}

export interface GetTransactionsResponse {
  message: string;
  data: {
    transactions: Transaction[];
    total: number;
  };
}

4. ⚙️ API Functions

Create a new file: src/lib/kirapay-api.ts


Endpoint: POST /link/generate Authentication: Required (x-api-key header) Description: Creates a new payment link for accepting crypto payments.

Required Fields:

  • price: Amount to be paid

  • currency: Token symbol (e.g., USDC, USDT)

  • receiver: Wallet address to receive payment

  • name: Description or name for the payment link

Optional Field:

  • redirectUrl: URL to redirect after successful payment

import { CreateLinkRequest, CreateLinkResponse } from '@/types/kirapay';

const API_BASE_URL = 'https://kirapay-api.holatech.app/api';

export const createPaymentLink = async (request: CreateLinkRequest): Promise<CreateLinkResponse> => {
  const apiKey = process.env.NEXT_PUBLIC_KIRAPAY_API_KEY;
  
  const response = await fetch(`${API_BASE_URL}/link/generate`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'x-api-key': apiKey!,
    },
    body: JSON.stringify(request),
  });

  const data = await response.json();
  
  if (!response.ok) {
    throw new Error(data.message || 'Failed to create payment link');
  }
  
  return data;
};

Endpoint: GET /link Authentication: Required Description: Retrieves all payment links created by your account with pagination.

Query Parameters:

  • page — Page number (default: 1)

  • limit — Items per page (default: 10)

import { GetLinksResponse } from '@/types/kirapay';

export const getPaymentLinks = async (page: number = 1, limit: number = 10): Promise<GetLinksResponse> => {
  const apiKey = process.env.NEXT_PUBLIC_KIRAPAY_API_KEY;
  const params = new URLSearchParams({
    page: page.toString(),
    limit: limit.toString(),
  });

  const response = await fetch(`${API_BASE_URL}/link?${params}`, {
    headers: {
      'Content-Type': 'application/json',
      'x-api-key': apiKey!,
    },
  });

  const data = await response.json();
  
  if (!response.ok) {
    throw new Error(data.message || 'Failed to fetch payment links');
  }
  
  return data;
};

Endpoint: GET /link/{code} Authentication: ❌ Not required (Public endpoint) Description: Fetches payment link details using its unique code.

Use Case: Display payment details to customers before they pay.

import { GetLinkByCodeResponse } from '@/types/kirapay';

export const getLinkByCode = async (code: string): Promise<GetLinkByCodeResponse> => {
  const response = await fetch(`${API_BASE_URL}/link/${code}`, {
    headers: { 'Content-Type': 'application/json' },
  });

  const data = await response.json();
  
  if (!response.ok) {
    throw new Error(data.message || 'Failed to fetch payment link');
  }
  
  return data;
};

🔹 Get Transactions

Endpoint: GET /wallet/transactions Authentication: Required (x-api-key header) Description: Retrieves all transaction history including blockchain details and status.

import { GetTransactionsResponse } from '@/types/kirapay';

export const getTransactions = async (): Promise<GetTransactionsResponse> => {
  const apiKey = process.env.NEXT_PUBLIC_KIRAPAY_API_KEY;

  const response = await fetch(`${API_BASE_URL}/wallet/transactions`, {
    headers: {
      'Content-Type': 'application/json',
      'x-api-key': apiKey!,
    },
  });

  const data = await response.json();
  
  if (!response.ok) {
    throw new Error(data.message || 'Failed to fetch transactions');
  }
  
  return data;
};

✅ Complete API File

import {
  CreateLinkRequest,
  CreateLinkResponse,
  GetLinksResponse,
  GetLinkByCodeResponse,
  GetTransactionsResponse
} from '@/types/kirapay';

const API_BASE_URL = 'https://kirapay-api.holatech.app/api';

const getApiKey = (): string => {
  const apiKey = process.env.NEXT_PUBLIC_KIRAPAY_API_KEY;
  if (!apiKey) {
    throw new Error('NEXT_PUBLIC_KIRAPAY_API_KEY is required');
  }
  return apiKey;
};

// POST /link/generate
export const createPaymentLink = async (request: CreateLinkRequest): Promise<CreateLinkResponse> => {
  const response = await fetch(`${API_BASE_URL}/link/generate`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'x-api-key': getApiKey(),
    },
    body: JSON.stringify(request),
  });

  const data = await response.json();
  if (!response.ok) throw new Error(data.message || 'Failed to create payment link');
  return data;
};

// GET /link
export const getPaymentLinks = async (page: number = 1, limit: number = 10): Promise<GetLinksResponse> => {
  const params = new URLSearchParams({ page: page.toString(), limit: limit.toString() });
  const response = await fetch(`${API_BASE_URL}/link?${params}`, {
    headers: {
      'Content-Type': 'application/json',
      'x-api-key': getApiKey(),
    },
  });

  const data = await response.json();
  if (!response.ok) throw new Error(data.message || 'Failed to fetch payment links');
  return data;
};

// GET /link/{code}
export const getLinkByCode = async (code: string): Promise<GetLinkByCodeResponse> => {
  const response = await fetch(`${API_BASE_URL}/link/${code}`, {
    headers: { 'Content-Type': 'application/json' },
  });

  const data = await response.json();
  if (!response.ok) throw new Error(data.message || 'Failed to fetch payment link');
  return data;
};

// GET /wallet/transactions
export const getTransactions = async (): Promise<GetTransactionsResponse> => {
  const response = await fetch(`${API_BASE_URL}/wallet/transactions`, {
    headers: {
      'Content-Type': 'application/json',
      'x-api-key': getApiKey(),
    },
  });

  const data = await response.json();
  if (!response.ok) throw new Error(data.message || 'Failed to fetch transactions');
  return data;
};

5. 💻 Create Simple UI

Create: src/app/page.tsx

"use client";

import { useState } from "react";
import { createPaymentLink } from "@/lib/kirapay-api";

export default function Home() {
  const [loading, setLoading] = useState(false);
  const [paymentUrl, setPaymentUrl] = useState("");

  const handleCreateLink = async () => {
    setLoading(true);
    try {
      const response = await createPaymentLink({
        currency: "USDC",
        receiver: "0x1234567890123456789012345678901234567890",
        price: 10,
        name: "Test Payment",
        redirectUrl: "https://example.com/success"
      });
      
      setPaymentUrl(response.data.url);
      alert("Payment link created!");
    } catch (error) {
      alert("Error: " + (error as Error).message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-gray-50 flex items-center justify-center p-4">
      <div className="bg-white rounded-lg shadow-lg p-8 max-w-md w-full">
        <h1 className="text-2xl font-bold text-gray-900 mb-6 text-center">
          KiraPay Integration
        </h1>
        
        <button
          onClick={handleCreateLink}
          disabled={loading}
          className="w-full bg-blue-600 text-white py-3 px-4 rounded-lg font-medium hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed transition-colors"
        >
          {loading ? "Creating..." : "Create Payment Link"}
        </button>

        {paymentUrl && (
          <div className="mt-6 p-4 bg-green-50 border border-green-200 rounded-lg">
            <p className="text-sm text-gray-600 mb-2">Payment Link:</p>
            <a
              href={paymentUrl}
              target="_blank"
              rel="noopener noreferrer"
              className="text-blue-600 hover:underline break-all text-sm"
            >
              {paymentUrl}
            </a>
          </div>
        )}
      </div>
    </div>
  );
}

6. ▶️ Run the Application

npm run dev

Visit 👉 http://localhost:3000 Click the Create Payment Link button to test.


📘 API Endpoints Summary

Endpoint
Method
Auth Required
Description

/link/generate

POST

✅ Yes

Create new payment link

/link

GET

✅ Yes

Get all payment links with pagination

/link/{code}

GET

❌ No

Get payment link details by code

/wallet/transactions

GET

✅ Yes

Get wallet transaction history


Please refer to the API Documentation for more details.

Last updated

Was this helpful?