daily-pay-sdk
v1.0.5
Published
SDK for Daily Pay payment system
Downloads
220
Maintainers
Readme
Daily Pay SDK
Official SDK for integrating with Daily Pay payment system - A comprehensive payment processing solution supporting multiple payment gateways, subscription management, and user authentication.
Installation
npm install daily-pay-sdkQuick Start
JavaScript
const { DailyPayClient } = require('daily-pay-sdk');
// Initialize the client
const client = new DailyPayClient({
apiKey: 'your-api-key-here',
baseURL: 'https://pay.dailyinvoice.xyz', // Optional: defaults to this
timeout: 30000 // Optional: request timeout in ms
});TypeScript
import { DailyPayClient, SDKConfig } from 'daily-pay-sdk';
const config: SDKConfig = {
apiKey: 'your-api-key-here',
baseURL: 'https://pay.dailyinvoice.xyz',
timeout: 30000
};
const client = new DailyPayClient(config);Table of Contents
- Apps Management
- Plans Management
- Subscriptions
- Transactions
- User Management
- API Keys
- Verification Services
- Error Handling
Apps Management
Manage your applications within the Daily Pay system.
JavaScript Examples
// Create a new app without logo
const newApp = await client.apps.create({
name: 'My E-commerce Store',
description: 'Online store for digital products',
appUrl: 'https://mystore.com',
webhookUrl: 'https://mystore.com/webhook'
});
// Create app with logo (Browser)
const fileInput = document.querySelector('input[type="file"]');
const logoFile = fileInput.files[0];
const appWithLogo = await client.apps.create({
name: 'My Store',
description: 'Store description',
appUrl: 'https://mystore.com'
}, logoFile);
// List all apps with pagination
const apps = await client.apps.list({ page: 1, limit: 10 });
console.log(apps.data); // Array of apps
console.log(apps.pagination); // Pagination info
// Get single app
const app = await client.apps.getApp('app-id-here');
// Update app
const updatedApp = await client.apps.update('app-id-here', {
name: 'Updated Store Name',
description: 'New description'
});
// Delete app
await client.apps.deleteApp('app-id-here');TypeScript Examples
import { App, CreateAppData, UpdateAppData } from 'daily-pay-sdk';
// Create app with type safety
const appData: CreateAppData = {
name: 'My E-commerce Store',
description: 'Online store for digital products',
appUrl: 'https://mystore.com',
webhookUrl: 'https://mystore.com/webhook'
};
const response = await client.apps.create(appData);
const app: App = response.data;
// List apps with pagination
interface ListParams {
page?: number;
limit?: number;
}
const listApps = async (params: ListParams = { page: 1, limit: 10 }) => {
const result = await client.apps.list(params);
console.log(`Total apps: ${result.pagination.totalItems}`);
return result.data;
};
// Update app with partial data
const updateData: UpdateAppData = {
name: 'Updated Store',
webhookUrl: 'https://mystore.com/new-webhook'
};
const updated = await client.apps.update('app-id-here', updateData);Node.js File Upload
For Node.js environments, use the dedicated file upload methods:
const fs = require('fs');
const path = require('path');
// Read logo file
const logoBuffer = fs.readFileSync(path.join(__dirname, 'logo.png'));
// Create app with logo
const appWithLogo = await client.apps.createWithFile({
name: 'My Store',
description: 'Store description',
appUrl: 'https://mystore.com'
}, logoBuffer, 'logo.png');
// Update app with logo
const updatedApp = await client.apps.updateWithFile('app-id-here', {
name: 'Updated Store'
}, logoBuffer, 'logo.png');Plans Management
Create and manage subscription plans.
JavaScript Examples
// Create a new plan
const plan = await client.plans.create({
name: 'Premium Monthly',
description: 'Access to all premium features',
price: 29.99,
currency: 'USD',
provider: 'stripe',
interval: 'monthly',
features: ['Feature 1', 'Feature 2', 'Feature 3'],
isActive: true
});
// List all plans
const plans = await client.plans.list({
page: 1,
limit: 20,
isActive: true // Optional: filter by active status
});
// Get active plans only
const activePlans = await client.plans.getActivePlans({ page: 1, limit: 10 });
// Get single plan
const singlePlan = await client.plans.getPlan('plan-id-here');
// Update plan
const updatedPlan = await client.plans.update('plan-id-here', {
price: 34.99,
features: ['New Feature 1', 'New Feature 2']
});
// Update plan status
const activated = await client.plans.updateStatus('plan-id-here', true);
// Delete plan
await client.plans.deletePlan('plan-id-here');TypeScript Examples
import { Plan, CreatePlanData, UpdatePlanData } from 'daily-pay-sdk';
// Create plan with type safety
const planData: CreatePlanData = {
name: 'Premium Yearly',
description: 'Yearly premium subscription',
price: 299.99,
currency: 'USD',
provider: 'stripe',
interval: 'yearly',
features: ['24/7 Support', 'Unlimited Projects', 'Advanced Analytics'],
isActive: true
};
const response = await client.plans.create(planData);
const newPlan: Plan = response.data;
// List and filter plans
const getActivePlans = async (): Promise<Plan[]> => {
const result = await client.plans.list({ isActive: true });
return result.data;
};
// Update specific fields
const updatePlanPrice = async (planId: string, newPrice: number) => {
const updateData: UpdatePlanData = { price: newPrice };
return client.plans.update(planId, updateData);
};Subscriptions
Manage customer subscriptions to plans.
JavaScript Examples
// Create a new subscription
const subscription = await client.subscriptions.create({
gateway: 'stripe',
planCode: 'plan-id-here',
email: '[email protected]'
// appID is optional if using API key authentication
});
// Create subscription with explicit app ID
const appSubscription = await client.subscriptions.createWithApp({
gateway: 'paystack',
planCode: 'plan-id-here',
email: '[email protected]',
appID: 'your-app-id'
});
console.log(subscription.authorization_url); // Payment link
console.log(subscription.reference); // Transaction referenceTypeScript Examples
import { Subscription, CreateSubscriptionData, PaymentProvider } from 'daily-pay-sdk';
// Create subscription with type safety
const createSubscription = async (
gateway: PaymentProvider,
planCode: string,
email: string
) => {
const data: CreateSubscriptionData = {
gateway,
planCode,
email
};
const result = await client.subscriptions.create(data);
if (result.authorization_url) {
// Redirect user to payment page
console.log('Payment URL:', result.authorization_url);
}
return result;
};
// Handle different payment providers
const providers: PaymentProvider[] = ['stripe', 'paystack', 'flutterwave', 'paypal'];
// Create subscription with specific app
const createAppSubscription = async (appId: string, planCode: string, email: string) => {
return client.subscriptions.createWithApp({
gateway: 'flutterwave',
planCode,
email,
appID: appId
});
};Transactions
Process payments and manage transaction history.
JavaScript Examples
// Initialize a payment
const payment = await client.transactions.initiate({
amount: 1000,
gateway: 'stripe',
email: '[email protected]',
currency: 'USD',
metadata: {
productId: '123',
customerName: 'John Doe'
}
});
// List all transactions
const transactions = await client.transactions.list({
page: 1,
limit: 20
});
// List transactions by app
const appTransactions = await client.transactions.listByAppId({
page: 1,
limit: 10,
appId: 'your-app-id'
});
// Get single transaction
const transaction = await client.transactions.getTransaction('transaction-id');
// Verify transaction by reference
const verified = await client.transactions.verify('transaction-reference');
// List by status
const pendingTransactions = await client.transactions.listByStatus('pending');
const successTransactions = await client.transactions.listByStatus('success');
// List by date range
const dateRangeTransactions = await client.transactions.listByDateRange(
'2024-01-01',
'2024-01-31',
{ page: 1, limit: 50 }
);TypeScript Examples
import {
Transaction,
InitiatePaymentData,
PaymentProvider,
InitiatePaymentResponse
} from 'daily-pay-sdk';
// Initiate payment with metadata
const initiatePayment = async (
amount: number,
email: string,
provider: PaymentProvider = 'stripe'
): Promise<InitiatePaymentResponse> => {
const paymentData: InitiatePaymentData = {
amount,
gateway: provider,
email,
currency: 'USD',
metadata: {
timestamp: new Date().toISOString(),
source: 'web-checkout'
}
};
return client.transactions.initiate(paymentData);
};
// Get transaction summary by status
interface TransactionSummary {
total: number;
pending: Transaction[];
success: Transaction[];
failed: Transaction[];
}
const getTransactionSummary = async (): Promise<TransactionSummary> => {
const [pending, success, failed] = await Promise.all([
client.transactions.listByStatus('pending'),
client.transactions.listByStatus('success'),
client.transactions.listByStatus('failed')
]);
return {
total: pending.pagination.totalItems + success.pagination.totalItems + failed.pagination.totalItems,
pending: pending.data,
success: success.data,
failed: failed.data
};
};User Management
Handle user registration, authentication, and profile management.
JavaScript Examples
// Register a new user
const registration = await client.users.register({
name: 'John Doe',
email: '[email protected]',
username: 'johndoe',
phone: '+1234567890',
password: 'securepassword123',
referredBy: 'REFERRAL_CODE' // Optional
});
// Login user
const login = await client.users.login({
email: '[email protected]',
password: 'securepassword123'
});
// Or login with username
const loginWithUsername = await client.users.login({
username: 'johndoe',
password: 'securepassword123'
});
console.log(login.token); // JWT token for subsequent requests
console.log(login.user); // User information
// Get current user
const currentUser = await client.users.getCurrentUser();
// Update current user
const updated = await client.users.updateCurrentUser({
name: 'John Updated',
phone: '+1987654321',
address: '123 Main St'
});
// List all users (admin only)
const users = await client.users.listAll({ page: 1, limit: 20 });
// Get user by ID
const user = await client.users.getUser('user-id-here');
// Request password reset
await client.users.forgetPassword({
email: '[email protected]'
});
// Reset password with token
await client.users.resetPassword({
token: 'reset-token-from-email',
password: 'newpassword123'
});
// Delete current user
await client.users.deleteCurrentUser();TypeScript Examples
import {
User,
RegisterUserData,
LoginData,
LoginResponse,
UpdateUserData
} from 'daily-pay-sdk';
// User registration with validation
const registerUser = async (userData: RegisterUserData): Promise<User> => {
const response = await client.users.register(userData);
return response.data;
};
// Login with multiple strategies
type LoginMethod = 'email' | 'username' | 'phone';
const loginUser = async (
identifier: string,
password: string,
method: LoginMethod = 'email'
): Promise<LoginResponse> => {
const loginData: LoginData = {
password
};
if (method === 'email') loginData.email = identifier;
else if (method === 'username') loginData.username = identifier;
else if (method === 'phone') loginData.phone = identifier;
return client.users.login(loginData);
};
// Profile update with partial data
const updateProfile = async (updates: Partial<UpdateUserData>): Promise<User> => {
const response = await client.users.updateCurrentUser(updates);
return response.data;
};API Keys
Manage API keys for application access.
JavaScript Examples
// List all API keys
const apiKeys = await client.apiKeys.list();
// Create a new API key
const newKey = await client.apiKeys.create({
name: 'Production Key',
description: 'API key for production environment',
appID: 'your-app-id'
});
// Deactivate an API key
await client.apiKeys.deactivate('key-id', 'app-id');TypeScript Examples
import { ApiKey, CreateApiKeyData } from 'daily-pay-sdk';
// Create API key with type safety
const createApiKey = async (
appId: string,
keyName: string
): Promise<ApiKey> => {
const data: CreateApiKeyData = {
name: keyName,
description: `API key for ${keyName}`,
appID: appId
};
const response = await client.apiKeys.create(data);
return response.data;
};
// Deactivate key
const deactivateKey = async (keyId: string, appId: string): Promise<void> => {
await client.apiKeys.deactivate(keyId, appId);
};Verification Services
Verify bank accounts and BVN information.
JavaScript Examples
// Verify bank account
const bankVerification = await client.verification.verifyBank({
accountNumber: '0123456789',
bankName: 'GTBank'
});
console.log(bankVerification.data.account_name); // Verified account name
// Verify BVN
const bvnVerification = await client.verification.verifyBVN({
bvn: '12345678901',
firstname: 'John',
lastname: 'Doe'
});TypeScript Examples
import {
BankVerificationData,
BankVerificationResponse,
BVNVerificationData,
BVNVerificationResponse
} from 'daily-pay-sdk';
// Verify bank account with type safety
const verifyBankAccount = async (
accountNumber: string,
bankName: string
): Promise<BankVerificationResponse> => {
const data: BankVerificationData = { accountNumber, bankName };
const response = await client.verification.verifyBank(data);
return response.data;
};
// Verify BVN with user details
const verifyBVN = async (
bvn: string,
firstName: string,
lastName: string
): Promise<BVNVerificationResponse> => {
const data: BVNVerificationData = {
bvn,
firstname: firstName,
lastname: lastName
};
const response = await client.verification.verifyBVN(data);
return response.data;
};Error Handling
The SDK provides comprehensive error handling with DailyPayError class.
JavaScript Examples
const { DailyPayError } = require('daily-pay-sdk');
try {
const app = await client.apps.getApp('invalid-id');
} catch (error) {
if (error instanceof DailyPayError) {
console.log('Error message:', error.message);
console.log('Status code:', error.statusCode);
console.log('Response data:', error.response);
// Handle specific status codes
switch (error.statusCode) {
case 401:
console.log('Unauthorized - check your API key');
break;
case 404:
console.log('Resource not found');
break;
case 422:
console.log('Validation error:', error.response);
break;
case 429:
console.log('Rate limit exceeded');
break;
default:
console.log('An error occurred:', error.message);
}
} else {
console.log('Network or other error:', error.message);
}
}TypeScript Examples
import { DailyPayError } from 'daily-pay-sdk';
interface ErrorResponse {
message: string;
errors?: Record<string, string[]>;
}
const handleApiCall = async <T>(promise: Promise<T>): Promise<T | null> => {
try {
return await promise;
} catch (error) {
if (error instanceof DailyPayError) {
console.error(`API Error (${error.statusCode}):`, error.message);
// Type-safe error handling
if (error.statusCode === 422) {
const validationErrors = error.response as ErrorResponse;
if (validationErrors.errors) {
Object.entries(validationErrors.errors).forEach(([field, messages]) => {
console.error(`${field}: ${messages.join(', ')}`);
});
}
}
// Re-throw if you want to handle it further up
throw error;
}
console.error('Unexpected error:', error);
return null;
}
};
// Usage
const safeAppFetch = async (appId: string) => {
return handleApiCall(client.apps.getApp(appId));
};Browser Support
The SDK works in both Node.js and browser environments. For file uploads in the browser, use the native FormData support:
// Browser file upload
const fileInput = document.getElementById('logo');
const file = fileInput.files[0];
const app = await client.apps.create({
name: 'Browser App',
description: 'Created from browser',
appUrl: window.location.origin
}, file); // Pass File/Blob directlyTypeScript Support
All resources and methods are fully typed. Import types as needed:
import {
DailyPayClient,
DailyPayError,
// Resources
App,
Plan,
Subscription,
Transaction,
User,
ApiKey,
// Request/Response types
CreateAppData,
CreatePlanData,
CreateSubscriptionData,
InitiatePaymentData,
RegisterUserData,
LoginResponse,
// Enums
PaymentProvider
} from 'daily-pay-sdk';License
MIT
