Giter Site home page Giter Site logo

button-client-node's Introduction

button-client-node Build Status

This module is a thin client for interacting with Button's API.

Please see the full API Docs for more information. For help, check out our Support page or get in touch.

Supported runtimes

  • Node 0.10, 0.11, 0.12, 4, 5, 6

Dependencies

  • None

Usage

npm install @button/button-client-node

To create a client capable of making network requests, invoke button-client-node with your API key.

var client = require('@button/button-client-node')('sk-XXX');

You can optionally supply a config argument with your API key:

var Q = require('q');

var client = require('@button/button-client-node')('sk-XXX', {
  timeout: 3000, // network requests will time out at 3 seconds
  promise: function(resolver) { return Q.Promise(resolver); }
});
Config
  • timeout: The time in ms for network requests to abort. Defaults to false.
  • promise: A function which accepts a resolver function and returns a promise. Used to integrate with the promise library of your choice (i.e. es6 Promises, Bluebird, Q, etc). If promise is supplied and is a function, all API functions will ignore any passed callbacks and instead return a promise.
  • hostname: Defaults to api.usebutton.com
  • port: Defaults to 443 if config.secure, else defaults to 80.
  • secure: Whether or not to use HTTPS. Defaults to true. N.B: Button's API is only exposed through HTTPS. This option is provided purely as a convenience for testing and development.

Node-style Callbacks

button-client-node supports standard node-style callbacks. To make a standard call, supply a callback function as the last argument to any API function and omit promise from your config.

var client = require('@button/button-client-node')('sk-XXX');

client.orders.get('btnorder-XXX', function(err, res) {
  // ...
});

All callbacks will be invoked with two arguments. err will be an Error object if an error occurred and null otherwise. res will be the API response if the request succeeded or null otherwise.

If an Error is returned after the client receives a response, such as for an upstream HTTP error, the Error.response property will be set to the NodeJS response object.

Promise

button-client-node supports a promise interface. To make a promise-based request, supply a function that accepts a single resolver function and returns a new promise on the promise key of your config. Additionally, you must omit the callback from your API function call.

var Promise = require('bluebird');
var client = require('@button/button-client-node')('sk-XXX', {
  promise: function(resolver) { return new Promise(resolver); }
});

client.orders.get('btnorder-XXX').then(function(result)  {
  // ...
}, function(reason) {
  // ...
});

A resolver function has the signature function(resolve, reject) { ... } and is supported by many promise implementations:

If your promise library of choice doesn't support such a function, you can always roll your own as long as your library supports resolving and rejecting a promise you create:

promiseCreator(resolver) {
  var promise = SpecialPromise();

  resolver(function(result) {
    promise.resolve(result);
  }, function(reason) {
    promise.reject(reason);
  });

  return promise;
}

The returned promise will either reject with an Error or resolve with the API response object.

Responses

All responses will assume the following shape:

{
  data,
  meta: {
    next,
    previous
  }
}

The data key will contain any resource data received from the API and the meta key will contain high-order information pertaining to the request.

meta
  • next: For any paged resource, next will be a cursor to supply for the next page of results.
  • previous: For any paged resource, previous will be a cursor to supply for the previous page of results.

Resources

We currently expose the following resources to manage:

Accounts

All
var client = require('@button/button-client-node')('sk-XXX');

client.accounts.all(function(err, res) {
    // ...
});
Transactions

Transactions are a paged resource. The response object will contain properties meta.next and meta.previous which can be supplied to subsequent invocations of #transactions to fetch additional results.

#transactions accepts an optional second parameter, options which may define the follow keys to narrow results:

options
  • cursor: An API cursor to fetch a specific set of results
  • start: An ISO-8601 datetime string to filter only transactions after start
  • end: An ISO-8601 datetime string to filter only transactions before end
var client = require('@button/button-client-node')('sk-XXX');

// without options argument
//
client.accounts.transactions('acc-1', function(err, res) {
    // ...
});

// with options argument
//
client.accounts.transactions('acc-1', {
  cursor: 'cXw',
  start: '2015-01-01T00:00:00Z',
  end: '2016-01-01T00:00:00Z'
}, function(err, res) {
    // ...
});

Merchants

All
options
  • status: Partnership status to filter by. One of ('approved', 'pending', or 'available')
  • currency: ISO-4217 currency code to filter returned rates by
var client = require('@button/button-client-node')('sk-XXX');

// without options argument
//
client.merchants.all(function(err, res) {
    // ...
});

// with options argument
//
client.merchants.all({
  status: 'pending',
  currency: 'USD'
}, function(err, res) {
    // ...
});

Orders

Create
var crypto = require('crypto');
var client = require('@button/button-client-node')('sk-XXX');

var hashedEmail = crypto.createHash('sha256')
  .update('[email protected]'.toLowerCase().trim())
  .digest('hex');

client.orders.create({
  total: 50,
  currency: 'USD',
  order_id: '1989',
  purchase_date: '2017-07-25T08:23:52Z',
  finalization_date: '2017-08-02T19:26:08Z',
  btn_ref: 'srctok-XXX',
  customer: {
    id: 'mycustomer-1234',
    email_sha256: hashedEmail
  }
}, function(err, res) {
    // ...
});
Get
var client = require('@button/button-client-node')('sk-XXX');

client.orders.get('btnorder-XXX', function(err, res) {
  // ...
});
Get by Button Ref
var client = require('@button/button-client-node')('sk-XXX');

client.orders.getByBtnRef('srctok-XXX', function (err, res) {
  // ...
});
Update
var client = require('@button/button-client-node')('sk-XXX');

client.orders.update('btnorder-XXX', { total: 60 }, function(err, res) {
  // ...
});
Delete
var client = require('@button/button-client-node')('sk-XXX');

client.orders.del('btnorder-XXX', function(err, res) {
  // ...
});

Customers

Create
var crypto = require('crypto');
var client = require('@button/button-client-node')('sk-XXX');

var hashedEmail = crypto.createHash('sha256')
  .update('[email protected]'.toLowerCase().trim())
  .digest('hex');

client.customers.create({
  id: 'customer-1234',
  email_sha256: hashedEmail
}, function(err, res) {
  // ...
});
Get
var client = require('@button/button-client-node')('sk-XXX');

client.customers.get('customer-1234', function(err, res) {
  // ...
});

Links

Create
client.links.create({
  url: "https://www.jet.com",
  experience: {
    btn_pub_ref: "my-pub-ref",
    btn_pub_user: "user-id"
  }
}, function(err, res) {
  // ...
});
Get Info
client.links.getInfo({
  url: "https://www.jet.com"
}, function(err, res) {
  // ...
});

Utils

Utils houses generic helpers useful in a Button Integration.

#isWebhookAuthentic

Used to verify that requests sent to a webhook endpoint are from Button and that their payload can be trusted. Returns true if a webhook request body matches the sent signature and false otherwise. See Webhook Security for more details.

Example usage with body-parser

var express = require('express');
var bodyParser = require('body-parser');
var utils = require('@button/button-client-node').utils

var app = express();

function verify(req, res, buf, encoding) {
  var isAuthentic = utils.isWebhookAuthentic(
    process.env['WEBHOOK_SECRET'],
    buf,
    req.headers['X-Button-Signature']
  );

  if (!isAuthentic) {
    throw new Error('Invalid Webhook Signature');
  }
}

app.use(bodyParser.json({ verify: verify, type: 'application/json' }));

Contributing

  • Installing development dependencies: npm install
  • Running tests: npm test
  • Running lint: npm run lint

button-client-node's People

Contributors

mightyguava avatar mikeybtn avatar tylernappy avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.