Skip to content

TheChainKeshflip/sdk-js

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

KeshPay JavaScript/TypeScript SDK

Official JavaScript/TypeScript SDK for KeshPay API - Seamless crypto & fiat payment integration.

Features

  • âś… Crypto Operations: Deposits, withdrawals, and balance management
  • âś… Fiat Operations: EVC and Salaam Bank integration
  • âś… Webhook Handling: Event routing and signature validation
  • âś… TypeScript Support: Full TypeScript types and interfaces
  • âś… Promise-based: Modern async/await support
  • âś… Authentication: Automatic request signing with HMAC-SHA256
  • âś… Error Handling: Comprehensive exception hierarchy

Installation

npm install @keshpay/sdk
# or
yarn add @keshpay/sdk
# or
pnpm add @keshpay/sdk

Quick Start

TypeScript

import { KeshPayClient } from '@keshpay/sdk';

const client = new KeshPayClient({
  apiKey: 'your_api_key',
  apiSecret: 'your_api_secret',
  partnerId: 'your_partner_id',
  baseURL: 'https://api.keshpay.com', // optional
});

// Create crypto deposit
const deposit = await client.crypto.deposits.create({
  asset: 'USDC',
  chainId: '1',
  amount: '100.00',
  idempotencyKey: 'deposit_001',
});

console.log(`Send ${deposit.asset} to: ${deposit.address}`);
console.log(`Status: ${deposit.status}`);

JavaScript (ES6)

const { KeshPayClient } = require('@keshpay/sdk');

const client = new KeshPayClient({
  apiKey: 'your_api_key',
  apiSecret: 'your_api_secret',
  partnerId: 'your_partner_id',
});

// Same API as TypeScript

Crypto Operations

Create Deposit

const deposit = await client.crypto.deposits.create({
  asset: 'USDC',        // USDC, USDT
  chainId: '1',         // 1 (Ethereum), 137 (Polygon), 8453 (Base)
  amount: '100.00',
  idempotencyKey: 'unique_key_001',
});

console.log(`Send ${deposit.asset} to: ${deposit.address}`);
console.log(`Expires at: ${deposit.expiresAt}`);

Get Deposit Status

const deposit = await client.crypto.deposits.get('68e088c7d393ae4f9556e2a7');
console.log(`Status: ${deposit.data.status}`);
console.log(`Confirmed at: ${deposit.data.confirmedAt}`);

List Deposits

const deposits = await client.crypto.deposits.list({ status: 'PENDING' });

for (const deposit of deposits.data) {
  console.log(`${deposit.asset}: ${deposit.amount} - ${deposit.status}`);
}

Create Withdrawal

const withdrawal = await client.crypto.withdrawals.create({
  asset: 'USDC',
  chainId: '1',
  amount: '50.00',
  toAddress: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb',
  idempotencyKey: 'withdrawal_001',
});

console.log(`Withdrawal ID: ${withdrawal.withdrawalId}`);
console.log(`Status: ${withdrawal.status}`);

Check Balance

// Get balance for specific asset
const balance = await client.crypto.balances.get('1', 'USDC');

console.log(`Balance: ${balance.balance}`);
console.log(`Total deposits: ${balance.totalDeposits}`);
console.log(`Total withdrawals: ${balance.totalWithdrawals}`);

// List all balances
const balances = await client.crypto.balances.list();
for (const balance of balances) {
  console.log(`${balance.asset} on chain ${balance.chainId}: ${balance.balance}`);
}

Fiat Operations

Create EVC Deposit

const deposit = await client.fiat.deposits.create({
  provider: 'EVC',
  customerNumber: '+252612345678',
  amount: '50.00',
  idempotencyKey: 'evc_001',
});

console.log(`Deposit ID: ${deposit.depositId}`);
console.log(`Instructions: ${deposit.instructions}`);
console.log(`Expires at: ${deposit.expiresAt}`);

Create Salaam Bank Deposit

const deposit = await client.fiat.deposits.create({
  provider: 'SALAAM_BANK',
  customerNumber: '+252612345678',
  amount: '100.00',
  idempotencyKey: 'salaam_001',
});

List Fiat Deposits

const deposits = await client.fiat.deposits.list({
  provider: 'EVC',
  status: 'PENDING',
});

Webhook Handling

Setup Webhook Handler

import { KeshPayClient } from '@keshpay/sdk';

const client = new KeshPayClient({
  apiKey: 'your_api_key',
  apiSecret: 'your_api_secret',
  partnerId: 'your_partner_id',
});

// Register event handlers
client.webhooks.on('crypto.deposit.updated', (event) => {
  const { depositId, status, amount, asset } = event.data;
  
  console.log(`Crypto deposit ${depositId} is now ${status}`);
  console.log(`Amount: ${amount} ${asset}`);
  
  if (status === 'CONFIRMED') {
    // Process confirmed deposit
    processDeposit(depositId);
  }
});

client.webhooks.on('crypto.withdrawal.completed', (event) => {
  const { withdrawalId, hash } = event.data;
  console.log(`Withdrawal ${withdrawalId} completed: ${hash}`);
});

Process Webhook in Express.js

import express from 'express';
import { KeshPayClient } from '@keshpay/sdk';

const app = express();
const client = new KeshPayClient({ /* ... */ });

app.post('/webhooks/keshpay', express.json(), async (req, res) => {
  try {
    const signature = req.headers['x-signature'] as string;
    const payload = JSON.stringify(req.body);
    
    // Handle webhook (validates signature automatically)
    const event = await client.webhooks.handle(payload, signature);
    
    console.log(`Webhook processed: ${event.event}`);
    
    res.json({ success: true });
  } catch (error) {
    console.error('Webhook error:', error);
    res.status(400).json({ error: 'Invalid webhook' });
  }
});

app.listen(3000, () => {
  console.log('Webhook server running on port 3000');
});

Process Webhook in Next.js

// app/api/webhooks/keshpay/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { KeshPayClient } from '@keshpay/sdk';

const client = new KeshPayClient({ /* ... */ });

export async function POST(request: NextRequest) {
  try {
    const signature = request.headers.get('x-signature') || '';
    const body = await request.text();
    
    const event = await client.webhooks.handle(body, signature);
    
    return NextResponse.json({ success: true, event: event.event });
  } catch (error) {
    return NextResponse.json(
      { error: 'Invalid webhook' },
      { status: 400 }
    );
  }
}

Error Handling

import {
  KeshPayClient,
  AuthenticationError,
  ValidationError,
  APIError,
  NetworkError,
} from '@keshpay/sdk';

try {
  const deposit = await client.crypto.deposits.create({
    asset: 'USDC',
    chainId: '1',
    amount: '100.00',
    idempotencyKey: 'deposit_001',
  });
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.error('Authentication failed:', error.message);
  } else if (error instanceof ValidationError) {
    console.error('Validation error:', error.message);
    console.error('Details:', error.response);
  } else if (error instanceof APIError) {
    console.error('API error:', error.message);
    console.error('Status code:', error.statusCode);
  } else if (error instanceof NetworkError) {
    console.error('Network error:', error.message);
  }
}

TypeScript Types

The SDK includes comprehensive TypeScript types:

import type {
  CryptoDepositRequest,
  CryptoDepositResponse,
  CryptoWithdrawalRequest,
  CryptoWithdrawalResponse,
  CryptoBalanceResponse,
  FiatDepositRequest,
  FiatDepositResponse,
  WebhookEvent,
  DepositStatus,
  TransactionStatus,
} from '@keshpay/sdk';

Supported Assets

Crypto Assets

Asset Chains Description
USDC Ethereum (1), Polygon (137), Base (8453) USD Coin
USDT Ethereum (1), Polygon (137), Tron Tether USD

Fiat Providers

  • EVC: E-Wallet payments in Somalia
  • Salaam Bank: Bank transfers in Somalia

Development

Build

npm run build

Watch Mode

npm run dev

Lint

npm run lint

Format

npm run format

Support

License

MIT License - see LICENSE file for details.

About

Official Keshpay JS/TS SDK for crypto & fiat.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published