Official JavaScript/TypeScript SDK for QBitFlow - Next Generation Crypto Payment Processing
npm install qbitflow

Official JavaScript/TypeScript SDK for QBitFlow - a comprehensive cryptocurrency payment processing platform that enables seamless integration of crypto payments, recurring subscriptions, and pay-as-you-go models into your applications.
- ๐ Type-Safe: Full TypeScript support with comprehensive type definitions
- ๐ Easy to Use: Simple, intuitive API design
- ๐ Automatic Retries: Built-in retry logic for failed requests
- โก Real-time Updates: WebSocket support for transaction status monitoring
- ๐ฆ Dual Package: Works with both CommonJS and ES modules
- ๐งช Well Tested: Comprehensive test coverage
- ๐ Great Documentation: Detailed docs with examples
- ๐ Webhook Support: Handle payment notifications easily
- ๐ณ One-Time Payments: Accept cryptocurrency payments with ease
- ๐ Recurring Subscriptions: Automated recurring billing in cryptocurrency
- ๐ Pay-as-You-Go: Usage-based billing with cryptocurrency
- ๐ฅ Customer Management: Create and manage customer profiles
- ๐๏ธ Product Management: Organize your products and pricing
- ๐ Transaction Tracking: Real-time transaction status updates
- ๐ Secure Authentication: API key-based authentication
- ๐ฏ Type-Safe: Full type hints for better IDE support
- ๐ Comprehensive Documentation: Detailed docstrings and examples
- Features
- Installation
- Quick Start
- 1. Get Your API Key
- 2. Initialize the Client
- 3. Create a One-Time Payment
- 4. Create a Recurring Subscription
- 5. Check Transaction Status
- Configuration
- One-Time Payments
- Create a Payment Session
- With Redirect URLs
- Get Payment Session
- Get Completed Payment
- List All Payments
- List Combined Payments
- Subscriptions
- Create a Subscription
- Frequency Units
- Get Subscription
- Get all payments for subscription
- Execute Test Billing Cycle
- Pay-As-You-Go Subscriptions
- Create PAYG Subscription
- Get PAYG Subscription
- Get all payments for PAYG subscription
- Execute Test Billing Cycle
- Increase units current period
- Transaction Status
- Check Status
- Transaction Types
- Status Values
- Customer Management
- Create a Customer
- Get Customer by UUID
- Update Customer
- Delete Customer
- Product Management
- Create a Product
- Update Product
- Delete Product
- Webhook Handling
- Express.js Example
- Error Handling
- API Reference
- QBitFlow
- Constructor
- Properties
- License
- Support
- Changelog
``bash`
npm install qbitflow
Or using yarn:
`bash`
yarn add qbitflow
Sign up at QBitFlow and obtain your API key from the dashboard.
`typescript
import { QBitFlow } from 'qbitflow';
// Initialize the client
const client = new QBitFlow('your-api-key');
`
`typescript
// Create a one-time payment
const payment = await client.oneTimePayments.createSession({
productId: 1,
customerUUID: 'customer-uuid',
webhookUrl: 'https://yourapp.com/webhook',
successUrl: 'https://yourapp.com/success',
cancelUrl: 'https://yourapp.com/cancel',
});
console.log('Payment link:', payment.link);
// Send this link to your customer
`
`typescript
const subscription = await client.subscriptions.createSession({
productId: 1,
frequency: { unit: 'months', value: 1 }, // Bill monthly
trialPeriod: { unit: 'days', value: 7 }, // 7-day trial (optional)
webhookUrl: 'https://yourapp.com/webhook',
customerUUID: 'customer-uuid',
});
console.log('Subscription link:', subscription.link);
`
`typescript
import { TransactionType, TransactionStatusValue } from 'qbitflow';
const status = await client.transactionStatus.get(
'transaction-uuid',
TransactionType.ONE_TIME_PAYMENT
);
if (status.status === TransactionStatusValue.COMPLETED) {
console.log('Payment completed! Transaction hash:', status.txHash);
} else if (status.status === TransactionStatusValue.FAILED) {
console.log('Payment failed:', status.message);
}
`
| Option | Type | Default | Description |
| ------------ | ------ | -------------------------- | -------------------------------------------- |
| apiKey | string | (required) | Your QBitFlow API key |baseUrl
| | string | https://api.qbitflow.app | API base URL |timeout
| | number | 30000 | Request timeout in milliseconds |maxRetries
| | number | 3 | Number of retry attempts for failed requests |
Create a payment session for a one-time purchase:
`typescript
// Using an existing product
const payment = await client.oneTimePayments.createSession({
productId: 1,
customerUUID: 'customer-uuid', // optional
webhookUrl: 'https://yourapp.com/webhook',
});
// Or create a custom payment
const payment = await client.oneTimePayments.createSession({
productName: 'Custom Product',
description: 'Product description',
price: 99.99, // USD
customerUUID: 'customer-uuid',
webhookUrl: 'https://yourapp.com/webhook',
});
console.log(payment.uuid); // Session UUID
console.log(payment.link); // Payment link for customer
`
You can provide redirect URLs for success and cancellation:
`typescript`
const payment = await client.oneTimePayments.createSession({
productId: 1,
successUrl: 'https://yourapp.com/success?uuid={{UUID}}&type={{TRANSACTION_TYPE}}',
cancelUrl: 'https://yourapp.com/cancel',
customerUUID: 'customer-uuid',
});
Available Placeholders:
- {{UUID}}: The session UUID{{TRANSACTION_TYPE}}
- : The transaction type (e.g., "payment", "subscription", "payAsYouGo")
Retrieve details of a payment session:
`typescript`
const session = await client.oneTimePayments.getSession('session-uuid');
console.log(session.productName, session.price);
Retrieve details of a completed payment:
`typescript`
const payment = await client.oneTimePayments.get('payment-uuid');
console.log(payment.transactionHash, payment.amount);
List all one-time payments with pagination:
`typescript
const result = await client.oneTimePayments.getAll({ limit: 10 });
console.log(result.items); // Array of payments
console.log(result.hasMore()); // Whether there are more pages
console.log(result.nextCursor); // Cursor for next page
// Fetch next page
if (result.hasMore()) {
const nextPage = await client.oneTimePayments.getAll({
limit: 10,
cursor: result.nextCursor,
});
}
`
Get all payments (one-time and subscription payments combined):
`typescript`
const result = await client.oneTimePayments.getAllCombined({ limit: 20 });
result.items.forEach((payment) => {
console.log(payment.source); // "payment" or "subscription_history"
console.log(payment.amount);
});
Create a recurring subscription:
`typescript
const subscription = await client.subscriptions.createSession({
productId: 1,
frequency: { unit: 'months', value: 1 }, // Bill monthly
trialPeriod: { unit: 'days', value: 7 }, // 7-day trial (optional)
minPeriods: 3, // Minimum billing periods (optional)
webhookUrl: 'https://yourapp.com/webhook',
customerUUID: 'customer-uuid',
});
console.log(subscription.link); // Send to customer
`
Available units for frequency and trialPeriod:
- secondsminutes
- hours
- days
- weeks
- months
-
Retrieve subscription details:
`typescript`
const subscription = await client.subscriptions.get('subscription-uuid');
console.log(subscription.status, subscription.nextBillingDate);
`typescript`
const history = await client.subscriptions.getPaymentHistory('subscription-uuid');
history.forEach((record) => {
console.log(record.uuid, record.amount, record.createdAt);
});
Test Mode Only: Manually trigger a billing cycle for testing.
For live mode: Billing cycles are executed automatically based on the subscription frequency.
`typescript`
const result = await client.subscriptions.executeTestBilling('subscription-uuid');
console.log('Transaction status link:', result.statusLink);
PAYG subscriptions allow customers to pay based on usage with a billing cycle.
`typescript
const payg = await client.payAsYouGo.createSession({
productId: 1,
frequency: { unit: 'months', value: 1 }, // Bill monthly
freeCredits: 100, // Initial free credits (optional)
webhookUrl: 'https://yourapp.com/webhook',
customerUUID: 'customer-uuid',
});
console.log(payg.link);
`
`typescript`
const payg = await client.payAsYouGo.get('payg-uuid');
console.log(payg.allowance, payg.unitsCurrentPeriod);
`typescript`
const history = await client.payAsYouGo.getPaymentHistory('payg-uuid');
history.forEach((record) => {
console.log(record.uuid, record.amount, record.createdAt);
});
Test Mode Only: Manually trigger a billing cycle for testing.
For live mode: Billing cycles are executed automatically based on the subscription frequency.
`typescript`
const result = await client.payAsYouGo.executeTestBilling('subscription-uuid');
console.log('Transaction status link:', result.statusLink);
Increase the number of units for the current billing period:
`typescript`
// For example, the product is billed per hour of usage, and the customer consumed 5 additional hours
const response = await client.payAsYouGo.increaseUnitsCurrentPeriod('payg-uuid', 5);
Get the current status of a transaction:
`typescript
import { TransactionType } from 'qbitflow';
const status = await client.transactionStatus.get(
'transaction-uuid',
TransactionType.ONE_TIME_PAYMENT
);
console.log(status.status); // "created", "pending", "completed", etc.
console.log(status.txHash); // Blockchain transaction hash
`
`typescript`
enum TransactionType {
/* One-time payment transaction /
ONE_TIME_PAYMENT = 'payment',
/* Create subscription transaction /
CREATE_SUBSCRIPTION = 'createSubscription',
/* Cancel subscription transaction /
CANCEL_SUBSCRIPTION = 'cancelSubscription',
/* Execute subscription payment transaction /
EXECUTE_SUBSCRIPTION_PAYMENT = 'executeSubscription',
/* Create pay-as-you-go subscription transaction /
CREATE_PAYG_SUBSCRIPTION = 'createPAYGSubscription',
/* Cancel pay-as-you-go subscription transaction /
CANCEL_PAYG_SUBSCRIPTION = 'cancelPAYGSubscription',
/* Increase allowance transaction /
INCREASE_ALLOWANCE = 'increaseAllowance',
/* Update max amount transaction /
UPDATE_MAX_AMOUNT = 'updateMaxAmount',
}
`typescript`
enum TransactionStatusValue {
/* Transaction has been created but not yet processed /
CREATED = 'created',
/* Waiting for blockchain confirmation /
WAITING_CONFIRMATION = 'waitingConfirmation',
/* Transaction is pending processing /
PENDING = 'pending',
/* Transaction has been successfully completed /
COMPLETED = 'completed',
/* Transaction has failed /
FAILED = 'failed',
/* Transaction has been cancelled /
CANCELLED = 'cancelled',
/* Transaction has expired /
EXPIRED = 'expired',
}
`typescript
const customerData: CreateCustomerDto = {
name: 'John',
lastName: 'Doe',
email: 'john@example.com',
phoneNumber: '+1234567890',
reference: 'CRM-12345',
};
const customer = await client.customers.create(customerData);
console.log('Customer created:', customer.uuid);
`
`typescript${customer.name} ${customer.lastName} - ${customer.email}
const customer = await client.customers.get('customer-uuid');
console.log();`
`typescript
const updateData: UpdateCustomerDto = {
name: 'John',
lastName: 'Doe',
email: 'john.doe@example.com',
phoneNumber: '+9876543210',
};
const updatedCustomer = await client.customers.update('customer-uuid', updateData);
`
`typescript`
const response = await client.customers.delete('customer-uuid');
console.log(response.message);
`typescript
const productData: CreateProductDto = {
name: 'Premium Subscription',
description: 'Access to all premium features',
price: 29.99,
reference: 'PROD-PREMIUM',
};
const product = await client.products.create(productData);
console.log('Product created: ID', product.id);
`
`typescript
const updateData: UpdateProductDto = {
name: 'Premium Plus',
description: 'Enhanced premium features',
price: 39.99,
};
const updatedProduct = await client.products.update(1, updateData);
`
`typescript`
const response = await client.products.delete(1);
`typescript
import express from 'express';
import { QBitFlow, SessionWebhookResponse, TransactionStatusValue } from 'qbitflow';
const app = express();
const client = new QBitFlow('your-api-key');
app.use(express.json());
app.post('/webhook', (req, res) => {
const event = req.body as SessionWebhookResponse;
console.log('Webhook received:', event.uuid);
console.log('Status:', event.status.status);
if (event.status.status === TransactionStatusValue.COMPLETED) {
console.log('Payment completed!');
// Handle successful payment
} else if (event.status.status === TransactionStatusValue.FAILED) {
console.log('Payment failed');
}
res.status(200).json({ received: true });
});
app.listen(3000, () => {
console.log('Webhook server running on port 3000');
});
`
`typescript`
interface SessionWebhookResponse {
/* Session UUID /
uuid: string;
/* Current transaction status /
status: TransactionStatus;
/* Complete session information /
session: Session;
}
The webhook payload includes:
- uuid: Session UUIDstatus
- : Current transaction status with type, status value, and optional transaction hashsession
- : Complete session details including product info, price, customer UUID, etc.
The SDK provides specific error classes for different scenarios:
`typescript
import {
NotFoundException,
UnauthorizedException,
ValidationException,
NetworkException,
QBitFlowError,
} from 'qbitflow';
try {
const payment = await client.oneTimePayments.get('invalid-uuid');
} catch (error) {
if (error instanceof NotFoundException) {
console.error('Payment not found');
} else if (error instanceof UnauthorizedException) {
console.error('Invalid API key');
} else if (error instanceof ValidationException) {
console.error('Invalid request:', error.message);
} else if (error instanceof NetworkException) {
console.error('Network error:', error.message);
} else if (error instanceof QBitFlowError) {
console.error('QBitFlow error:', error.message);
} else {
console.error('Unknown error:', error);
}
}
`
Main client class.
#### Constructor
`typescript`
new QBitFlow(apiKey: string)
new QBitFlow(config: QBitFlowConfig)
#### Properties
- customers: CustomerRequests - Customer operationsproducts: ProductRequests
- - Product operationsusers: UserRequests
- - User operationsapiKeys: ApiKeyRequests
- - API key operationsoneTimePayments: PaymentRequests
- - One-time payment operationssubscriptions: SubscriptionRequests
- - Subscription operationspayAsYouGo: PayAsYouGoRequests
- - Pay-as-you-go operationstransactionStatus: TransactionStatusRequests
- - Transaction status operations
Run the test suite:
`bashRun all tests
npm test
This project is licensed under the MPL-2.0 License - see the LICENSE file for details.
- ๐ Documentation
- ๐ง Email Support
- ๐ Issue Tracker
See CHANGELOG.md for version history and updates.
For security issues, please email security@qbitflow.app instead of using the issue tracker.
---
Made with โค๏ธ by the QBitFlow team