Skip to content

Instantly share code, notes, and snippets.

@optimalisatie
Last active November 11, 2018 08:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save optimalisatie/b35061f58d3fbcb5abf475c9ff1cf48e to your computer and use it in GitHub Desktop.
Save optimalisatie/b35061f58d3fbcb5abf475c9ff1cf48e to your computer and use it in GitHub Desktop.
CoinGate Node.js Library
/**
* A simple CoinGate Node.js class based on
* @link https://github.com/coingate/coingate-php
*/
var VERSION = '3.0.1';
var LIVE_ENDPOINT = 'https://api.coingate.com/v2';
var SANDBOX_ENDPOINT = 'https://api-sandbox.coingate.com/v2';
var AUTH_TOKEN = '';
var ENVIRONMENT = 'live';
var USER_AGENT = 'CoinGate Node.js Library' + ' v' + VERSION;
// request library
const request = require('request');
// order class
class Order {
constructor(order) {
this.order = order;
}
get hash() {
return this.order;
}
get(key) {
return this.order[key];
}
}
// coingate class
class CoinGate {
constructor() {
this.auth_token = AUTH_TOKEN;
this.environment = ENVIRONMENT;
this.user_agent = USER_AGENT; // default
}
set config(authentication) {
var that = this;
['auth_token', 'environment', 'user_agent'].forEach(function(key) {
if (key in authentication && authentication[key]) {
if (typeof authentication[key] !== 'string') {
throw new APIError(key + ' not string');
}
that[key] = authentication[key];
}
});
}
testConnection(authentication) {
return this.request('/auth/test', 'GET', {}, authentication);
}
request(url, method = 'POST', params = {}, authentication = []) {
const auth_token = ("auth_token" in authentication && authentication["auth_token"]) ? authentication['auth_token'] : this.auth_token;
const environment = ("environment" in authentication && authentication["environment"]) ? authentication['environment'] : this.environment;
const user_agent = ("user_agent" in authentication && authentication["user_agent"]) ? authentication['user_agent'] : this.user_agent;
return new Promise(function(resolve, reject) {
// verify auth token
if (auth_token === '') {
throw new BadRequest();
}
// verify environment
if (['live', 'sandbox'].indexOf(environment) === -1) {
throw new BadEnvironment();
}
var requestOptions = {
url: (environment === 'sandbox' ? SANDBOX_ENDPOINT : LIVE_ENDPOINT) + url
};
requestOptions.headers = {};
requestOptions.headers['Authorization'] = 'Token ' + auth_token;
if (method.toUpperCase() === 'POST') {
requestOptions.method = 'POST';
requestOptions.form = params;
}
request(requestOptions, function(err, response, body) {
if (err) {
throw new InternalServerError(error);
} else if (response.statusCode === 401) {
switch (body) {
case 'BadCredentials':
throw new BadCredentials();
break;
case 'BadAuthToken':
throw new BadAuthToken();
break;
case 'AccountBlocked':
throw new AccountBlocked();
break;
case 'IpAddressIsNotAllowed':
throw new IpAddressIsNotAllowed();
break;
default:
throw new Unauthorized(body);
break;
}
} else if (response.statusCode === 429) {
throw new RateLimitException(body);
} else if (response.statusCode === 500 || response.statusCode === 504) {
throw new InternalServerError(body);
} else if (response.statusCode !== 200) {
throw new APIError(body);
} else {
if (body.toUpperCase() === 'OK') {
resolve();
} else {
try {
var resp = JSON.parse(body);
} catch (e) {
return resolve(body);
}
resolve(resp);
}
}
});
});
}
findOrder(orderId, options = {}, authentication = {}) {
var that = this;
return new Promise(function(resolve, reject) {
that.request('/orders/' + orderId, 'GET', {}, authentication).then(function(order) {
resolve(new Order(order));
}).catch(reject);
});
}
createOrder(params, options = {}, authentication = {}) {
var that = this;
// required
['order_id', 'price_amount', 'price_currency', 'receive_currency'].forEach(function(key) {
if (!(key in params)) {
throw new BadRequest(key + ' is required');
}
});
return new Promise(function(resolve, reject) {
that.request('/orders', 'POST', params, authentication).then(function(order) {
if (typeof order === 'object' && order.id && order.status) {
resolve(new Order(order));
} else {
throw new OrderIsNotValid(JSON.stringify(order));
}
}).catch(reject);
});
}
}
exports.CoinGate = new CoinGate();
// error handlers
class APIError extends Error {};
// HTTP Status 400
class BadRequest extends APIError {};
class CredentialsMissing extends BadRequest {};
class BadEnvironment extends BadRequest {};
// HTTP Status 401
class Unauthorized extends APIError {};
class BadCredentials extends Unauthorized {};
class BadAuthToken extends Unauthorized {};
class AccountBlocked extends Unauthorized {};
class IpAddressIsNotAllowed extends Unauthorized {};
// HTTP Status 404
class NotFound extends APIError {};
class PageNotFound extends NotFound {};
class RecordNotFound extends NotFound {};
class OrderNotFound extends NotFound {};
// HTTP Status 422
class UnprocessableEntity extends APIError {};
class OrderIsNotValid extends UnprocessableEntity {};
// HTTP Status 429
class RateLimitException extends APIError {};
// HTTP Status 500, 504
class InternalServerError extends APIError {};
@optimalisatie
Copy link
Author

optimalisatie commented Nov 11, 2018

Usage

const CoinGate = require('./coingate/index.js').CoinGate;

// set config
CoinGate.config = {
  auth_token: '',
  environment: 'sandbox'
};

// test connection
CoinGate.testConnection().then(function() {
    console.log('OK');
}).catch(console.error);

// create order
CoinGate.createOrder({
    order_id: 'ordertest',
    price_amount: 15,
    price_currency: 'USD',
    receive_currency: 'USD',
    title: 'Test order',
    description: 'Test order description.',
    cancel_url: 'https://domain.com/cancelled',
    success_url: 'https://domain.com/success',
    token: 'test123'
}).then(function(order) {
    console.log('order created', order);
}).catch(console.error);

// find order
CoinGate.findOrder(1).then(function(order) {
    console.log(order);
}).catch(console.error);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment