UNPKG

nodejs-cryptomus

Version:

A comprehensive Node.js client for the Cryptomus API

106 lines (105 loc) 3.51 kB
import axios from 'axios'; import { CryptomusError } from './types'; import { generateSignature } from './utils/signature'; /** * Cryptomus API client */ export class CryptomusClient { /** * Create a new Cryptomus API client * * @param options - Configuration options */ constructor(options) { this.merchantId = options.merchantId; this.paymentKey = options.paymentKey; this.payoutKey = options.payoutKey; this.apiUrl = options.apiUrl || 'https://api.cryptomus.com/v1'; this.httpClient = axios.create({ baseURL: this.apiUrl, timeout: 30000, headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' } }); } /** * Make a request to the payment API * * @param method - HTTP method * @param endpoint - API endpoint * @param data - Request payload * @param options - Request options * @returns API response */ async requestPayment(method, endpoint, data = {}, options = {}) { return this.request(method, endpoint, data, this.paymentKey, options); } /** * Make a request to the payout API * * @param method - HTTP method * @param endpoint - API endpoint * @param data - Request payload * @param options - Request options * @returns API response * @throws Error if payout key is not provided */ async requestPayout(method, endpoint, data = {}, options = {}) { if (!this.payoutKey) { throw new Error('Payout key is required for payout operations'); } return this.request(method, endpoint, data, this.payoutKey, options); } /** * Make a request to the API * * @param method - HTTP method * @param endpoint - API endpoint * @param data - Request payload * @param apiKey - API key * @param options - Request options * @returns API response * @throws CryptomusError with API error message */ async request(method, endpoint, data = {}, apiKey, options = {}) { var _a, _b; const payload = method === 'GET' ? {} : data; const sign = generateSignature(payload, apiKey); const config = { method, url: endpoint, headers: { ...options.headers, 'merchant': this.merchantId, 'sign': sign }, timeout: options.timeout }; if (method === 'GET') { config.params = data; } else { config.data = payload; } try { const response = await this.httpClient.request(config); return response.data; } catch (error) { if (axios.isAxiosError(error) && error.response) { const axiosError = error; const errorResponse = (_a = axiosError.response) === null || _a === void 0 ? void 0 : _a.data; throw new CryptomusError(errorResponse.message || 'API request failed', errorResponse.errors, (_b = axiosError.response) === null || _b === void 0 ? void 0 : _b.status); } // Re-throw any other errors if (error instanceof Error) { throw new CryptomusError(error.message); } else { throw new CryptomusError('Unknown error occurred'); } } } }