UNPKG

blockchain-payments-node

Version:
102 lines (101 loc) 3.34 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const qs_1 = __importDefault(require("qs")); const axios_1 = __importDefault(require("axios")); const BlockchainPaymentsError_1 = require("./Errors/BlockchainPaymentsError"); const BlockchainAddressGapTooLarge_1 = __importDefault(require("./Errors/BlockchainAddressGapTooLarge")); /** * Blockchain.info Payments API (V2) * * @link https://www.blockchain.com/api/api_receive */ class BlockchainPayments { /** * Blockchain Payments constructor */ constructor({ apiKey, xpub, webhookSecret }) { this.apiKey = apiKey; this.xpub = xpub; this.webhookSecret = webhookSecret; this.api = axios_1.default.create({ baseURL: 'https://api.blockchain.info/v2/receive', paramsSerializer(params) { return qs_1.default.stringify(params); } }); this.api.interceptors.response.use(undefined, this.handleException); } /** * Handle an API request error. */ handleException(error) { let data; let exception = BlockchainPaymentsError_1.BlockchainPaymentsError; if (error.response && typeof error.response.data === 'object') { data = error.response.data; } if (data && data.message === 'Problem with xpub') { exception = BlockchainAddressGapTooLarge_1.default; } throw new exception(error.message, data); } /** * Prepare querystring, including the API key using the given data. */ buildQuery(data) { return Object.assign({ key: this.apiKey }, data); } /** * Create a payment address. */ createAddress(options) { return this.api.get('', { params: this.buildQuery({ xpub: this.xpub, callback: options.webhookUrl, }), }).then(({ data }) => { return data; }); } /** * Monitor any Bitcoin address for incoming payments. */ watchAddress({ onNotification = 'KEEP', confirmations = 1, type = 'ALL', address, webhookUrl, }) { const query = this.buildQuery({ addr: address, callback: webhookUrl, op: type, confs: confirmations, onNotification, }); return this.api.post('/balance_update', JSON.stringify(query), { headers: { 'Content-Type': 'text/plain', } }).then((response) => { return response.data; }); } /** * Stop address watching for the given watcher ID. * IDs are returned by the watchAddress() method's response body. */ stopWatch(id) { return this.api.delete(`/balance_update/${id}`, { params: this.buildQuery(), }).then((response) => { return response.data; }); } /** * Update the currently used xPub to the given xPub. */ setXPub(xpub) { this.xpub = xpub; } } exports.default = BlockchainPayments;