Giter Site home page Giter Site logo

chartmogul-node's Introduction

Official ChartMogul API Node.js Client

chartmogul-node provides convenient Node.js bindings for ChartMogul's API.

npm Package


Installation | Configuration | Usage | Development | Contributing | License



Installation

This library requires node.js 16.x or above.

npm install --save chartmogul-node

Configuration

First create a Config object by passing your api key, available from the administration section of your ChartMogul account.

const ChartMogul = require('chartmogul-node');
const config = new ChartMogul.Config(process.env.CHARTMOGUL_API_KEY);

You need to pass this config object as the first argument to each request.

Test your authentication

ChartMogul.Ping.ping(config)
  .then(res => console.log(res))
  .catch(err => console.error(err))

Usage

The library can be used both with promise and callback patterns. Supply the callback function as the last argmunent.

Here are sample examples:

Using as promise

const ChartMogul = require('chartmogul-node');

const config = new ChartMogul.Config('apiKey');

ChartMogul.Customer.create(config, {
  data_source_uuid: 'ds_e243129a-12c0-4e29-8f54-07da7905fbd1',
  external_id: 'cus_0001',
  name: 'Adam Smith',
  email: '[email protected]',
  country: 'US',
  city: 'New York'
})
.then(res => {
  console.log(res);
})
.catch(e => console.error(e.message, e.httpStatus, e.response));

Using with a callback

const ChartMogul = require('chartmogul-node');

const config = new ChartMogul.Config('apiKey');

ChartMogul.Customer.create(config, data, (err, res) => {
  if(err) {
    console.error(err.message, err.httpStatus, err.response)
  }
  console.log(res);
});

Import API

Available methods in Import API:

ChartMogul.DataSource.create(config, data)
ChartMogul.DataSource.retrieve(config, dataSourceUuid)
ChartMogul.DataSource.all(config, query)
ChartMogul.DataSource.destroy(config, dataSourceUuid)
ChartMogul.Customer.create(config, data)
ChartMogul.Customer.retrieve(config, customerUuid)
ChartMogul.Customer.all(config, { per_page: 20 })
ChartMogul.Customer.modify(config, customerUuid, data)
ChartMogul.Customer.destroy(config, customerUuid)
ChartMogul.Customer.merge(config, {
  'from': {'customer_uuid': 'cus_5915ee5a-babd-406b-b8ce-d207133fb4cb'},
  'into': {'customer_uuid': 'cus_2123290f-09c8-4628-a205-db5596bd58f7'}
})

ChartMogul.Customer.contacts(config, customerUuid, { per_page: 10, cursor: 'cursor==' })
ChartMogul.Customer.createContact(config, customerUuid, data)

ChartMogul.Customer.notes(config, customerUuid, { per_page: 10, cursor: 'cursor==' })
ChartMogul.Customer.createNote(config, customerUuid, data)

ChartMogul.Customer.opportunities(config, customerUuid, { per_page: 10, cursor: 'cursor==' })
ChartMogul.Customer.createOpportunity(config, customerUuid, data)
ChartMogul.Contact.create(config, data)
ChartMogul.Contact.retrieve(config, contactUuid)
ChartMogul.Contact.modify(config, contactUuid)
ChartMogul.Contact.destroy(config, contactUuid)
ChartMogul.Contact.merge(config, intoUuid, fromUuid);
ChartMogul.Contact.all(config, { per_page: 10, cursor: 'cursor==' })
ChartMogul.CustomerNote.create(config, data)
ChartMogul.CustomerNote.retrieve(config, noteUuid)
ChartMogul.CustomerNote.patch(config, noteUuid, data)
ChartMogul.CustomerNote.destroy(config, noteUuid)
ChartMogul.CustomerNote.all(config, { per_page: 10, cursor: 'cursor==', customer_uuid: customerUuid})
ChartMogul.Opportunity.create(config, data)
ChartMogul.Opportunity.retrieve(config, opportunityUuid)
ChartMogul.Opportunity.patch(config, opportunityUuid, data)
ChartMogul.Opportunity.destroy(config, opportunityUuid)
ChartMogul.Opportunity.all(config, { per_page: 10, cursor: 'cursor==', customer_uuid: customerUuid})
ChartMogul.Plan.create(config, data)
ChartMogul.Plan.retrieve(config, uuid)
ChartMogul.Plan.modify(config, uuid, { name: 'new name' })
ChartMogul.Plan.destroy(config, uuid)
ChartMogul.Plan.all(config, query)
ChartMogul.PlanGroup.create(config, data)
ChartMogul.PlanGroup.retrieve(config, planGroupUuid)
ChartMogul.PlanGroup.modify(config, planGroupUuid, data)
ChartMogul.PlanGroup.destroy(config, planGroupUuid)
ChartMogul.PlanGroup.all(config, query)
ChartMogul.PlanGroup.all(config, planGroupUuid, query)
ChartMogul.Subscription.all(config, customerUuid, query)
ChartMogul.Subscription.cancel(config, subscriptionUuid, { cancelled_at: '' })
ChartMogul.Subscription.modify(config, subscriptionUuid, { cancellation_dates: [] })
ChartMogul.Invoice.create(config, customerUuid, data)
ChartMogul.Invoice.retrieve(config, invoiceUuid)
ChartMogul.Invoice.destroy(config, invoiceUuid)
ChartMogul.Invoice.all(config, customerUuid, query)
ChartMogul.Invoice.all(config, query)
ChartMogul.Invoice.destroy_all(config, dataSourceUuid, customerUuid)
ChartMogul.Transaction.create(config, invoiceUuid, data)
ChartMogul.SubscriptionEvent.create(config, {
  subscription_event: {
    event_type: 'subscription_cancelled',
    event_date: '2022-06-13',
    effective_date: '2022-06-13',
    subscription_external_id: 'sub_ex_id_1',
    customer_external_id: 'cus_ex_id_1',
    data_source_uuid: '4175177b-3e4b-45b6-b6fb-426d6fd79028'
  }
})
ChartMogul.SubscriptionEvent.updateWithParams(config, {
  subscription_event: {
    id: 1,
    plan_external_id: 'gazillion_monthly'
  }
})
ChartMogul.SubscriptionEvent.deleteWithParams(config, {
  subscription_event: {
    id: 1
  }
})
ChartMogul.SubscriptionEvent.all(config, query)

Enrichment API

Available methods in Enrichment API:

ChartMogul.Customer.search(config, { email: '[email protected]' })
ChartMogul.Customer.attributes(config, customerUuid)
ChartMogul.Tag.add(config, customerUuid, {
  'tags': ['important', 'Prio1']
});
ChartMogul.Tag.add(config, {
  'email': '[email protected]',
  'tags': ['important', 'Prio1']
})'
ChartMogul.Tag.remove(config, customerUuid, {
  'tags': ['Prio1', 'discountable']
});
ChartMogul.CustomAttribute.add(config, customerUuid, {
  'custom': [
    { 'type': 'Integer', 'key': 'age', 'value': 8 }
  ]
});
ChartMogul.CustomAttribute.add(config, {
  'email': '[email protected]',
  'custom': [
    { 'type': 'Integer', 'key': 'age', 'value': 8 }
  ]
});
ChartMogul.CustomAttribute.update(config, customerUuid, {
  'custom': {
    'age': 20,
    'channel': 'Twitter'
  }
});
ChartMogul.CustomAttribute.remove(config, customerUuid, {
  'custom': ['CAC']
});

Available methods in Metrics API:

ChartMogul.Metrics.all(config, {
  'start-date': '2015-01-01',
  'end-date': '2015-11-24',
  'interval': 'month',
  'geo': 'GB',
  'plans': 'Bronze Plan'
})
ChartMogul.Metrics.mrr(config, query)
ChartMogul.Metrics.arr(config, query)
ChartMogul.Metrics.arpa(config, query)
ChartMogul.Metrics.asp(config, query)
ChartMogul.Metrics.customerCount(config, query)
ChartMogul.Metrics.customerChurnRate(config, query)
ChartMogul.Metrics.mrrChurnRate(config, query)
ChartMogul.Metrics.ltv(config, query)
ChartMogul.Metrics.Customer.activities(config, customerUuid, query)
ChartMogul.Metrics.Customer.subscriptions(config, customerUuid, query)
ChartMogul.Metrics.Activity.all(config, query)
ChartMogul.Metrics.ActivitiesExport.create(config, query)
ChartMogul.Metrics.ActivitiesExport.retrieve(config, id)

Account

Available methods:

ChartMogul.Account.retrieve(config)

Errors

The library throws following error objects.

  • ChartMogul.ChartMogulError
  • ChartMogul.ConfigurationError
  • ChartMogul.ForbiddenError
  • ChartMogul.NotFoundError
  • ChartMogul.ResourceInvalidError
  • ChartMogul.SchemaInvalidError
  • ChartMogul.DeprecatedParamError

The following table describes the properties of the error object.

Property Type Description
message string The error message
httpStatus number When the error occurs during an HTTP request, the HTTP status code.
response object or string HTTP response as JSON, or raw response if not parsable to JSON

Rate Limits & Exponential Backoff

The library will keep retrying if the request exceeds the rate limit or if there's any network related error. By default, the request will be retried for 20 times (approximated 15 minutes) before finally giving up.

You can change the retry count using Config object:

const ChartMogul = require('chartmogul-node');
const config = new ChartMogul.Config(process.env.CHARTMOGUL_API_KEY);
config.retries = 15; // 0 disables retrying

Development

To work on the library:

  • Fork it
  • Create your feature branch (git checkout -b my-new-feature)
  • Install dependencies: npm install
  • Fix bugs or add features. Make sure the changes pass the coding guidelines by runing: npm run lint
  • Write tests for your new features. For HTTP mocking nock library is used. Run tests with npm test and check test coverage with npm run cover
  • If all tests are passed, push to the branch (git push origin my-new-feature)
  • Create a new Pull Request

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/chartmogul/chartmogul-node.

Releasing

  1. You need an authorized account on npmjs.com
  2. Bump up the version in package.json & tag on GitHub
  3. npm test
  4. npm publish

Full Howto

License

The library is available as open source under the terms of the MIT License.

The MIT License (MIT)

Copyright (c) 2016 ChartMogul Ltd.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

chartmogul-node's People

Contributors

alpdal avatar bilbof avatar bogdanguranda avatar briwa avatar dependabot[bot] avatar dina920 avatar galadim1 avatar hassansin avatar jasonl avatar jwswj avatar kamilpavlicko avatar kmossco avatar kremalicious avatar mariabraganca avatar nickfranklin avatar pkopac avatar sbrych avatar soeunsona avatar srikalab avatar swember avatar velinarusjakova avatar whobubble avatar

Stargazers

 avatar  avatar  avatar  avatar  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

chartmogul-node's Issues

Search throws error for empty result

If you search email address, and no results are found, an error is thrown:

{ NotFoundError: The requested Resource could not be found. {"code":404,"message":"Can't find any customers with email: \"alex+11223@[domain].com\"","param":"email"}

That's pretty unexpected. Would expect to get back an empty search result since this isn't an error, it's just no result.

Pagination for Metrics.Customer.subscriptions

Hi, I’m writing a script to fetch subscriptions for a particular customer, and I’m using the method Metrics.Customer.subscriptions to do that.

It works well, except that I don’t know how to pass pagination parameters (per_page and page), since the method doesn’t seem to take an options object (unlike Customer.all). Is this a current limitation of the library? Is there a workaround for this? Cheers!

Importing invoice fails

If I attempt to import this invoice using the library, it fails, but, using curl it works fine.

code:

        canceled_at = sub.autorenewing == false ? sub.expiry_dt : null;

        lineItems = [{
          type: 'subscription',
          subscription_external_id: sub.order_id,
          plan_uuid: planMap[sub.order_sku],
          service_period_start: sub.order_dt.toString(),
          due_date: sub.order_dt.toString(),
          service_period_end: sub.expiry_dt ? sub.expiry_dt.toString() : null,
          //cancelled_at: canceled_at ? canceled_at.toString() : null,
          amount_in_cents: sub.amount_in_cents
        }];
        data = {
          external_id: sub.id,
          date: sub.order_dt ? sub.order_dt.toString() : null,
          currency: sub.currency_code,
          line_items: lineItems
        };
        console.log(data)
        ChartMogul.Import.Invoice.create(config, cust.uuid, data, (err, res) => {
          if (err)
            defer.reject(err);
          else
            defer.resolve(res);
        });

Console log of data:

{ external_id: 'Zr6AlcCIRQ6xR4gyZzeTFA',
  date: 'Sun Jul 26 2015 03:38:55 GMT-0700 (PDT)',
  currency: 'CAD',
  line_items:
   [ { type: 'subscription',
       subscription_external_id: 'GPA.1343-7803-4956-35795',
       plan_uuid: 'pl_196e2566-2346-4263-9599-f9e164e0f308',
       service_period_start: 'Sun Jul 26 2015 03:38:55 GMT-0700 (PDT)',
       due_date: 'Sun Jul 26 2015 03:38:55 GMT-0700 (PDT)',
       service_period_end: 'Mon Sep 12 2016 22:59:40 GMT-0700 (PDT)',
       amount_in_cents: 349 } ] }

Error:

{ SchemaInvalidError: JSON schema validation hasn't passed.
    at new SchemaInvalidError (/Users/alex/dev/is/web/node_modules/chartmogul-node/lib/chartmogul/errors/schema-invalid-error.js:7:11)
    at Request.request [as _callback] (/Users/alex/dev/is/web/node_modules/chartmogul-node/lib/chartmogul/resource.js:80:19)
    at Request.self.callback (/Users/alex/dev/is/web/node_modules/chartmogul-node/node_modules/request/request.js:187:22)
    at emitTwo (events.js:106:13)
    at Request.emit (events.js:191:7)
    at Request.<anonymous> (/Users/alex/dev/is/web/node_modules/chartmogul-node/node_modules/request/request.js:1044:10)
    at emitOne (events.js:96:13)
    at Request.emit (events.js:188:7)
    at IncomingMessage.<anonymous> (/Users/alex/dev/is/web/node_modules/chartmogul-node/node_modules/request/request.js:965:12)
    at emitNone (events.js:91:20)
    at IncomingMessage.emit (events.js:185:7)
    at endReadableNT (_stream_readable.js:975:12)
    at _combinedTickCallback (internal/process/next_tick.js:74:11)
    at process._tickCallback (internal/process/next_tick.js:98:9)
  name: 'SchemaInvalidError',
  response: { error: 'The property \'#/\' did not contain a required property of \'invoices\'' },
  httpStatus: 400 }

curl:

curl -i -X POST "https://api.chartmogul.com/v1/import/customers/cus_3e8226d6-d613-407b-a0bb-fd6e504eff97/invoices" \
     -u TOKEN:SECRET \
     -H "Content-Type: application/json" \
     -d '{
     "invoices":[
{ "external_id": "Zr6AlcCIRQ6xR4gyZzeTFA",
  "date": "Sun Jul 26 2015 03:38:55 GMT-0700 (PDT)",
  "currency": "CAD",
  "line_items":
   [ { "type": "subscription",
       "subscription_external_id": "GPA.1343-7803-4956-35795",
       "plan_uuid": "pl_196e2566-2346-4263-9599-f9e164e0f308",
       "service_period_start": "Sun Jul 26 2015 03:38:55 GMT-0700 (PDT)",
       "due_date": "Sun Jul 26 2015 03:38:55 GMT-0700 (PDT)",
       "service_period_end": "Mon Sep 12 2016 22:59:40 GMT-0700 (PDT)",
       "amount_in_cents": 349 } ] }
        ]
     }'

HTTP/1.1 201 Created
Server: nginx/1.9.10
Date: Sun, 14 Aug 2016 03:23:57 GMT
Content-Type: application/json; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff
ETag: W/"2f29292d7b287d93de52197e33d4e2ab"
Cache-Control: max-age=0, private, must-revalidate
X-Request-Id: eaf45e86-d9c7-48f5-a25e-94a38d3d9ae5
X-Runtime: 0.125522
Strict-Transport-Security: max-age=15768000

{"invoices":[{"uuid":"inv_99492f7f-f29d-4419-978d-3daedde77a11","external_id":"Zr6AlcCIRQ6xR4gyZzeTFA","date":"2015-07-26T10:38:55.000Z","due_date":null,"currency":"CAD","line_items":[{"uuid":"li_caa3a567-da86-46cc-a6f8-d5e044283aff","external_id":null,"type":"subscription","subscription_uuid":"sub_2f6f9937-6114-49f5-8190-6e8ee4b666cd","plan_uuid":"pl_196e2566-2346-4263-9599-f9e164e0f308","prorated":false,"service_period_start":"2015-07-26T10:38:55.000Z","service_period_end":"2016-09-13T05:59:40.000Z","amount_in_cents":349,"quantity":1,"discount_code":"","discount_amount_in_cents":0,"tax_amount_in_cents":0}],"transactions":[]}]}Alexs-MacBook-Pro:web alex$

Any chance of releasing 2.0.0?

Right now there is a mismatch between the readme and the API, as the readme is already updated with the new API Key config based while the latest version 1.9.0 works with the old token and secret.

Query string not passed after replacing `request` library with `superagent`

Issue Description:

We have encountered a significant issue after transitioning from the request library to superagent for HTTP requests. Specifically, when attempting to fetch all metrics from your endpoint, the start-date query parameter, crucial for this request, is not being passed along, leading to failed requests due to the API's requirement for this parameter.

Import API 422 error message not provided

When importing an invoice with type subscription but without a plan_uuid value, a 422 error is returned but without a useful error message such as 'plan_uuid is a required field'.

Reproduction steps:

  1. Import a customer into ChartMogul using the Import API and Node library
  2. Use the request below
  3. The following response will be provided: "Failed to created invoices <invoice_id> for customer (): The Invoice could not be created or updated. ResourceInvalidError 422".

Request:

ChartMogul.Import.Invoice.create(config,
   "cus_f466e33d-ff2b-4a11-8f85-417eb02157a7",
   {
     "invoices":[
       {
          "external_id": "INV0001",
          "date": "2015-11-01 00:00:00",
          "currency": "USD",
          "line_items": [
            {
              "type": "subscription",
              "subscription_external_id": "sub_0001",
              "service_period_start": "2015-11-01 00:00:00",
              "service_period_end": "2015-12-01 00:00:00",
              "amount_in_cents": 5000,
              "quantity": 1,
              "discount_code": "PSO86",
              "discount_amount_in_cents": 1000,
              "tax_amount_in_cents": 900
            }
          ]
       }
     ]
     },
   function (err, res) {
   // asynchronously called
});

SchemaInvalidError has a fake specificity

When making a call with an incorrectly specified type, eg:

await(ChartMogul.CustomAttribute.add(cmConfig, entry.uuid, {
    custom: [
           { type: 'String', value: '560dccca5963a44522dd76fd', key: 'shoelaceId' },
           { type: 'Date', value: '2015-10-02T00:16:10.000Z', key: 'phone' }
    ]
}));

A fairly specific error is throw:

{ SchemaInvalidError: JSON schema validation hasn't passed. {"code":400,"message":"Parameter \"custom[0][type]\" does not have a valid value","param":"custom[0][type]"}

This would appear to imply that the first entry is at fault when actually, the second error is the broken one here.

@types/chartmogul-node are outdated. Miss-match right of the bat `@types/chartmogul-node`

@types/chartmogul-node are outdated. Miss-match right of the bat @types/chartmogul-node

export class Config {
    VERSION: string;
    API_BASE: string;
    retries: number;

    constructor(token: string, secret: string, base?: string);
    getAccountToken(): string;
    getSecretKey(): string;
}

vs chartmogul-node

class Config {
  constructor (apiKey, apiBase) {
    this.apiKey = apiKey;
    this.apiBase = apiBase || API_BASE;
  }
[Nest] 87015  - 03/12/2022, 6:08:58 AM   ERROR [ExceptionsHandler] Invalid URI "abcd12312312312312apikey/v1/ping"
Error: Invalid URI "abcd12312312312312apikey/v1/ping"
    at Request.init (/Users/okhomenko/chartmogul-integration/node_modules/request/request.js:273:31)
    at new Request (/Users/okhomenko/chartmogul-integration/node_modules/request/request.js:127:8)
    at request (/Users/okhomenko/chartmogul-integration/node_modules/request/index.js:53:10)
    at RetryOperation._fn (/Users/okhomenko/chartmogul-integration/node_modules/chartmogul-node/lib/chartmogul/util/retry.js:46:5)
    at RetryOperation.attempt (/Users/okhomenko/chartmogul-integration/node_modules/retry/lib/retry_operation.js:112:8)
    at Object.retryRequest (/Users/okhomenko/chartmogul-integration/node_modules/chartmogul-node/lib/chartmogul/util/retry.js:45:13)
    at /Users/okhomenko/chartmogul-integration/node_modules/chartmogul-node/lib/chartmogul/resource.js:68:12
    at new Promise (<anonymous>)
    at Function.request (/Users/okhomenko/chartmogul-integration/node_modules/chartmogul-node/lib/chartmogul/resource.js:40:21)
    at Function.ping (/Users/okhomenko/chartmogul-integration/node_modules/chartmogul-node/lib/chartmogul/resource.js:145:19)

Originally posted by @okhomenko in #28 (comment)

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.