Skip to content

Instantly share code, notes, and snippets.

@thatmarvin
Created June 30, 2012 13:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thatmarvin/3023815 to your computer and use it in GitHub Desktop.
Save thatmarvin/3023815 to your computer and use it in GitHub Desktop.
Gnarly Node.js Balanced Payments client
/*
Usage:
// In app.js
var balanced = require('./this-file.js');
balanced.configure({
secret: '...',
marketplaceUri: '...'
});
// In response middleware
var balanced = require('./this-file.js');
balanced.get(..., callback);
balanced.post(..., callback);
*/
require('sugar');
var request = require('request');
var winston = require('winston');
var u = require('url');
var config = {
secret: null,
marketplaceUri: null
};
function client(method, uri, json, callback) {
if (!config.secret || !config.marketplaceUri) {
throw new Error('Missing required API secret or marketplaceUri');
}
var url = u.format({
protocol: 'https',
host: 'api.balancedpayments.com',
auth: config.secret + ':',
pathname: uri,
});
request({
method: method,
uri: url,
encoding: 'utf-8',
followRedirect: false,
json: json || true
}, function (err, response, body) {
if ((method === 'PUT' || method === 'POST') && !json) {
throw new Error('API call is missing "json" parameter');
}
if (response && response.statusCode >= 400) {
var msg = [
'Balanced call failed:',
method,
uri,
response.statusCode,
body.description
].join(' ');
winston.error(msg);
err = new Error('Balanced call failed: ' + body.description);
}
callback(err, response, body);
});
}
// marketplaceUri is really only for creating new accounts.
// Other REST uris should be available on the stored responses
module.exports = {
configure: function (theConfig) {
config = Object.merge(config, theConfig, true);
},
get: function (uri, callback) {
client('GET', uri, null, callback);
},
post: function (uri, json, callback) {
client('POST', uri, json, callback);
},
put: function (uri, json, callback) {
client('PUT', uri, json, callback);
},
delete: function (uri, callback) {
client('DELETE', uri, null, callback);
},
// This is for testing only
createCard: function (card, callback) {
client('POST', config.marketplaceUri + '/cards', card, callback);
},
createBankAccount: function (bankAccount, callback) {
client('POST', config.marketplaceUri + '/bank_accounts', bankAccount, callback);
},
createBuyer: function (email, cardUri, callback) {
client('POST', config.marketplaceUri + '/accounts', {
email_address: email,
card_uri: cardUri
}, callback);
},
createMerchant: function (email, merchant, bankAccountUri, name, callback) {
client('POST', config.marketplaceUri + '/accounts', {
email_address: email,
merchant: merchant,
bank_account_uri: bankAccountUri,
name: name
}, callback);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment