Guides

NakaPay Node.js SDK Guide

Integrate NakaPay into your Node.js applications seamlessly with our official SDK. This guide will walk you through installation, initialization, and common use cases.

Last updated on May 23, 2025

Installation

The NakaPay Node.js SDK is available on npm and GitHub. Install it via npm or yarn:

1npm install nakapay-sdk
2# or
3yarn add nakapay-sdk

The SDK is open-source and actively maintained. For the latest updates, documentation, and source code, visit the official repository: https://github.com/hubavka/nakapay-sdk

Initialization

First, import the SDK and initialize the client with your API key. You can obtain your API key from the NakaPay Dashboard.

1import { NakaPay } from 'nakapay-sdk';
2
3// Replace 'YOUR_API_KEY' with your actual API key
4const nakaPay = new NakaPay('YOUR_API_KEY');
5
6// Optional: If you are self-hosting or using a different API endpoint
7// const nakaPay = new NakaPay('YOUR_API_KEY', { 
8//   baseUrl: 'https://api.nakapay.app/api/v1' 
9// });
Important: Your API key is secret! Keep it secure and never expose it in client-side code. This SDK is intended for server-side use.

Core Operations

1. Creating a Payment Request

To create a new payment request (which will typically generate a Lightning invoice):

1async function createNewPayment() {
2  try {
3    const paymentRequest = await nakaPay.createPaymentRequest({
4      amount: 100, // Amount in satoshis
5      description: 'Payment for Order #123',
6      metadata: { orderId: '123', customerId: '456' }
7    });
8
9    console.log('Payment Request Created:', paymentRequest);
10    // Example response properties:
11    // console.log('ID:', paymentRequest.id);
12    // console.log('Invoice:', paymentRequest.invoice);
13    // console.log('Status:', paymentRequest.status);
14    // console.log('Expires At:', paymentRequest.expiresAt);
15    
16    // You would typically display the invoice (e.g., as a QR code) to the user.
17
18    // Example of checking status (from SDK README)
19    setTimeout(async () => {
20      if (paymentRequest && paymentRequest.id) {
21        const statusInfo = await nakaPay.getPaymentStatus(paymentRequest.id);
22        console.log(`Payment ID ${paymentRequest.id} Status:`, statusInfo.status);
23      }
24    }, 30000);
25
26  } catch (error) {
27    console.error('Error creating payment request:', error.message);
28  }
29}
30
31createNewPayment();

For more details on request parameters, see the API Reference.

2. Getting Payment Request Details

You can retrieve the details of an existing payment request using its ID:

1async function getPaymentDetails(paymentId) {
2  try {
3    const paymentDetails = await nakaPay.getPaymentRequest(paymentId);
4    console.log('Payment Details:', paymentDetails);
5    // paymentDetails will include amount, description, status, invoice, etc.
6  } catch (error) {
7    console.error('Error fetching payment details:', error.message);
8  }
9}
10
11// Example: getPaymentDetails('pr_xxxxxxxxxxxxxx');

3. Checking Payment Status

To check the current status of a payment request:

1async function checkStatus(paymentId) {
2  try {
3    const statusInfo = await nakaPay.getPaymentStatus(paymentId);
4    console.log('Payment Status:', statusInfo.status);
5    // Possible statuses: 'pending', 'completed', 'failed', 'expired'
6
7    if (statusInfo.status === 'completed') {
8      console.log('Payment was successful!');
9      // Fulfill order, grant access, etc.
10    }
11  } catch (error) {
12    console.error('Error checking payment status:', error.message);
13  }
14}
15
16// Example: checkStatus('pr_xxxxxxxxxxxxxx');

While polling for status is possible, we highly recommend using Webhooks for real-time payment notifications for better efficiency and reliability.

4. Listing Payments (History)

Retrieve a list of payment requests associated with your business (API key).

1async function listPayments() {
2  try {
3    // The SDK README mentions getPayments(businessId, options), but for an API key-based SDK,
4    // the businessId might be implicit from the API key.
5    // Assuming the SDK handles this or the method doesn't require explicit businessId.
6    // If businessId is required, it should be obtained securely.
7    const payments = await nakaPay.getPayments({ // options object
8      limit: 10, 
9      offset: 0
10    });
11
12    console.log('Fetched Payments:', payments); 
13    // Assuming 'payments' is an array of PaymentRequest objects.
14    // The exact response structure (e.g., if it includes pagination) should be verified from SDK types/docs.
15    
16    payments.forEach(payment => {
17      console.log(`- ${payment.id}: ${payment.amount} sats, Status: ${payment.status}`);
18    });
19
20  } catch (error) {
21    console.error('Error listing payments:', error.message);
22  }
23}
24
25listPayments();

5. Registering a Webhook Endpoint

You can programmatically register or update your webhook endpoint using the SDK. This allows you to receive real-time notifications for payment events.

1async function setupWebhook() {
2  try {
3    // Assuming businessId is implicit via API key for this SDK method,
4    // or needs to be passed if the SDK requires it.
5    // The SDK README shows: registerWebhook(businessId: string, options: WebhookOptions)
6    // For this example, let's assume businessId is handled or known.
7    // const businessId = 'YOUR_BUSINESS_ID'; 
8
9    const webhookRegistration = await nakaPay.registerWebhook({ // Pass options directly if businessId is implicit
10    // const webhookRegistration = await nakaPay.registerWebhook(businessId, { // Or if businessId is needed
11      url: 'https://your-app.com/webhook-handler', 
12      events: ['payment.completed', 'payment.failed'], // Example events
13      // secret: 'your-strong-secret-for-verifying-nakapay-webhooks', // Optional: if you want to provide your own secret
14    });
15
16    console.log('Webhook Registered/Updated:', webhookRegistration);
17    // Expected response from SDK README: { success: boolean; message: string }
18    if (webhookRegistration.success) {
19      console.log(webhookRegistration.message);
20    }
21    // If NakaPay generates a secret for you to verify its webhooks, that should be handled.
22
23  } catch (error) {
24    console.error('Error registering webhook:', error.message);
25  }
26}
27
28setupWebhook();

For more details on handling incoming webhooks and verifying signatures, please see our Webhooks Guide.

Error Handling

All SDK methods return Promises. If an API call fails or an error occurs, the Promise will reject. Always wrap your SDK calls in try...catch blocks to handle potential errors gracefully. Error objects typically include a message property and may contain additional details from the API.

1try {
2  // Example SDK call:
3  // const data = await nakaPay.someMethod();
4} catch (error) {
5  console.error('NakaPay SDK Error:', error.name, error.message);
6  // The error object structure might vary. Check SDK documentation for specifics.
7  // if (error.response && error.response.data) {
8  //   console.error('API Error Details:', error.response.data);
9  // }
10  // Implement user-friendly error feedback
11}

Further Information

This guide covers the most common uses of the NakaPay Node.js SDK. For a complete list of API endpoints, request/response schemas, and more advanced scenarios, please refer to our full API Reference.

For the latest SDK updates, detailed documentation, examples, and to report issues, visit the official SDK repository: https://github.com/hubavka/nakapay-sdk

If you encounter any issues or have questions, please don't hesitate to reach out to our support team or check the FAQ.