3tpay-sdk
v0.1.1
Published
Welcome to the `3tpay-sdk`! This is a lightweight, TypeScript-based Software Development Kit (SDK) designed to make integrating with the **Crypto Payment API** (hosted at `https://payment.web3twenty.com/v2/api`) a breeze. Whether you're a merchant looking
Readme
3tpay-sdk
Welcome to the 3tpay-sdk! This is a lightweight, TypeScript-based Software Development Kit (SDK) designed to make integrating with the Crypto Payment API (hosted at https://payment.web3twenty.com/v2/api) a breeze. Whether you're a merchant looking to create invoices, manage licenses, or track transactions, or an admin needing to oversee system-wide data, this SDK has you covered. It’s published on npm as 3tpay-sdk, so you can easily add it to your project and start building.
This SDK is production-ready, type-safe, and built for simplicity. It supports trial access (via trial hashes), full merchant licenses, and admin API keys, giving you flexibility for different use cases. With detailed examples, robust error handling, and TypeScript support, you’ll be up and running in no time.
Table of Contents
- Features
- Installation
- Getting Started
- Merchant SDK
- Admin SDK
- Error Handling
- Testing the SDK
- Contributing
- License
Features
Here’s what the 3tpay-sdk brings to the table:
- Merchant SDK: Tools for merchants to manage licenses, register stores, create and track invoices, verify micro-payments, and get transaction metrics.
- Admin SDK: Admin tools to monitor system metrics, list merchants, invoices, and transactions with filtering options.
- Authentication Options:
- Trial Hash: Test the API with a temporary trial hash.
- Full License: Secure merchant operations with a license and user key.
- API Key: Admin access with an API key.
- Type Safety: Full TypeScript support with type definitions for all inputs and responses.
- Simple API: Easy-to-use methods like
merchant.createInvoiceoradmin.getMetrics. - Customizable Config: Set your API URL and credentials however you need.
- Error Handling: Custom error classes for clear debugging (e.g.,
UnauthorizedError). - Lightweight: Only depends on
axiosfor HTTP requests, keeping it lean.
Installation
To start using the 3tpay-sdk, install it from npm. Here are the commands:
npm install 3tpay-sdkOr if you prefer Yarn:
yarn add 3tpay-sdkYou’ll need Node.js (version 14 or higher). The SDK works in both browser and server environments since it uses axios under the hood.
Getting Started
Configuration
The SDK uses a Config class to handle settings like the API base URL and authentication credentials. You’ll create a config instance and pass it to either the MerchantSDK or AdminSDK to get started.
The config supports these options:
baseUrl: The API endpoint (defaults tohttps://payment.web3twenty.com/v2/api).apiKey: For admin operations.licenseanduserKey: For merchant operations with a full license.trialHash: For trial access to merchant features.
Here’s how to set it up:
import { Config, MerchantSDK, AdminSDK } from '3tpay-sdk';
// Merchant config with a trial hash (for testing)
const trialConfig = Config.getInstance({
trialHash: 'your-trial-hash-here',
});
// Merchant config with a full license
const merchantConfig = Config.getInstance({
license: 'your-license-here',
userKey: 'your-user-key-here',
});
// Admin config with an API key
const adminConfig = Config.getInstance({
apiKey: 'your-api-key-here',
});
// Create SDK instances
const merchantWithTrial = new MerchantSDK(trialConfig.getConfig());
const merchantWithLicense = new MerchantSDK(merchantConfig.getConfig());
const admin = new AdminSDK(adminConfig.getConfig());You can update the config later if needed:
trialConfig.updateConfig({ trialHash: 'new-trial-hash-here' });Authentication Modes
The SDK supports three ways to authenticate:
- Trial Hash: Use a
trialHashto test merchant features without a full license. - Full License: Use a
licenseanduserKeyfor secure, long-term merchant access. - API Key: Use an
apiKeyfor admin operations.
The SDK handles the authentication headers for you based on what you provide in the config.
Merchant SDK
The MerchantSDK is where most developers will spend their time. It lets you manage licenses, register merchants, handle invoices, and more. Let’s break it down with examples.
License Management
Generate a License
Need a full license? Use generateLicense with an email and the number of months you want it to last.
import { MerchantSDK } from '3tpay-sdk';
const config = Config.getInstance({ trialHash: 'your-trial-hash' });
const merchant = new MerchantSDK(config.getConfig());
async function generateNewLicense() {
try {
const response = await merchant.generateLicense('[email protected]', 6);
console.log('New License:', response.license); // e.g., "lic-123"
console.log('User Key:', response.userKey); // e.g., "key-456"
} catch (error) {
console.error('Error:', error.message);
}
}
generateNewLicense();Generate a Trial Hash
Want to test the SDK first? Generate a trial hash with generateTrialHash.
import { MerchantSDK } from '3tpay-sdk';
const config = Config.getInstance({}); // No auth needed to generate trial hash
const merchant = new MerchantSDK(config.getConfig());
async function getTrialHash() {
try {
const response = await merchant.generateTrialHash();
console.log('Trial Hash:', response.trialHash); // e.g., "trial-abc789"
} catch (error) {
console.error('Error:', error.message);
}
}
getTrialHash();Renew a License
To extend an existing license, use renewLicense with your current license, userKey, and the number of extra months.
import { MerchantSDK } from '3tpay-sdk';
const config = Config.getInstance({
license: 'lic-123',
userKey: 'key-456',
});
const merchant = new MerchantSDK(config.getConfig());
async function renewMyLicense() {
try {
const response = await merchant.renewLicense('lic-123', 'key-456', 3);
console.log('Renewed:', response.success); // true
} catch (error) {
console.error('Error:', error.message);
}
}
renewMyLicense();Get License Details
Check the status of a license (e.g., expiration date) with getLicenseDetails.
import { MerchantSDK } from '3tpay-sdk';
const config = Config.getInstance({
license: 'lic-123',
userKey: 'key-456',
});
const merchant = new MerchantSDK(config.getConfig());
async function checkLicense() {
try {
const details = await merchant.getLicenseDetails('lic-123', 'key-456');
console.log('End Date:', details.endDate); // e.g., "2025-03-01T00:00:00Z"
console.log('Time Left:', details.remainingTime); // e.g., "5 months"
} catch (error) {
console.error('Error:', error.message);
}
}
checkLicense();Merchant Operations
Register a Merchant
To set up a new merchant, provide a storeName and masterWalletAddress.
import { MerchantSDK } from '3tpay-sdk';
const config = Config.getInstance({ trialHash: 'trial-abc789' });
const merchant = new MerchantSDK(config.getConfig());
async function registerNewMerchant() {
const merchantData = {
storeName: 'CoolStore',
masterWalletAddress: '0x1234567890abcdef1234567890abcdef12345678',
};
try {
const response = await merchant.registerMerchant(merchantData);
console.log('Merchant ID:', response.merchantId); // e.g., "merch-001"
console.log('Wallet:', response.masterWalletAddress); // "0x123..."
} catch (error) {
console.error('Error:', error.message);
}
}
registerNewMerchant();Get Merchant Transactions
Fetch a merchant’s transactions with filters like page, limit, currency, and timeRange.
import { MerchantSDK } from '3tpay-sdk';
const config = Config.getInstance({ trialHash: 'trial-abc789' });
const merchant = new MerchantSDK(config.getConfig());
async function fetchTransactions() {
try {
const transactions = await merchant.getTransactions('merch-001', {
page: 1,
limit: 5,
currency: 'USDT',
timeRange: 'weekly',
sortBy: 'timestamp',
sortOrder: 'desc',
});
console.log('Transactions:', transactions.data); // Array of transaction objects
console.log('Pagination:', transactions.pagination); // e.g., { page: 1, limit: 5, total: 25, totalPages: 5 }
} catch (error) {
console.error('Error:', error.message);
}
}
fetchTransactions();Get Merchant Invoices
Get a list of invoices for a merchant with filters like status and timeRange.
import { MerchantSDK } from '3tpay-sdk';
const config = Config.getInstance({ trialHash: 'trial-abc789' });
const merchant = new MerchantSDK(config.getConfig());
async function fetchInvoices() {
try {
const invoices = await merchant.getInvoices('merch-001', {
page: 1,
limit: 10,
status: 'paid',
timeRange: 'monthly',
sortBy: 'amount',
sortOrder: 'asc',
});
console.log('Invoices:', invoices.data); // Array of invoice objects
console.log('Pagination:', invoices.pagination); // e.g., { page: 1, limit: 10, total: 30, totalPages: 3 }
} catch (error) {
console.error('Error:', error.message);
}
}
fetchInvoices();Get Merchant Metrics
See a merchant’s stats (e.g., total payments, fees) with an optional timeRange.
import { MerchantSDK } from '3tpay-sdk';
const config = Config.getInstance({ trialHash: 'trial-abc789' });
const merchant = new MerchantSDK(config.getConfig());
async function fetchMetrics() {
try {
const metrics = await merchant.getMetrics('merch-001', 'monthly');
console.log('Total Payments:', metrics.totalPayments); // e.g., 5000
console.log('Total Fees:', metrics.totalFees); // e.g., 250
console.log('Transaction Count:', metrics.transactionCount); // e.g., 100
console.log('Invoice Count:', metrics.invoiceCount); // e.g., 75
} catch (error) {
console.error('Error:', error.message);
}
}
fetchMetrics();Invoice Operations
Create an Invoice
Create a new invoice with details like amount, currency, and URLs for success/failure.
import { MerchantSDK } from '3tpay-sdk';
const config = Config.getInstance({ trialHash: 'trial-abc789' });
const merchant = new MerchantSDK(config.getConfig());
async function createNewInvoice() {
const invoiceData = {
merchantId: 'merch-001',
amount: 50,
currency: 'USDT',
blockchain: 'mind',
expirationMinutes: 30,
success_url: 'https://mystoresite.com/success',
failed_url: 'https://mystoresite.com/failed',
ipn_url: 'https://mystoresite.com/webhook', // Optional instant payment notification
};
try {
const invoice = await merchant.createInvoice(invoiceData);
console.log('Invoice ID:', invoice.invoiceId); // e.g., "inv-789"
console.log('Payment Address:', invoice.disposableAddress); // e.g., "0x..."
console.log('Pay URL:', invoice.pay_url); // e.g., "https://payment.web3twenty.com/pay?data=..."
} catch (error) {
console.error('Error:', error.message);
}
}
createNewInvoice();Get an Invoice
Retrieve details about an invoice by its invoiceId.
import { MerchantSDK } from '3tpay-sdk';
const config = Config.getInstance({ trialHash: 'trial-abc789' });
const merchant = new MerchantSDK(config.getConfig());
async function fetchInvoice() {
try {
const invoice = await merchant.getInvoice('inv-789');
console.log('Status:', invoice.status); // e.g., "pending"
console.log('Amount:', invoice.amount); // 50
console.log('Currency:', invoice.currency); // "USDT"
} catch (error) {
console.error('Error:', error.message);
}
}
fetchInvoice();Verify a Micro-Payment
Verify a micro-payment with the invoiceId, txHash, and memo.
import { MerchantSDK } from '3tpay-sdk';
const config = Config.getInstance({ trialHash: 'trial-abc789' });
const merchant = new MerchantSDK(config.getConfig());
async function verifyPayment() {
const paymentData = {
invoiceId: 'inv-789',
txHash: '0xabcdef1234567890abcdef1234567890abcdef12',
memo: 'micro-payment-001',
};
try {
const response = await merchant.verifyMicroPayment(paymentData);
console.log('Verification:', response); // API-specific response
} catch (error) {
console.error('Error:', error.message);
}
}
verifyPayment();Admin SDK
The AdminSDK is for admin users who need to manage the entire platform. It requires an apiKey for authentication.
Get System Metrics
Get an overview of the system, like total merchants and payments.
import { AdminSDK } from '3tpay-sdk';
const config = Config.getInstance({ apiKey: 'your-api-key-here' });
const admin = new AdminSDK(config.getConfig());
async function fetchSystemMetrics() {
try {
const metrics = await admin.getSystemMetrics();
console.log('Total Merchants:', metrics.totalMerchants); // e.g., 15
console.log('Total Invoices:', metrics.totalInvoices); // e.g., 150
console.log('Total Payments:', metrics.totalPayments); // e.g., 7500
} catch (error) {
console.error('Error:', error.message);
}
}
fetchSystemMetrics();Get All Merchants
List all merchants with pagination and sorting options.
import { AdminSDK } from '3tpay-sdk';
const config = Config.getInstance({ apiKey: 'your-api-key-here' });
const admin = new AdminSDK(config.getConfig());
async function fetchAllMerchants() {
try {
const merchants = await admin.getAllMerchants({
page: 1,
limit: 10,
sortBy: 'storeName',
sortOrder: 'asc',
});
console.log('Merchants:', merchants.data); // Array of merchant objects
console.log('Pagination:', merchants.pagination); // e.g., { page: 1, limit: 10, total: 15, totalPages: 2 }
} catch (error) {
console.error('Error:', error.message);
}
}
fetchAllMerchants();Get All Invoices
List all invoices with filters like currency and status.
import { AdminSDK } from '3tpay-sdk';
const config = Config.getInstance({ apiKey: 'your-api-key-here' });
const admin = new AdminSDK(config.getConfig());
async function fetchAllInvoices() {
try {
const invoices = await admin.getAllInvoices({
page: 1,
limit: 10,
currency: 'USDT',
status: 'paid',
});
console.log('Invoices:', invoices.data); // Array of invoice objects
console.log('Pagination:', invoices.pagination); // e.g., { page: 1, limit: 10, total: 50, totalPages: 5 }
} catch (error) {
console.error('Error:', error.message);
}
}
fetchAllInvoices();Get All Transactions
List all transactions with filters like timeRange and status.
import { AdminSDK } from '3tpay-sdk';
const config = Config.getInstance({ apiKey: 'your-api-key-here' });
const admin = new AdminSDK(config.getConfig());
async function fetchAllTransactions() {
try {
const transactions = await admin.getAllTransactions({
page: 1,
limit: 10,
timeRange: 'monthly',
status: 'confirmed',
});
console.log('Transactions:', transactions.data); // Array of transaction objects
console.log('Pagination:', transactions.pagination); // e.g., { page: 1, limit: 10, total: 100, totalPages: 10 }
} catch (error) {
console.error('Error:', error.message);
}
}
fetchAllTransactions();Error Handling
The SDK includes custom errors to make debugging easier. Here are some common ones:
UnauthorizedError: Missing or invalid credentials (401).InvalidLicenseError: Problem with your license (403).BadRequestError: Invalid input (400).NotFoundError: Resource not found (404).
Here’s how to handle them:
import { MerchantSDK, UnauthorizedError, BadRequestError } from '3tpay-sdk';
const config = Config.getInstance({ trialHash: 'trial-abc789' });
const merchant = new MerchantSDK(config.getConfig());
async function tryCreatingInvoice() {
const invoiceData = { merchantId: 'merch-001', amount: 50, currency: 'USDT', blockchain: 'mind', expirationMinutes: 30 };
try {
const invoice = await merchant.createInvoice(invoiceData);
console.log('Invoice created:', invoice.invoiceId);
} catch (error) {
if (error instanceof UnauthorizedError) {
console.error('Auth failed:', error.message);
} else if (error instanceof BadRequestError) {
console.error('Bad input:', error.message);
} else {
console.error('Unknown error:', error.message);
}
}
}
tryCreatingInvoice();Testing the SDK
The SDK comes with tests. Run them with:
npm testOr with Yarn:
yarn testSet up a mock server or local API instance for full test coverage.
Contributing
Want to help improve the SDK? Here’s how:
- Fork the repo.
- Create a branch for your changes.
- Add tests for your updates.
- Submit a pull request with a clear explanation.
Make sure your code follows the SDK’s style and passes all tests.
License
The 3tpay-sdk is released under the MIT License. Check the LICENSE file for details.
Happy coding! This README has everything you need to integrate the 3tpay-sdk smoothly, with examples you can paste and play with right away. If you need more help, feel free to reach out!
