function AccountBase(client, data) { if (!(this instanceof AccountBase)) { return new AccountBase(client, data); } BaseModel.call(this, client, data); }
n/a
function Base() { if (!(this instanceof Base)) { return new Base(); } }
n/a
function Client(opts) { if (!(this instanceof Client)) { return new Client(opts); } ClientBase.call(this, opts); }
...
With a `client instance`, you can now make API calls. We've included some examples below, but in general the library has Javascript
prototypes for each of the objects described in our [REST API documentation](https://developers.coinbase.com/api/v2). These classes
each have methods for making the relevant API calls; for instance, ``coinbase.model.Transaction.complete`` maps to the [complete
bitcoin request](https://developers.coinbase.com/api/v2#complete-request-money) API endpoint. The comments of each method in the
code references the endpoint it implements. Each API method returns an ``object`` representing the JSON response from the API.
**Listing available accounts**
```javascript
var coinbase = require('coinbase');
var client = new coinbase.Client({'apiKey': mykey, 'apiSecret':
mysecret});
client.getAccounts({}, function(err, accounts) {
accounts.forEach(function(acct) {
console.log('my bal: ' + acct.balance.amount + ' for ' + acct.name);
});
});
```
...
function ClientBase(opts) { if (!(this instanceof ClientBase)) { return new ClientBase(opts); } // assign defaults and options to the context assign(this, { baseApiUri: BASE_URI, tokenUri: TOKEN_ENDPOINT_URI, caFile: CERT_STORE, strictSSL: true }, opts); // check for the different auth strategies var api = !!(this.apiKey && this.apiSecret) var oauth = !!this.accessToken; // XOR if (!(api ^ oauth)) { throw new Error('you must either provide an "accessToken" or the "apiKey" & "apiSecret" parameters'); } }
n/a
function Transfer(client, data, account) { if (!(this instanceof Transfer)) { return new Transfer(client, data, account); } BaseModel.call(this, client, data); if (!account) { throw new Error("no account arg"); } if (!account.id) { throw new Error("account has no id"); } this.account = account; }
n/a
function Account(client, data) { if (!(this instanceof Account)) { return new Account(client, data); } AccountBase.call(this, client, data); }
n/a
function Address(client, data, account) { if (!(this instanceof Address)) { return new Address(client, data, account); } BaseModel.call(this, client, data); if (!account) { throw new Error("no account arg"); } if (!account.id) { throw new Error("account has no id"); } this.account = account; }
n/a
function Buy(client, data, account) { if (!(this instanceof Buy)) { return new Buy(client, data, account); } Transfer.call(this, client, data, account); }
n/a
function Checkout(client, data) { if (!(this instanceof Checkout)) { return new Checkout(client, data); } BaseModel.call(this, client, data); }
n/a
function Deposit(client, data, account) { if (!(this instanceof Deposit)) { return new Deposit(client, data, account); } Transfer.call(this, client, data, account); }
n/a
function Order(client, data) { if (!(this instanceof Order)) { return new Order(client, data); } BaseModel.call(this, client, data); }
n/a
function Sell(client, data, account) { if (!(this instanceof Sell)) { return new Sell(client, data, account); } Transfer.call(this, client, data, account); }
n/a
function Transaction(client, data, account) { if (!(this instanceof Transaction)) { return new Transaction(client, data, account); } BaseModel.call(this, client, data); if (!account) { throw new Error("no account arg"); } if (!account.id) { throw new Error("account has no id"); } this.account = account; }
n/a
function User(client, data) { if (!(this instanceof User)) { return new User(client, data); } BaseModel.call(this, client, data); }
n/a
function Withdrawal(client, data, account) { if (!(this instanceof Withdrawal)) { return new Withdrawal(client, data, account); } Transfer.call(this, client, data, account); }
n/a
function AccountBase(client, data) { if (!(this instanceof AccountBase)) { return new AccountBase(client, data); } BaseModel.call(this, client, data); }
n/a
_getAll = function (opts, callback, headers) { var self = this; var args = {}; var path; if (this.hasField(opts, 'next_uri')) { path = opts.next_uri.replace('/v2/', ''); args = null; } else { path = 'accounts/' + this.id + '/' + opts.colName; if (this.hasField(opts, 'starting_after')) { args.starting_after = opts.starting_after; } if (this.hasField(opts, 'ending_before')) { args.ending_before = opts.ending_before; } if (this.hasField(opts, 'limit')) { args.limit = opts.limit; } if (this.hasField(opts, 'order')) { args.order = opts.order; } } this.client._getHttp(path, args, function onGet(err, result) { if (!handleError(err, result, callback)) { if (result.data.length > 0) { var ObjFunc = self.client._stringToClass(result.data[0].resource); } var objs = _.map(result.data, function onMap(obj) { return new ObjFunc(self.client, obj, self); }); callback(null, objs, result.pagination); } }, headers); }
...
// };
Account.prototype.getAddresses = function(args, callback) {
var opts = {
'colName' : 'addresses',
'ObjFunc' : Address,
};
this._getAll(_.assign(args || {}, opts), callback)
};
Account.prototype.getAddress = function(addressId, callback) {
var opts = {
'colName' : 'addresses',
'ObjFunc' : Address,
'id' : addressId
...
_getOne = function (opts, callback, headers) { var self = this; var path = 'accounts/' + this.id + '/' + opts.colName + '/' + opts.id; this.client._getHttp(path, null, function onGet(err, obj) { if (!handleError(err, obj, callback)) { var ObjFunc = self.client._stringToClass(obj.data.resource); callback(null, new ObjFunc(self.client, obj.data, self)); } }, headers); }
...
Account.prototype.getAddress = function(addressId, callback) {
var opts = {
'colName' : 'addresses',
'ObjFunc' : Address,
'id' : addressId
};
this._getOne(opts, callback)
};
// ```
// args = {
// 'name': address label, (optional)
// 'callback_url': callback_url (optional)
// };
...
_initTxn = function (args, callback, headers) { var self = this; var path = 'accounts/' + this.id + "/transactions"; this.client._postHttp(path, args, function onPost(err, obj) { if (!handleError(err, obj, callback)) { var txn = new Transaction(self.client, obj.data, self); callback(null, txn); } }, headers); }
...
// 'amount' : amount,
// 'currency' : currency,
// 'description' : notes
// };
Account.prototype.transferMoney = function(args, callback) {
args.type = 'transfer';
this._initTxn(args, callback);
};
//```
// args = {
// 'to' : bitcoin address or email,
// 'amount' : amount,
// 'currency' : currency,
...
_postOne = function (opts, callback, headers) { var self = this; var path = 'accounts/' + this.id + '/' + opts.colName; this.client._postHttp(path, opts.params, function onPost(err, obj) { if (!handleError(err, obj, callback)) { var ObjFunc = self.client._stringToClass(obj.data.resource); callback(null, new ObjFunc(self.client, obj.data, self)); } }, headers); }
...
// ```
Account.prototype.createAddress = function(args, callback) {
var opts = {
'colName' : 'addresses',
'ObjFunc' : Address,
'params' : args
};
this._postOne(opts, callback)
};
Account.prototype.getTransactions = function(args, callback) {
var opts = {
'colName' : 'transactions',
'ObjFunc' : Transaction,
...
function Base() { if (!(this instanceof Base)) { return new Base(); } }
n/a
dumpJSON = function () { return JSON.stringify(this.getProps()); }
...
};
Base.prototype.dumpJSON = function() {
return JSON.stringify(this.getProps());
};
Base.prototype.toString = function() {
return this.dumpJSON();
};
module.exports = Base;
...
getProps = function () { var tmp = {}; assign(tmp, this); delete tmp.client; delete tmp.account; return tmp; }
...
assign(tmp, this);
delete tmp.client;
delete tmp.account;
return tmp;
};
Base.prototype.dumpJSON = function() {
return JSON.stringify(this.getProps());
};
Base.prototype.toString = function() {
return this.dumpJSON();
};
module.exports = Base;
...
hasField = function (obj, field) { return (obj && obj.hasOwnProperty(field) && obj[field]); }
...
// };
// ```
//
ClientBase.prototype._getAllHttp = function(opts, callback, headers) {
var self = this;
var args = {}
var path;
if (this.hasField(opts, 'next_uri')) {
path = opts.next_uri.replace('/v2/', '');
args = null;
} else {
path = opts.colName;
if (this.hasField(opts, 'starting_after')) {
args.starting_after = opts.starting_after;
}
...
toString = function () { return this.dumpJSON(); }
n/a
function Client(opts) { if (!(this instanceof Client)) { return new Client(opts); } ClientBase.call(this, opts); }
...
With a `client instance`, you can now make API calls. We've included some examples below, but in general the library has Javascript
prototypes for each of the objects described in our [REST API documentation](https://developers.coinbase.com/api/v2). These classes
each have methods for making the relevant API calls; for instance, ``coinbase.model.Transaction.complete`` maps to the [complete
bitcoin request](https://developers.coinbase.com/api/v2#complete-request-money) API endpoint. The comments of each method in the
code references the endpoint it implements. Each API method returns an ``object`` representing the JSON response from the API.
**Listing available accounts**
```javascript
var coinbase = require('coinbase');
var client = new coinbase.Client({'apiKey': mykey, 'apiSecret':
mysecret});
client.getAccounts({}, function(err, accounts) {
accounts.forEach(function(acct) {
console.log('my bal: ' + acct.balance.amount + ' for ' + acct.name);
});
});
```
...
createAccount = function (args, callback) { var opts = { 'colName' : 'accounts', 'ObjFunc' : Account, 'params' : args }; this._postOneHttp(opts, callback); }
...
});
});
it('should create account', function() {
var args = {
"name": na.NEW_ACCOUNT_NAME_1
};
client.createAccount(args, function(err, account) {
assert.equal(err, null, err);
assert(account, 'no account');
assert(account.name, 'no name');
assert.equal(account.name, na.NEW_ACCOUNT_NAME_1, 'wrong account name');
});
});
...
createCheckout = function (args, callback) { var opts = { 'colName' : 'checkouts', 'ObjFunc' : Checkout, 'params' : args }; this._postOneHttp(opts, callback); }
n/a
createOrder = function (args, callback) { var opts = { 'colName' : 'orders', 'ObjFunc' : Order, 'params' : args }; this._postOneHttp(opts, callback); }
...
});
});
it('should create order', function() {
client.getCheckout(na.GET_CHECKOUT_RESP.data.id, function(err, checkout) {
assert.equal(err, null, err);
assert(checkout);
checkout.createOrder(function(err, order) {
assert.equal(err, null, err);
assert(order);
assert.equal(order.id, na.CREATE_ORDER_RESP.data.id);
});
});
});
...
getAccount = function (account_id, callback) { var opts = { 'path' : 'accounts/' + account_id, 'ObjFunc' : Account }; this._getOneHttp(opts, callback); }
...
**Get Balance from an Account Id**
```javascript
var coinbase = require('coinbase');
var client = new coinbase.Client({'apiKey': mykey, 'apiSecret': mysecret});
client.getAccount('<ACCOUNT ID>', function(err, account) {
console.log('bal: ' + account.balance.amount + ' currency: ' + account.balance.currency);
});
```
**Selling bitcoin**
```javascript
...
getAccounts = function (args, callback) { var opts = { 'colName' : 'accounts', 'ObjFunc' : Account }; this._getAllHttp(_.assign(args || {}, opts), callback) }
...
**Listing available accounts**
```javascript
var coinbase = require('coinbase');
var client = new coinbase.Client({'apiKey': mykey, 'apiSecret': mysecret});
client.getAccounts({}, function(err, accounts) {
accounts.forEach(function(acct) {
console.log('my bal: ' + acct.balance.amount + ' for ' + acct.name);
});
});
```
**Get Balance from an Account Id**
...
getBuyPrice = function (params, callback) { var currencyPair; if (params.currencyPair) { currencyPair = params.currencyPair; } else if (params.currency) { currencyPair = 'BTC-' + params.currency; } else { currencyPair = 'BTC-USD'; } this._getOneHttp({'path': 'prices/' + currencyPair + '/buy'}, callback); }
...
});
});
```
**Checking bitcoin prices**
```javascript
client.getBuyPrice({'currencyPair': 'BTC-USD'}, function(err, obj
) {
console.log('total amount: ' + obj.data.amount);
});
```
**Verifying merchant callback authenticity**
```javascript
if (client.verifyCallback(req.raw_body, req.headers['CB-SIGNATURE'])) {
...
getCheckout = function (checkoutId, callback) { var opts = { 'path' : 'checkouts/' + checkoutId, 'ObjFunc' : Checkout }; this._getOneHttp(opts, callback); }
...
});
describe('checkout methods', function() {
var client = new Client({'apiKey': 'mykey', 'apiSecret': 'mysecret', 'baseApiUri
': na.TEST_BASE_URI});
it('should get orders', function() {
client.getCheckout(na.GET_CHECKOUT_RESP.data.code, function(err, checkout) {
assert.equal(err, null, err);
assert(checkout);
checkout.getOrders(null, function(err, order) {
assert.equal(err, null, err);
assert(order);
assert.equal(order[0].id, na.GET_ORDERS_RESP.data[0].id);
...
getCheckouts = function (args, callback) { var opts = { 'colName' : 'checkouts', 'ObjFunc' : Checkout }; this._getAllHttp(_.assign(args || {}, opts), callback) }
n/a
getCurrencies = function (callback) { this._getOneHttp({'path': 'currencies'}, callback); }
...
assert.equal(obj.data.amount,
na.GET_SPOT_RESP.data.amount,
'wrong amount: ' + obj.data.amount);
});
});
it('should get supported currencies', function() {
client.getCurrencies(function(err, obj) {
assert.equal(err, null, err);
assert(obj, 'no currencies');
assert.equal(obj.length,
na.GET_CURRENCIES_RESP.length,
'wrong number of currencies: ' + obj.length);
});
});
...
getCurrentUser = function (callback) { var opts = { 'path' : 'user', 'ObjFunc' : User }; this._getOneHttp(opts, callback); }
...
assert(account, 'no account');
assert(account.name, 'no name');
assert.equal(account.name, na.NEW_ACCOUNT_NAME_1, 'wrong account name');
});
});
it('should get current user', function() {
client.getCurrentUser(function(err, user) {
assert.equal(err, null, err);
assert(user, 'no user');
assert(user.name, "no email");
assert.equal(user.name,
na.GET_CURRENT_USER_RESP.data.name,
'wrong user: ' + user.name);
...
getExchangeRates = function (params, callback) { this._getOneHttp({'path': 'exchange-rates', 'params': params}, callback); }
...
assert.equal(obj.length,
na.GET_CURRENCIES_RESP.length,
'wrong number of currencies: ' + obj.length);
});
});
it('should get exchange rates', function() {
client.getExchangeRates({}, function(err, obj) {
assert.equal(err, null, err);
assert(obj, 'no rates');
assert(obj.data.rates, "no rate");
assert.equal(obj.data.rates.AED,
na.GET_EX_RATES_RESP.data.rates.AED,
'wrong rate: ' + obj.data.rates.AED);
});
...
getHistoricPrices = function (params, callback) { this._getOneHttp({'path': 'prices/historic', 'params': params} , callback); }
n/a
getMerchant = function (merchantId, callback) { var opts = { 'path' : 'merchants/' + merchantId, 'ObjFunc' : Merchant }; this._getOneHttp(opts, callback); }
n/a
getNotification = function (notificationId, callback) { var opts = { 'path' : 'notifications/' + notificationId, 'ObjFunc' : Notification }; this._getOneHttp(opts, callback); }
n/a
getNotifications = function (args, callback) { var opts = { 'colName' : 'notifications', 'ObjFunc' : Notification }; this._getAllHttp(_.assign(args || {}, opts), callback) }
n/a
getOrder = function (orderId, callback) { var opts = { 'path' : 'orders/' + orderId, 'ObjFunc' : Order }; this._getOneHttp(opts, callback); }
n/a
getOrders = function (args, callback) { var opts = { 'colName' : 'orders', 'ObjFunc' : Order }; this._getAllHttp(_.assign(args || {}, opts), callback) }
...
var client = new Client({'apiKey': 'mykey', 'apiSecret': 'mysecret', 'baseApiUri'
;: na.TEST_BASE_URI});
it('should get orders', function() {
client.getCheckout(na.GET_CHECKOUT_RESP.data.code, function(err, checkout) {
assert.equal(err, null, err);
assert(checkout);
checkout.getOrders(null, function(err, order) {
assert.equal(err, null, err);
assert(order);
assert.equal(order[0].id, na.GET_ORDERS_RESP.data[0].id);
});
});
});
...
getPaymentMethod = function (methodId, callback) { var opts = { 'path' : 'payment-methods/' + methodId, 'ObjFunc' : PaymentMethod }; this._getOneHttp(opts, callback); }
...
assert.equal(pms.length,
na.GET_PAYMENT_METHODS_RESP.data.length,
'wrong number of methods: ' + pms.length);
});
});
it('should get payment method', function() {
client.getPaymentMethod(na.GET_PAYMENT_METHOD_RESP.data.id,
function(err, pm) {
assert.equal(err, null, err);
assert(pm, 'no payment method');
assert.equal(pm.id, na.GET_PAYMENT_METHOD_RESP.data.id,
'wrong payment method');
});
});
...
getPaymentMethods = function (args, callback) { var opts = { 'colName' : 'payment-methods', 'ObjFunc' : PaymentMethod }; this._getAllHttp(_.assign(args || {}, opts), callback) }
...
assert.equal(obj.data.rates.AED,
na.GET_EX_RATES_RESP.data.rates.AED,
'wrong rate: ' + obj.data.rates.AED);
});
});
it('should get payment methods', function() {
client.getPaymentMethods({}, function(err, pms) {
assert.equal(err, null, err);
assert(pms, 'no payment methods');
assert.equal(pms.length,
na.GET_PAYMENT_METHODS_RESP.data.length,
'wrong number of methods: ' + pms.length);
});
});
...
getSellPrice = function (params, callback) { var currencyPair; if (params.currencyPair) { currencyPair = params.currencyPair; } else if (params.currency) { currencyPair = 'BTC-' + params.currency; } else { currencyPair = 'BTC-USD'; } this._getOneHttp({'path': 'prices/' + currencyPair + '/sell'}, callback); }
...
assert.equal(obj.data.amount,
na.GET_BUY_PRICE_RESP.data.amount,
'wrong amount: ' + obj.data.amount);
});
});
it('should get sell price (undefined)', function() {
client.getSellPrice({}, function(err, obj) {
assert.equal(err, null, err);
assert(obj, 'no price');
assert(obj.data.amount, 'no amount');
assert.equal(obj.data.amount,
na.GET_BUY_PRICE_RESP.data.amount,
'wrong amount: ' + obj.data.amount);
});
...
getSpotPrice = function (params, callback) { var currencyPair; if (params.currencyPair) { currencyPair = params.currencyPair; } else if (params.currency) { currencyPair = 'BTC-' + params.currency; } else { currencyPair = 'BTC-USD'; } this._getOneHttp({'path': 'prices/' + currencyPair + '/spot'}, callback); }
...
assert.equal(obj.data.amount,
na.GET_BUY_PRICE_RESP.data.amount,
'wrong amount: ' + obj.data.amount);
});
});
it('should get spot price (undefined)', function() {
client.getSpotPrice({}, function(err, obj) {
assert.equal(err, null, err);
assert(obj, 'no price');
assert(obj.data.amount, 'no amount');
assert.equal(obj.data.amount,
na.GET_SPOT_RESP.data.amount,
'wrong amount: ' + obj.data.amount);
});
...
getTime = function (callback) { this._getOneHttp({'path': 'time'}, callback); }
n/a
getUser = function (userId, callback) { var opts = { 'path' : 'users/' + userId, 'ObjFunc' : User }; this._getOneHttp(opts, callback); }
n/a
refresh = function (callback) { var self = this; var params = { 'grant_type' : 'refresh_token', 'refresh_token' : this.refreshToken }; var path = this.tokenUri; this._postHttp(path, params, function myPost(err, result) { if (err) { err.type = etypes.TokenRefreshError; callback(err, result); return; } self.accessToken = result.access_token; self.refreshToken = result.refresh_token; callback(null, result); }); }
n/a
toString = function () { return "Coinbase API Client for " + this.baseApiUri; }
n/a
verifyCallback = function (body, signature) { var verifier = crypto.createVerify('RSA-SHA256'); verifier.update(body); return verifier.verify(callback_key, signature, 'base64'); }
...
client.getBuyPrice({'currencyPair': 'BTC-USD'}, function(err, obj) {
console.log('total amount: ' + obj.data.amount);
});
```
**Verifying merchant callback authenticity**
```javascript
if (client.verifyCallback(req.raw_body, req.headers['CB-SIGNATURE'])) {
// Process callback
}
```
## Error Handling
Errors are thrown for invalid arguments but are otherwise returned as the
...
function ClientBase(opts) { if (!(this instanceof ClientBase)) { return new ClientBase(opts); } // assign defaults and options to the context assign(this, { baseApiUri: BASE_URI, tokenUri: TOKEN_ENDPOINT_URI, caFile: CERT_STORE, strictSSL: true }, opts); // check for the different auth strategies var api = !!(this.apiKey && this.apiSecret) var oauth = !!this.accessToken; // XOR if (!(api ^ oauth)) { throw new Error('you must either provide an "accessToken" or the "apiKey" & "apiSecret" parameters'); } }
n/a
_deleteHttp = function (path, callback, headers) { var url = this.baseApiUri + this._setAccessToken(path); request.del(url, this._generateReqOptions(url, path, null, 'DELETE', headers), function onDel(err, response, body) { if (!handleHttpError(err, response, callback)) { callback(null, body); } }); }
...
AccountBase.call(this, client, data);
}
Account.prototype = Object.create(AccountBase.prototype);
Account.prototype.delete = function(callback) {
var path = "accounts/" + this.id;
this.client._deleteHttp(path, callback);
};
Account.prototype.setPrimary = function(callback) {
var path = "accounts/" + this.id + "/primary";
this.client._postHttp(path, null, callback);
};
...
_generateReqOptions = function (url, path, body, method, headers) { var bodyStr = body ? JSON.stringify(body) : ''; // specify the options var options = { 'url': url, 'ca': this.caFile, 'strictSSL': this.strictSSL, 'body': bodyStr, 'method': method, 'headers' : { 'Content-Type' : 'application/json', 'Accept' : 'application/json', 'User-Agent' : 'coinbase/node/1.0.4' } }; // add additional headers when we're using the "api key" and "api secret" if (this.apiSecret && this.apiKey) { var sig = this._generateSignature(path, method, bodyStr); // add signature and nonce to the header options.headers = assign(options.headers, { 'CB-ACCESS-SIGN': sig.digest, 'CB-ACCESS-TIMESTAMP': sig.timestamp, 'CB-ACCESS-KEY': this.apiKey, 'CB-VERSION': this.version || '2016-02-18' }) } return options; }
...
ClientBase.prototype._getHttp = function(path, args, callback, headers) {
var params = '';
if (args && !_.isEmpty(args)) {
params = '?' + qs.stringify(args);
}
var url = this.baseApiUri + this._setAccessToken(path + params);
var opts = this._generateReqOptions(url, path + params, null, 'GET', headers
);
request.get(opts, function onGet(err, response, body) {
if (!handleHttpError(err, response, callback)) {
if (!body) {
callback(new Error("empty response"), null);
} else {
var obj = JSON.parse(body);
...
_generateSignature = function (path, method, bodyStr) { var timestamp = Math.floor(Date.now() / 1000); var message = timestamp + method + '/v2/' + path + bodyStr; var signature = crypto.createHmac('sha256', this.apiSecret).update(message).digest('hex'); return { 'digest': signature, 'timestamp': timestamp }; }
...
'Accept' : 'application/json',
'User-Agent' : 'coinbase/node/1.0.4'
}
};
// add additional headers when we're using the "api key" and "api secret"
if (this.apiSecret && this.apiKey) {
var sig = this._generateSignature(path, method, bodyStr);
// add signature and nonce to the header
options.headers = assign(options.headers, {
'CB-ACCESS-SIGN': sig.digest,
'CB-ACCESS-TIMESTAMP': sig.timestamp,
'CB-ACCESS-KEY': this.apiKey,
'CB-VERSION': this.version || '2016-02-18'
...
_getAllHttp = function (opts, callback, headers) { var self = this; var args = {} var path; if (this.hasField(opts, 'next_uri')) { path = opts.next_uri.replace('/v2/', ''); args = null; } else { path = opts.colName; if (this.hasField(opts, 'starting_after')) { args.starting_after = opts.starting_after; } if (this.hasField(opts, 'ending_before')) { args.ending_before = opts.ending_before; } if (this.hasField(opts, 'limit')) { args.limit = opts.limit; } if (this.hasField(opts, 'order')) { args.order = opts.order; } } this._getHttp(path, args, function onGet(err, result) { if (!handleError(err, result, callback)) { var objs = []; if (result.data.length !== 0) { var ObjFunc = self._stringToClass(result.data[0].resource); objs = _.map(result.data, function onMap(obj) { return new ObjFunc(self, obj); }); } callback(null, objs, result.pagination); } }, headers); }
...
Client.prototype.getAccounts = function(args, callback) {
var opts = {
'colName' : 'accounts',
'ObjFunc' : Account
};
this._getAllHttp(_.assign(args || {}, opts), callback)
};
Client.prototype.getAccount = function(account_id, callback) {
var opts = {
'path' : 'accounts/' + account_id,
'ObjFunc' : Account
...
_getHttp = function (path, args, callback, headers) { var params = ''; if (args && !_.isEmpty(args)) { params = '?' + qs.stringify(args); } var url = this.baseApiUri + this._setAccessToken(path + params); var opts = this._generateReqOptions(url, path + params, null, 'GET', headers); request.get(opts, function onGet(err, response, body) { if (!handleHttpError(err, response, callback)) { if (!body) { callback(new Error("empty response"), null); } else { var obj = JSON.parse(body); callback(null, obj); } } }); }
...
args.limit = opts.limit;
}
if (this.hasField(opts, 'order')) {
args.order = opts.order;
}
}
this._getHttp(path, args, function onGet(err, result) {
if (!handleError(err, result, callback)) {
var objs = [];
if (result.data.length !== 0) {
var ObjFunc = self._stringToClass(result.data[0].resource);
objs = _.map(result.data, function onMap(obj) {
return new ObjFunc(self, obj);
});
...
_getOneHttp = function (args, callback, headers) { var self = this; this._getHttp(args.path, args.params, function onGet(err, obj) { if (!handleError(err, obj, callback)) { if (obj.data.resource) { var ObjFunc = self._stringToClass(obj.data.resource); callback(null, new ObjFunc(self, obj.data)); } else { callback(null, obj); } } }, headers); }
...
Client.prototype.getAccount = function(account_id, callback) {
var opts = {
'path' : 'accounts/' + account_id,
'ObjFunc' : Account
};
this._getOneHttp(opts, callback);
};
Client.prototype.createAccount = function(args, callback) {
var opts = {
'colName' : 'accounts',
'ObjFunc' : Account,
...
_postHttp = function (path, body, callback, headers) { var url = this.baseApiUri + this._setAccessToken(path); body = body || {} var options = this._generateReqOptions(url, path, body, 'POST', headers); request.post(options, function onPost(err, response, body) { if (!handleHttpError(err, response, callback)) { if (body) { var obj = JSON.parse(body); callback(null, obj); } else { callback(null, body); } } }); }
...
// 'colName' : colName,
// 'params' : args
// }
//
ClientBase.prototype._postOneHttp = function(opts, callback, headers) {
var self = this;
var body = opts.params;
this._postHttp(opts.colName, body, function onPost(err, obj) {
if (!handleError(err, obj, callback)) {
if (obj.data.resource) {
var ObjFunc = self._stringToClass(obj.data.resource);
callback(null, new ObjFunc(self, obj.data));
} else {
callback(null, obj);
}
...
_postOneHttp = function (opts, callback, headers) { var self = this; var body = opts.params; this._postHttp(opts.colName, body, function onPost(err, obj) { if (!handleError(err, obj, callback)) { if (obj.data.resource) { var ObjFunc = self._stringToClass(obj.data.resource); callback(null, new ObjFunc(self, obj.data)); } else { callback(null, obj); } } }, headers); }
...
var opts = {
'colName' : 'accounts',
'ObjFunc' : Account,
'params' : args
};
this._postOneHttp(opts, callback);
};
Client.prototype.getCurrentUser = function(callback) {
var opts = {
'path' : 'user',
'ObjFunc' : User
...
_putHttp = function (path, body, callback, headers) { var url = this.baseApiUri + this._setAccessToken(path); var options = this._generateReqOptions(url, path, body, 'PUT', headers); request.put(options, function onPut(err, response, body) { if (!handleHttpError(err, response, callback)) { if (body) { var obj = JSON.parse(body); callback(null, obj); } else { callback(null, body); } } }); }
...
var path = "accounts/" + this.id + "/primary";
this.client._postHttp(path, null, callback);
};
Account.prototype.update = function(args, callback) {
var self = this;
var path = "accounts/" + this.id;
this.client._putHttp(path, args, function myPut(err, result) {
if (err) {
callback(err, null);
return;
}
var account = new Account(self.client, result.data);
callback(null, account);
});
...
_setAccessToken = function (path) { // OAuth access token if (this.accessToken) { if (path.indexOf('?') > -1) { return path + '&access_token=' + this.accessToken; } return path + '?access_token=' + this.accessToken; } return path }
...
ClientBase.prototype._getHttp = function(path, args, callback, headers) {
var params = '';
if (args && !_.isEmpty(args)) {
params = '?' + qs.stringify(args);
}
var url = this.baseApiUri + this._setAccessToken(path + params);
var opts = this._generateReqOptions(url, path + params, null, 'GET', headers);
request.get(opts, function onGet(err, response, body) {
if (!handleHttpError(err, response, callback)) {
if (!body) {
callback(new Error("empty response"), null);
} else {
...
_stringToClass = function (name) { return MODELS[name] }
...
}
}
this._getHttp(path, args, function onGet(err, result) {
if (!handleError(err, result, callback)) {
var objs = [];
if (result.data.length !== 0) {
var ObjFunc = self._stringToClass(result.data[0].resource);
objs = _.map(result.data, function onMap(obj) {
return new ObjFunc(self, obj);
});
}
callback(null, objs, result.pagination);
}
}, headers);
...
function Transfer(client, data, account) { if (!(this instanceof Transfer)) { return new Transfer(client, data, account); } BaseModel.call(this, client, data); if (!account) { throw new Error("no account arg"); } if (!account.id) { throw new Error("account has no id"); } this.account = account; }
n/a
_commit = function (opts, callback) { var self = this; var path = 'accounts/' + self.account.id + '/' + opts.colName + '/' + self.id + '/commit'; self.client._postHttp(path, null, function onPut(err, result) { if (!handleError(err, result, callback)) { callback(null, new opts.ObjFunc(self.client, result.data, self.account)); } }); }
...
Buy.prototype.commit = function(callback) {
var opts = {
'colName' : 'buys',
'ObjFunc' : Buy
};
this._commit(opts, callback);
};
module.exports = Buy;
...
function handleError(err, obj, callback) { if (!callback) {throw "no callback - check method signature";} if (err) { callback(err, null); return true; } if (obj.error) { callback(createError(obj.error, {name: 'APIError'}), null); return true; } if (obj.errors) { callback(createError(obj, {name: 'APIError'}), null); return true; } if (obj.success !== undefined && obj.success !== true) { callback(createError(obj, {name: 'APIError'}), null); return true; } return false; }
n/a
function handleHttpError(err, response, callback) { if (!callback) { throw new Error("no callback for http error handler- check method signature"); } if (err) { callback(err, null); return true; } if (!response) { callback(createError('no response'), null); return true; } if (response.statusCode !== 200 && response.statusCode !== 201 && response.statusCode !== 204) { var error; try { var errorBody = _parseError(JSON.parse(response.body)); error = createError(response.statusCode, errorBody.message, {name: _convertErrorName(errorBody.id)}); } catch (ex) { error = createError(response.statusCode, response.body); } callback(error, null); return true; } return false; }
n/a
function Account(client, data) { if (!(this instanceof Account)) { return new Account(client, data); } AccountBase.call(this, client, data); }
n/a
function Address(client, data, account) { if (!(this instanceof Address)) { return new Address(client, data, account); } BaseModel.call(this, client, data); if (!account) { throw new Error("no account arg"); } if (!account.id) { throw new Error("account has no id"); } this.account = account; }
n/a
function Buy(client, data, account) { if (!(this instanceof Buy)) { return new Buy(client, data, account); } Transfer.call(this, client, data, account); }
n/a
function Checkout(client, data) { if (!(this instanceof Checkout)) { return new Checkout(client, data); } BaseModel.call(this, client, data); }
n/a
function Deposit(client, data, account) { if (!(this instanceof Deposit)) { return new Deposit(client, data, account); } Transfer.call(this, client, data, account); }
n/a
function Merchant(client, data) { if (!(this instanceof Merchant)) { return new Merchant(client, data); } BaseModel.call(this, client, data); }
n/a
function Notification(client, data) { if (!(this instanceof Notification)) { return new Notification(client, data); } BaseModel.call(this, client, data); }
n/a
function Order(client, data) { if (!(this instanceof Order)) { return new Order(client, data); } BaseModel.call(this, client, data); }
n/a
function PaymentMethod(client, data) { if (!(this instanceof PaymentMethod)) { return new PaymentMethod(client, data); } BaseModel.call(this, client, data); }
n/a
function Sell(client, data, account) { if (!(this instanceof Sell)) { return new Sell(client, data, account); } Transfer.call(this, client, data, account); }
n/a
function Transaction(client, data, account) { if (!(this instanceof Transaction)) { return new Transaction(client, data, account); } BaseModel.call(this, client, data); if (!account) { throw new Error("no account arg"); } if (!account.id) { throw new Error("account has no id"); } this.account = account; }
n/a
function User(client, data) { if (!(this instanceof User)) { return new User(client, data); } BaseModel.call(this, client, data); }
n/a
function Withdrawal(client, data, account) { if (!(this instanceof Withdrawal)) { return new Withdrawal(client, data, account); } Transfer.call(this, client, data, account); }
n/a
function Account(client, data) { if (!(this instanceof Account)) { return new Account(client, data); } AccountBase.call(this, client, data); }
n/a
buy = function (args, callback) { var opts = { 'colName' : 'buys', 'ObjFunc' : Buy, 'params' : args }; this._postOne(opts, callback) }
...
});
});
it('should buy', function() {
var args = {
"qty": "100"
};
btcAccount.buy(args, function(err, transfer) {
assert.equal(err, null, err);
assert(transfer);
assert.equal(transfer.id, na.BUY_RESP.data.id,
"can not buy: " + JSON.stringify(transfer));
});
});
});
...
createAddress = function (args, callback) { var opts = { 'colName' : 'addresses', 'ObjFunc' : Address, 'params' : args }; this._postOne(opts, callback) }
...
});
it('should create address', function() {
var args = {
"callback_url": "http://www.example.com/callback",
"label": "Dalmation donations"
};
btcAccount.createAddress(args, function(err, result) {
assert.equal(err, null, err);
assert(result);
assert.equal(result.label, na.CREATE_ADDRESS_RESP.data.label,
"can not create address: " + JSON.stringify(result));
});
});
...
delete = function (callback) { var path = "accounts/" + this.id; this.client._deleteHttp(path, callback); }
...
nock(TEST_BASE_URI)
.filteringPath(EXPIRE_REGEX, '')
.post('/accounts/' + ACCOUNT_1.id + '/primary')
.reply(200, PRIMARY_RESPONSE);
nock(TEST_BASE_URI)
.filteringPath(EXPIRE_REGEX, '')
.delete('/accounts/' + ACCOUNT_3.id)
.reply(204, null);
var MODIFY_ACCOUNT_RESP = {
"data": {
"id": "53752d3e46cd93c93c00000c",
"resource": "account",
"name": "Satoshi Wallet",
...
deposit = function (args, callback) { var opts = { 'colName' : 'deposits', 'ObjFunc' : Deposit, 'params' : args }; this._postOne(opts, callback) }
n/a
getAddress = function (addressId, callback) { var opts = { 'colName' : 'addresses', 'ObjFunc' : Address, 'id' : addressId }; this._getOne(opts, callback) }
...
assert(result);
assert.equal(result.length, na.GET_ADDRESSES_RESP.data.length,
"can not get addresses: " + JSON.stringify(result));
});
});
it('should get address', function() {
btcAccount.getAddress(na.GET_ADDRESS_RESP.data.address, function(err, result) {
assert.equal(err, null, err);
assert(result);
assert.equal(result.id, na.GET_ADDRESS_RESP.data.id,
"can not get address: " + JSON.stringify(result));
assert.equal(result.label, na.GET_ADDRESS_RESP.data.label,
"can not get address: " + JSON.stringify(result));
});
...
getAddresses = function (args, callback) { var opts = { 'colName' : 'addresses', 'ObjFunc' : Address, }; this._getAll(_.assign(args || {}, opts), callback) }
...
assert.equal(err, null, err);
assert(account);
assert.equal(account.name, na.MODIFY_ACCOUNT_RESP.data.name, "can not modify account");
});
});
it('should get addresses', function() {
btcAccount.getAddresses(null, function(err, result) {
assert.equal(err, null, err);
assert(result);
assert.equal(result.length, na.GET_ADDRESSES_RESP.data.length,
"can not get addresses: " + JSON.stringify(result));
});
});
...
getBuy = function (buy_id, callback) { var opts = { 'colName' : 'buys', 'ObjFunc' : Buy, 'id' : buy_id }; this._getOne(opts, callback); }
n/a
getBuys = function (args, callback) { var opts = { 'colName' : 'buys', 'ObjFunc' : Buy, }; this._getAll(_.assign(args || {}, opts), callback) }
...
assert(txn);
assert.equal(txn.id, na.REQUEST_MONEY_RESP.data.id,
"can not request money: " + JSON.stringify(txn));
});
});
it('should get transfers', function() {
btcAccount.getBuys(null, function(err, result) {
assert.equal(err, null, err);
assert(result);
assert.equal(result.length,
na.GET_BUYS_RESP.data.length,
"can not get transfers: " + JSON.stringify(result));
});
});
...
getDeposit = function (deposit_id, callback) { var opts = { 'colName' : 'deposit', 'ObjFunc' : Deposit, 'id' : deposit_id }; this._getOne(opts, callback); }
n/a
getDeposits = function (args, callback) { var opts = { 'colName' : 'deposits', 'ObjFunc' : Deposit, }; this._getAll(_.assign(args || {}, opts), callback) }
n/a
getSell = function (sell_id, callback) { var opts = { 'colName' : 'sells', 'ObjFunc' : Sell, 'id' : sell_id }; this._getOne(opts, callback); }
n/a
getSells = function (args, callback) { var opts = { 'colName' : 'sells', 'ObjFunc' : Sell, }; this._getAll(_.assign(args || {}, opts), callback) }
n/a
getTransaction = function (transaction_id, callback) { var opts = { 'colName' : 'transactions', 'ObjFunc' : Transaction, 'id' : transaction_id }; this._getOne(opts, callback); }
...
assert.equal(result.length,
na.GET_TRANSACTIONS_RESP.data.length,
"can not get transactions: " + JSON.stringify(result));
});
});
it('should get transaction', function() {
btcAccount.getTransaction('1234', function(err, txn) {
assert.equal(err, null, err);
assert(txn);
assert.equal(txn.id, na.GET_TRANSACTION_RESP.data.id,
"can not get txn: " + JSON.stringify(txn));
});
});
...
getTransactions = function (args, callback) { var opts = { 'colName' : 'transactions', 'ObjFunc' : Transaction, }; this._getAll(_.assign(args || {}, opts), callback) }
...
console.log('my txn id is: ' + txn.id);
});
```
**Listing current transactions**
```javascript
account.getTransactions(null, function(err, txns) {
txns.forEach(function(txn) {
console.log('my txn status: ' + txn.status);
});
});
```
**Using pagination**
...
getWithdrawal = function (withdrawal_id, callback) { var opts = { 'colName' : 'withdrawals', 'ObjFunc' : Withdrawal, 'id' : withdrawal_id }; this._getOne(opts, callback); }
n/a
getWithdrawals = function (args, callback) { var opts = { 'colName' : 'withdrawals', 'ObjFunc' : Withdrawal, }; this._getAll(_.assign(args || {}, opts), callback) }
n/a
requestMoney = function (args, callback) { args.type = 'request'; this._initTxn(args, callback); }
...
```javascript
var args = {
"to": "user1@example.com",
"amount": "1.234",
"currency": "BTC",
"description": "Sample transaction for you"
};
account.requestMoney(args, function(err, txn) {
console.log('my txn id is: ' + txn.id);
});
```
**Listing current transactions**
```javascript
...
sell = function (args, callback) { var opts = { 'colName' : 'sells', 'ObjFunc' : Sell, 'params' : args }; this._postOne(opts, callback) }
...
**Selling bitcoin**
```javascript
var args = {
"amount": "12",
"currency": "BTC"
};
account.sell(args, function(err, xfer) {
console.log('my xfer id is: ' + xfer.id);
});
```
**Sending bitcoin**
```javascript
...
sendMoney = function (args, callback, twoFactorAuth) { var tfa = twoFactorAuth ? {'CB-2FA-Token': twoFactorAuth} : null; args.type = 'send'; this._initTxn(args, callback, tfa); }
...
```javascript
var args = {
"to": "user1@example.com",
"amount": "1.234",
"currency": "BTC",
"description": "Sample transaction for you"
};
account.sendMoney(args, function(err, txn) {
console.log('my txn id is: ' + txn.id);
});
```
**Requesting bitcoin**
```javascript
...
setPrimary = function (callback) { var path = "accounts/" + this.id + "/primary"; this.client._postHttp(path, null, callback); }
...
describe('account methods', function() {
var client = new Client({'apiKey': 'mykey', 'apiSecret': 'mysecret', 'baseApiUri'
;: na.TEST_BASE_URI});
var btcAccount = new Account(client, {"id": na.ACCOUNT_1.id});
var usdAccount1 = new Account(client, {"id": na.ACCOUNT_3.id});
it('should setPrimary', function() {
btcAccount.setPrimary(function(err, result) {
assert.equal(err, null, err);
assert(result);
});
});
it('should delete account', function() {
usdAccount1.delete(function(err, result) {
...
transferMoney = function (args, callback) { args.type = 'transfer'; this._initTxn(args, callback); }
...
it('should transfer money', function() {
var args = {
"to": "5011f33df8182b142400000a",
"amount": "1.234",
"notes": "Sample transaction for you"
};
btcAccount.transferMoney(args, function(err, txn) {
assert.equal(err, null, err);
assert(txn);
assert.equal(txn.id, na.TRANSFER_MONEY_RESP.data.id,
"can not transfer money: " + JSON.stringify(txn));
});
});
...
update = function (args, callback) { var self = this; var path = "accounts/" + this.id; this.client._putHttp(path, args, function myPut(err, result) { if (err) { callback(err, null); return; } var account = new Account(self.client, result.data); callback(null, account); }); }
...
}
return path
};
ClientBase.prototype._generateSignature = function(path, method, bodyStr) {
var timestamp = Math.floor(Date.now() / 1000);
var message = timestamp + method + '/v2/' + path + bodyStr;
var signature = crypto.createHmac('sha256', this.apiSecret).update(message
).digest('hex');
return {
'digest': signature,
'timestamp': timestamp
};
};
...
withdraw = function (args, callback) { var opts = { 'colName' : 'withdrawals', 'ObjFunc' : Withdrawal, 'params' : args }; this._postOne(opts, callback) }
n/a
function Address(client, data, account) { if (!(this instanceof Address)) { return new Address(client, data, account); } BaseModel.call(this, client, data); if (!account) { throw new Error("no account arg"); } if (!account.id) { throw new Error("account has no id"); } this.account = account; }
n/a
getTransactions = function (args, callback) { var opts = { 'colName' : 'addresses/' + this.id + '/transactions', 'ObjFunc' : Transaction, }; this.account._getAll(_.assign(args || {}, opts), callback) }
...
console.log('my txn id is: ' + txn.id);
});
```
**Listing current transactions**
```javascript
account.getTransactions(null, function(err, txns) {
txns.forEach(function(txn) {
console.log('my txn status: ' + txn.status);
});
});
```
**Using pagination**
...
function Buy(client, data, account) { if (!(this instanceof Buy)) { return new Buy(client, data, account); } Transfer.call(this, client, data, account); }
n/a
commit = function (callback) { var opts = { 'colName' : 'buys', 'ObjFunc' : Buy }; this._commit(opts, callback); }
...
describe('buy methods', function() {
var client = new Client({'apiKey': 'mykey', 'apiSecret': 'mysecret', 'baseApiUri
': na.TEST_BASE_URI});
var account = new Account(client, na.ACCT);
var xfer = new Buy(client, na.XFER_1, account);
it('should commit transfer', function() {
xfer.commit(function(err, update) {
assert.equal(err, null, err);
assert(update, 'no updated xfer');
});
});
});
});
...
function Checkout(client, data) { if (!(this instanceof Checkout)) { return new Checkout(client, data); } BaseModel.call(this, client, data); }
n/a
createOrder = function (callback) { var opts = { 'colName' : 'checkouts/' + this.id + '/orders', 'ObjFunc' : Order, }; this.client._postOneHttp(opts, callback); }
...
});
});
it('should create order', function() {
client.getCheckout(na.GET_CHECKOUT_RESP.data.id, function(err, checkout) {
assert.equal(err, null, err);
assert(checkout);
checkout.createOrder(function(err, order) {
assert.equal(err, null, err);
assert(order);
assert.equal(order.id, na.CREATE_ORDER_RESP.data.id);
});
});
});
...
getOrders = function (args, callback) { var opts = { 'colName' : 'checkouts/' + this.id + '/orders', 'ObjFunc' : Order }; this.client._getAllHttp(_.assign(args || {}, opts), callback) }
...
var client = new Client({'apiKey': 'mykey', 'apiSecret': 'mysecret', 'baseApiUri'
;: na.TEST_BASE_URI});
it('should get orders', function() {
client.getCheckout(na.GET_CHECKOUT_RESP.data.code, function(err, checkout) {
assert.equal(err, null, err);
assert(checkout);
checkout.getOrders(null, function(err, order) {
assert.equal(err, null, err);
assert(order);
assert.equal(order[0].id, na.GET_ORDERS_RESP.data[0].id);
});
});
});
...
function Deposit(client, data, account) { if (!(this instanceof Deposit)) { return new Deposit(client, data, account); } Transfer.call(this, client, data, account); }
n/a
commit = function (callback) { var opts = { 'colName' : 'deposits', 'ObjFunc' : Deposit }; this._commit(opts, callback); }
...
describe('buy methods', function() {
var client = new Client({'apiKey': 'mykey', 'apiSecret': 'mysecret', 'baseApiUri
': na.TEST_BASE_URI});
var account = new Account(client, na.ACCT);
var xfer = new Buy(client, na.XFER_1, account);
it('should commit transfer', function() {
xfer.commit(function(err, update) {
assert.equal(err, null, err);
assert(update, 'no updated xfer');
});
});
});
});
...
function Order(client, data) { if (!(this instanceof Order)) { return new Order(client, data); } BaseModel.call(this, client, data); }
n/a
refund = function (args, callback) { var self = this; if (!self.client) {throw "no client";} if (!self.id) { callback(new Error("no order id"), null); return; } var path = 'orders/' + self.id + '/refund'; self.client._postHttp(path, args, function onPost(err, result) { if (!handleError(err, result, callback)) { var order = new Order(self.client, result.data); callback(null, order); } }); }
...
describe('order methods', function() {
var client = new Client({'apiKey': 'mykey', 'apiSecret': 'mysecret', 'baseApiUri'
;: na.TEST_BASE_URI});
var order = new Order(client, na.REFUND_RESP.data);
it('should refund order', function() {
var args = {};
order.refund(args, function(err, order) {
assert.equal(err, null, err);
assert(order, 'no refund');
assert(order.id);
assert.equal(order.id, na.REFUND_RESP.data.id, 'wrong order');
assert(order.refund_transaction.id);
assert.equal(order.refund_transaction.id,
na.REFUND_RESP.data.refund_transaction.id, 'no refund txn');
...
function Sell(client, data, account) { if (!(this instanceof Sell)) { return new Sell(client, data, account); } Transfer.call(this, client, data, account); }
n/a
commit = function (callback) { var opts = { 'colName' : 'sells', 'ObjFunc' : Sell }; this._commit(opts, callback); }
...
describe('buy methods', function() {
var client = new Client({'apiKey': 'mykey', 'apiSecret': 'mysecret', 'baseApiUri
': na.TEST_BASE_URI});
var account = new Account(client, na.ACCT);
var xfer = new Buy(client, na.XFER_1, account);
it('should commit transfer', function() {
xfer.commit(function(err, update) {
assert.equal(err, null, err);
assert(update, 'no updated xfer');
});
});
});
});
...
function Transaction(client, data, account) { if (!(this instanceof Transaction)) { return new Transaction(client, data, account); } BaseModel.call(this, client, data); if (!account) { throw new Error("no account arg"); } if (!account.id) { throw new Error("account has no id"); } this.account = account; }
n/a
cancel = function (callback) { var self = this; if (self.type !== 'request') { throw "Can only cancel 'request' transactions"; } var path = 'accounts/' + self.account.id + '/transactions/' + self.id; self.client._deleteHttp(path, function onDel(err, result) { if (!handleError(err, result, callback)) { callback(null, result); } }); }
...
assert.equal(txn.id, na.COMPLETE_RESP.data.id,
'wrong txn id');
assert.equal(txn.status, 'pending', 'wrong txn status');
});
});
it('should cancel transaction', function() {
txn.cancel(function(err, res) {
assert.equal(err, null, err);
});
});
});
});
...
complete = function (callback) { var self = this; if (self.type !== 'request') { throw "Can only complete 'request' transactions"; } var path = 'accounts/' + self.account.id + '/transactions/' + self.id + '/complete'; self.client._postHttp(path, null, function onPut(err, result) { if (!handleError(err, result, callback)) { callback(null, new Transaction(self.client, result.data, self.account)); } }); }
...
it('should resend transaction', function() {
txn.resend(function(err, res) {
assert.equal(err, null, err);
});
});
it('should complete transaction', function() {
txn.complete(function(err, txn) {
assert.equal(err, null, err);
assert(txn, 'no txn');
assert(txn.id, 'no txn id');
assert.equal(txn.id, na.COMPLETE_RESP.data.id,
'wrong txn id');
assert.equal(txn.status, 'pending', 'wrong txn status');
});
...
resend = function (callback) { var self = this; if (self.type !== 'request') { throw "Can only resend 'request' transactions"; } var path = 'accounts/' + self.account.id + '/transactions/' + self.id + '/resend'; self.client._postHttp(path, null, function onPut(err, result) { if (!handleError(err, result, callback)) { callback(null, result); } }); }
...
});
describe('transaction methods', function() {
var client = new Client({'apiKey': 'mykey', 'apiSecret': 'mysecret', 'baseApiUri'
;: na.TEST_BASE_URI});
var txn = new Transaction(client, na.TXN_1, {'id': 'A1234'});
it('should resend transaction', function() {
txn.resend(function(err, res) {
assert.equal(err, null, err);
});
});
it('should complete transaction', function() {
txn.complete(function(err, txn) {
assert.equal(err, null, err);
...
function User(client, data) { if (!(this instanceof User)) { return new User(client, data); } BaseModel.call(this, client, data); }
n/a
showAuth = function (callback) { var self = this; if (!self.client) {throw "no client";} if (!self.id) { callback(new Error("no user id"), null); return; } var path = 'user/auth'; self.client._getHttp(path, null, function onGet(err, result) { if (!handleError(err, result, callback)) { callback(null, result.data); } }); }
n/a
update = function (args, callback) { var self = this; if (!self.client) {throw "no client";} if (!self.id) { callback(new Error("no user id"), null); return; } var path = 'user'; self.client._putHttp(path, args, function onPut(err, result) { if (!handleError(err, result, callback)) { callback(null, new User(self.client, result.data)); } }); }
...
}
return path
};
ClientBase.prototype._generateSignature = function(path, method, bodyStr) {
var timestamp = Math.floor(Date.now() / 1000);
var message = timestamp + method + '/v2/' + path + bodyStr;
var signature = crypto.createHmac('sha256', this.apiSecret).update(message
).digest('hex');
return {
'digest': signature,
'timestamp': timestamp
};
};
...
function Withdrawal(client, data, account) { if (!(this instanceof Withdrawal)) { return new Withdrawal(client, data, account); } Transfer.call(this, client, data, account); }
n/a
commit = function (callback) { var opts = { 'colName' : 'withdrawals', 'ObjFunc' : Withdrawal }; this._commit(opts, callback); }
...
describe('buy methods', function() {
var client = new Client({'apiKey': 'mykey', 'apiSecret': 'mysecret', 'baseApiUri
': na.TEST_BASE_URI});
var account = new Account(client, na.ACCT);
var xfer = new Buy(client, na.XFER_1, account);
it('should commit transfer', function() {
xfer.commit(function(err, update) {
assert.equal(err, null, err);
assert(update, 'no updated xfer');
});
});
});
});
...