Giter VIP home page Giter VIP logo

recurly-js's Introduction

Recurly-js

npm Known Vulnerabilities

This is a fork of original node-recurly library by Rob Righter for the recurly recurring billing service.

This library is intended to follow very closely the recurly documentation found at: Recurly Docs

Installation

npm install recurly-js --save

Add a config file to your project that has contents similar to:

module.exports = {
  API_KEY: 'secret',
  SUBDOMAIN:    '[your_account]',
  ENVIRONMENT:  'sandbox',
  DEBUG: false,
  API_VERSION: 2.7 // optional
};

Usage

Using callbacks

var Recurly = require('recurly-js');
var recurly = new Recurly(require('./config'));
recurly.accounts.get('account_code_123', function (errResponse, response) {
})

Or a promises based version

var Recurly = require('recurly-js/promise');
var recurly = new Recurly(require('./config'));
recurly.accounts.get('account_code_123')
  .then(function (response) {})
  .catch(function (errorResponse) {})

For convenience the original callback version of every method is available with Callback suffix

var callback = function () {};

var filter = {
  state: 'active'
};

recurly.subscriptions.listByAccountCallback('account_code_123', callback, filter)

Accounts

http://docs.recurly.com/api/accounts

recurly.accounts.list(callback, filter)
recurly.accounts.create(details, callback)
recurly.accounts.update(accountcode, details, callback) 
recurly.accounts.get(accountcode, callback) 
recurly.accounts.close(accountcode, callback) 
recurly.accounts.reopen(accountcode, callback)
recurly.accounts.notes(accountcode, callback)

Billing Information

http://docs.recurly.com/api/billing-info

recurly.billingInfo.update(accountcode, details, callback) 
recurly.billingInfo.get(accountcode, callback) 
recurly.billingInfo.remove(accountcode, callback) 

Adjustments

http://docs.recurly.com/api/adjustments

recurly.adjustments.list(accountcode, callback)
recurly.adjustments.get(uuid, callback)
recurly.adjustments.create(accountcode, details, callback)
recurly.adjustments.remove(uuid, callback)

Coupons

http://docs.recurly.com/api/coupons

recurly.coupons.list(callback, filter)
recurly.coupons.get(couponcode, callback)
recurly.coupons.create(details, callback)
recurly.coupons.deactivate(couponcode, callback)

Coupon Redemption

http://docs.recurly.com/api/coupons/coupon-redemption

recurly.couponRedemption.redeem(couponcode, details, callback)
recurly.couponRedemption.get(accountcode, callback)
recurly.couponRedemption.remove(accountcode, callback)
recurly.couponRedemption.getByInvoice(invoicenumber, callback) // Deprecated
recurly.couponRedemption.getAllByInvoice(invoicenumber, callback)

Invoices

http://docs.recurly.com/api/invoices

recurly.invoices.list(callback, filter)
recurly.invoices.listByAccount(accountcode, callback, filter)
recurly.invoices.get(invoicenumber, callback)
recurly.invoices.create(accountcode, details, callback)
recurly.invoices.preview(accountcode, callback)
recurly.invoices.refundLineItems(invoicenumber, details, callback)
recurly.invoices.refundOpenAmount(invoicenumber, details, callback)
recurly.invoices.markSuccessful(invoicenumber, callback)
recurly.invoices.markFailed(invoicenumber, callback)
recurly.invoices.enterOfflinePayment(invoicenumber, details, callback)

Special pdf method - callback will contain a pdf document as Buffer You should send the buffer to the client with content type of application/pdf

recurly.invoices.retrievePdf(invoicenumber, details, callback)

Subscriptions

http://docs.recurly.com/api/subscriptions

recurly.subscriptions.list(callback, filter) 
recurly.subscriptions.listByAccount(accountcode, callback, filter) 
recurly.subscriptions.get(uuid, callback) 
recurly.subscriptions.create(details, callback) 
recurly.subscriptions.preview(details, callback) 
recurly.subscriptions.update(uuid, details, callback) 
recurly.subscriptions.updateNotes(uuid, details, callback)
recurly.subscriptions.updatePreview(uuid, details, callback)
recurly.subscriptions.cancel(uuid, callback) 
recurly.subscriptions.reactivate(uuid, callback) 
recurly.subscriptions.terminate(uuid, refundType, callback) 
recurly.subscriptions.postpone(uuid, nextRenewalDate, callback) 

Subscription Plans

http://docs.recurly.com/api/plans

recurly.plans.list(callback, filter) 
recurly.plans.get(plancode, callback) 
recurly.plans.create(details, callback)
recurly.plans.update(plancode, details, callback)
recurly.plans.remove(plancode, callback)

Plan Add-ons

http://docs.recurly.com/api/plans/add-ons

recurly.planAddons.list(plancode, callback, filter) 
recurly.planAddons.get(plancode, addoncode, callback) 
recurly.planAddons.create(plancode, details, callback)
recurly.planAddons.update(plancode, addoncode, details, callback)
recurly.planAddons.remove(plancode, addoncode, callback)

Purchases

https://dev.recurly.com/docs/create-purchase

recurly.purchases.create(details, callback)

The purchase endpoint requires API version v2.6. Creating multiple subscriptions requires API v2.8, and some extra feature flags enabled. Contact Recurly support for more details.

Transactions

http://docs.recurly.com/api/transactions

recurly.transactions.list(callback, filter) 
recurly.transactions.listByAccount(accountcode, callback, filter) 
recurly.transactions.get(id, callback) 
recurly.transactions.create(details, callback) 
recurly.transactions.refund(id, callback, amount) 

Usage Records

https://dev.recurly.com/docs/usage-record-object

recurly.usageRecords.list(subscription_uuid, add_on_code, callback, filter) 
recurly.usageRecords.lookup(subscription_uuid, add_on_code, usage_id, callback) 
recurly.usageRecords.log(subscription_uuid, add_on_code, details, callback) 
recurly.usageRecords.update(subscription_uuid, add_on_code, usage_id, details, callback) 
recurly.usageRecords.delete(subscription_uuid, add_on_code, usage_id, callback) 

Custom API calls

var options = {
  url: '/v2/accounts/' + account_code + '/invoices',
  method: 'POST',
  headers: {
    "My-Custom_header": "Value"
  },
  bodyRoot: 'invoice', // xml root element
  body: {} // content to convert to xml using js2xmlparser
};

recurly.api(options, callback)

Maintainers

Thodoris Greasidis
Thodoris Greasidis

Umayr Shahid
Umayr Shahid

recurly-js's People

Contributors

allenhartwig avatar blakmatrix avatar bluecollarcoder avatar breadbaker avatar cgerrior avatar cparjaszewski avatar elijahparker avatar everdance avatar ivanguardado avatar jaanttil avatar mrbar42 avatar pimterry avatar razor-x avatar robrighter avatar thgreasi avatar thisislawatts avatar thomas-hilaire avatar umayr avatar valorkin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

recurly-js's Issues

three_d_secure_action_result_token_mismatch

Whenever there is a 3-D secure action i keep getting three_d_secure_action_result_token_mismatch error code, this happens when i try to create subscription or an account that has three_d_secure_action_result_token_id, i am doing exactly like this example.

list accounts promise with a filter fails

The following fails

let Recurly = require('recurly-js/promise');
let config = ...
var recurly = new Recurly(config);
function list() {
    recurly.accounts.list({per_page: 5})
        .then((data) => {
            console.log(data);
        });
}
list();

error:
/client.js:100
throw new Error('Callback should be a function');

Subscription creation fails with non-latin characters

I'm not sure if I'm misusing the module or if this is a bug in module itself, but I recently noticed that calling recurly.subscriptions.create fails when JSON input has non-latin characters. For example calling subscription create with (Notice umlauts & and accents):

var testData = {
 	plan_code: 'testplan',
  	currency: 'USD',
  	quantity: 1,
  	account: {
     	account_code: '123456',
     	email: '[email protected]',
     	first_name: 'Verena',
     	last_name: 'Examplé Ö',
     	billing_info: {
     		number: '4111-1111-1111-1111' ,
     		month: 1,
     		year: 2020
     	}
	}
}

Failed with HTTP 400 error:

<?xml version="1.0" encoding="UTF-8"?>\n<bad-request>\n <error line="17" position="434">An error occurred parsing your XML request.</error>\n</bad-request>

Changing https://github.com/umayr/recurly-js/blob/master/lib/client.js#L25

'Content-Length': (data) ? data.length : 0,

to

'Content-Length': (data) ? Buffer.byteLength(data, 'utf8') : 0,

Fixed the issue for me.

Create Purchase: Element 'adjustments': This element is not expected."

Whenever I try to use the create purchase endpoint, I get the following error:

error: {
node-app_1 | symbol: 'invalid_xml',
node-app_1 | description: 'The provided XML was invalid.',
node-app_1 | details: "12:0: ERROR: Element 'adjustments': This element is not expected."
node-app_1 | }

My code is as follows:

const Recurly = require('recurly-js/promise');

const config = require('./config');

const recurly = new Recurly(config);

/*
  productsAndAmounts is an Array of Object
  schema: {
    productCode: String,
    quantity: Number,
    price: Number
  }
*/
module.exports = async (email, productsAndAmounts, currency = 'CAD') => {
  try {
    const adjustments = productsAndAmounts.map(i => {
      return {
        adjustment: {
          product_code: i.productCode,
          quantity: i.quantity,
          revenue_schedule_type: 'at_invoice',
          unit_amount_in_cents: i.price
        }
      };
    });
    return new Promise((resolve, reject) => {
      recurly.purchases.create(
        {
          account: {
            account_code: email
          },
          currency,
          adjustments
        },
        (err, data) => {
          if (err) {
            reject(err);
          } else {
            resolve(data);
          }
        }
      );
    });
  } catch (e) {
    throw new Error('Error during the purchase attempt');
  }
};

I do believe that either something is going on behind the scenes that I fail to understand or there is an issue with the library. Although, I don't completely drop the generic brainfart on my side explanation as well. Could someone please either confirm or debunk my suspicions? Thank you in advance.

Promise interface for API

recurly.api doesn't fit the Promise interface pattern of other calls - callback is currently required. Would be great to get this working per the other functions.

Converting response to simpler format

The response XML is converted to JSON which places child $ and _ to represent attributes and text nodes, I'm guessing. Also data types are represented by object with $.type and $._ as the value.

JSON supports types, so it's possible to convert to JSON types without having to represent it in serial text format.

I've put together a dirty solution:

const recurlyNormalize = data => {
  return Object.entries(data).reduce((curr, [key, value]) => {
    const type = typeof value
    // handle arrays
    if (value.$ && value.$.type === 'array') {
      const list = Object.values(value).find(value => Array.isArray(value)) || Object.values(value).pop()
      curr[key] = Array.isArray(list) ? list.map(item => recurlyNormalize(item)) : [recurlyNormalize(list)]
    // convert types
    } else if (value.$ && value.$.type && value._) {
      if (value.$.type === 'boolean') curr[key] = !!value._
      else if (value.$.type === 'integer') curr[key] = parseInt(value._, 10)
      else curr[key] = value._
    // special type nil has no value._
    } else if (value.$ && value.$.nil === 'nil') {
      curr[key] = null
    // handle objects with $
    } else if (key === '$') {
      curr = Object.assign(curr, recurlyNormalize(value))
    // recurse arrays
    } else if (Array.isArray(value)) {
      curr[key] = value.map(item => recurlyNormalize(item))
    // recurse objects
    } else if (!['string', 'boolean', 'number'].includes(type)) {
      curr[key] = recurlyNormalize(value)
    // basic types
    } else {
      curr[key] = (value)
    }
    return curr
  }, {})
}

If there is interest in using this approach I can refine it, add tests and submit a PR?

Missing `billing` functions

Seems to be missing all POST routes for billing, such as creating billing data based on a token or credit card.

Possibility to pass XML parser options

Hi,

Thanks for the great module! Would be nice to have possibility to pass Xml2js options somehow, currently coupon API for example returns JSON something like this:

coupon_code: 'testcode1',
name: 'TestCode1',
state: 'redeemable',
description: '',
discount_type: 'dollars',
discount_in_cents: { USD: { _: '3000', '$': { type: 'integer' } } },
invoice_description: '',
redeem_by_date: { '$': { nil: 'nil' } },
single_use: { _: 'false', '$': { type: 'boolean' } },
applies_for_months: { '$': { nil: 'nil' } },
max_redemptions: { '$': { nil: 'nil' } },
applies_to_all_plans: { _: 'false', '$': { type: 'boolean' } },
created_at: { _: '2016-10-25T11:44:32Z', '$': { type: 'datetime' } },
deleted_at: { '$': { nil: 'nil' } },
duration: 'forever',
temporal_unit: { '$': { nil: 'nil' } },
temporal_amount: { '$': { nil: 'nil' } },
applies_to_non_plan_charges: { _: 'false', '$': { type: 'boolean' } },
redemption_resource: 'account',
max_redemptions_per_account: { _: '1', '$': { type: 'integer' } },
coupon_type: 'single_code',
plan_codes: { '$': { type: 'array' }, plan_code: [ '1234', '5678' ] }

By changing Xml2js instantiation as follows:

var parser = new Xml2js.Parser({explicitArray: false, ignoreAttrs:true,  valueProcessors: [Xml2js.processors.parseNumbers, Xml2js.processors.parseBooleans]})

Module would provide data in a lot simpler format:

coupon_code: 'testcode1',
name: 'TestCode1',
state: 'redeemable',
description: '',
discount_type: 'dollars',
discount_in_cents: { USD: 3000 },
invoice_description: '',
redeem_by_date: '',
single_use: false,
applies_for_months: '',
max_redemptions: '',
applies_to_all_plans: false,
created_at: '2016-10-25T11:44:32Z',
deleted_at: '',
duration: 'forever',
temporal_unit: '',
temporal_amount: '',
applies_to_non_plan_charges: false,
redemption_resource: 'account',
max_redemptions_per_account: 1,
coupon_type: 'single_code',
plan_codes: { plan_code: [ 1234, 5678 ] },

getting all existing planAddons does not seem to work

I am trying to write some test in our code base to fix the way we do billing using recurly..started writing some tests and stumbled on the call to get all addons configured in recurly.

getting list of plans works fine.

Here is the code

const Recurly = require('recurly-js/promise');
const defaultConfig = {
API_KEY: process.env.API_KEY,
SUBDOMAIN: process.env.SUBDOMAIN,
ENVIRONMENT: 'SANDBOX',
DEBUG: true
};
const recurlyPromise = new Recurly(defaultConfig);

async function getRecurlyPlans() {
return recurlyPromise.plans.list();
}

async function getRecurlyPlanAddOns() {
return recurlyPromise.planAddons.list();
}

using recurly-js ^3.2.0 version
here is the log for getRecurlyPlanAddOns() call

{ host: 'wickr-qa.recurly.com',
port: 443,
path: '/v2/plans/function (err, value) {\n if (promise === null) return;\n if (err) {\n var wrapped = wrapAsOperationalError(maybeWrapAsError(err));\n promise._attachExtraTrace(wrapped);\n promise._reject(wrapped);\n } else if (!multiArgs) {\n promise._fulfill(value);\n } else {\n var $_len = arguments.length;var args = new Array(Math.max($_len - 1, 0)); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];};\n promise._fulfill(args);\n }\n promise = null;\n }/add_ons',
method: 'GET',
headers:
{ Authorization: 'Basic NzAxMTE2Yjg0MmE5NGM3Y2E2MDdlZGRkNDQyYzNjYWI=',
Accept: 'application/xml',
'Content-Length': 0,
'Content-Type': 'application/xml; charset=utf-8',
'User-Agent': 'umayr/recurly-node/3.2.0' } }

Replaced copy of cgerrior/node-recurly with umayr/recurly-js and received the following error on subscription update

Hi. We just replaced cgerrior/node-recurly with umayr/recurly-js and immediately received the following error when attempting to update a subscription.

Is this expected and/or is there a document detailing some problems to expect after migration?

names were changed below for security. I'm not sure how to decipher the additional information given in Hexidecimal below.

Error updating subscription for: aabbd927-0975-4bcd-8f7e-a435c615d799 { status: 'error',
  data: 400,
  headers: 
   { date: 'Thu, 16 Nov 2017 22:42:58 GMT',
     'content-type': 'application/xml; charset=utf-8',
     'transfer-encoding': 'chunked',
     connection: 'close',
     'set-cookie': [ '__cfduid=adabc23ce07513a0a0a4913540615c76f1517972172; expires=Fri, 16-Nov-18 22:42:58 GMT; path=/; domain=.recurly.com; HttpOnly' ],
     'cache-control': 'no-cache',
     'x-request-id': 'avorvtr28a66jb9vii10',
     'strict-transport-security': 'max-age=15552000; includeSubDomains; preload',
     server: 'nginx',
     'cf-ray': '3abcf7689c655408-LAQ' },
  additional: <Buffer 3c 3f 78 6d 6c 20 76 65 72 73 69 6f 6e 3d 22 31 2e 30 22 20 65 6e 63 6f 64 69 6e 67 3d 22 55 54 46 2d 38 22 3f 3e 0a 3c 65 72 72 6f 72 3e 0a 20 20 3c ... > }

More then 50 results in list subs by account

recurly.subscriptions.listByAccount(accountcode, callback) and other calls are limited to 50 results. recurly-js does not seem to support including the cursor in a request to get additional pages. Can this be accomplished through recurly-js? Alternatively, how can I make a raw request facilitated via recurly-js with a cursor/paged result?

Charset not added to POST/PUT headers

Is there a reason that the library does not add charset=utf-8 to the POST/PUT headers? As per Recurly documentation here, this is required. Not adding it results in rejection of fields that have special characters (such as someone's name being 'Richàrd').

I would like to push up a branch to fix this, if possible.

Thanks!

sort begin_time not working as expected

It's likely I'm calling something wrong, however, the following is returning only expired subscriptions as intended, but not only those updated between the date range specified. I'm having the same issue using created_at, any suggestions?

var filter = {
state: 'expired',
sort: 'updated_at',
order: 'desc',
begin_time: '2016-11-01',
end_time: '2016-11-03'
};
recurly.subscriptions.list(function(output){
return resolve(output);
}, filter);
});

Retrieve invoice PDF not working for me

I am trying to get a recurly invoice pdf.

routes.get('/invoices/:invoice_number', (req, res) => {
  const invoiceNumber = req.params.invoice_number
  recurly.invoices.exportPdf(invoiceNumber, (response) => {
    if(response.status === 'ok') {
      sendPdf(res, response.data)
    } else {
      res.send(response)
    }
  });
});
const sendPDF = (res, data) => {
  res.setHeader('Content-Type', 'application/pdf');
  res.send(data);
}

The recurly response looks like this...
screen shot 2017-01-29 at 2 22 41 pm

Client code looks like this...

 client.get('/invoices/' + this.props.invoiceNumb)
    .then(function(result) {
      const blob = result.blob()
      var blobUrl = URL.createObjectURL(blob);
      window.open(blobUrl);
    })
    .catch((err) => {
      console.log('invoice error:', err)
    })

I've tried adding encoding:null in the request headers and converting the recurly response to a base64 string and a few other things, but whenever the pdf opens in a new url I get "Failed to load PDF document". Any ideas what the problem is?

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.