Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

chargebee-typescript

Package Overview
Dependencies
Maintainers
1
Versions
59
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

chargebee-typescript - npm Package Compare versions

Comparing version 2.20.0 to 2.20.1

2

lib/environment.js

@@ -6,3 +6,3 @@ let environment = {

timeout: 80000,
clientVersion: 'v2.20.0',
clientVersion: 'v2.20.1',
port: 443,

@@ -9,0 +9,0 @@ timemachineWaitInMillis: 3000,

{
"name": "chargebee-typescript",
"version": "2.20.0",
"version": "2.20.1",
"description": "A library in typescript for integrating with Chargebee.",

@@ -5,0 +5,0 @@ "keywords": [

# Chargebee Typescript Client Library - API V2
[![npm](https://img.shields.io/npm/v/chargebee-typescript.svg?maxAge=2592000)](https://www.npmjs.com/package/chargebee-typescript)
[![npm](https://img.shields.io/npm/dt/chargebee-typescript.svg?maxAge=2592000)](https://www.npmjs.com/package/chargebee-typescript)
[![npm](https://img.shields.io/npm/v/chargebee-typescript.svg?maxAge=25920000)](https://www.npmjs.com/package/chargebee-typescript)
[![npm](https://img.shields.io/npm/dt/chargebee-typescript.svg?maxAge=25920000)](https://www.npmjs.com/package/chargebee-typescript)
This is the [typescript](https://www.typescriptlang.org/) Library for integrating with Chargebee. Sign up for a Chargebee account [here](https://www.chargebee.com).
This is a server-side [typescript](https://www.typescriptlang.org/) library for integrating with Chargebee. Sign up for a Chargebee account [here](https://www.chargebee.com).
## Installation
## Requirements
Install the latest version 2.x.x of the library with the following commands:
Node 8 or higher.
$ npm install chargebee-typescript@">=2"
## Installation
Then import the library as:
Install the latest version of the library with:
import {ChargeBee} from 'chargebee-typescript';
var chargebee = new ChargeBee();
```sh
npm install chargebee-typescript
# or
yarn add chargebee-typescript
# or
pnpm install chargebee-typescript
```
## Usage
### Before getting started
This library lazily requests data only upon trying to access it. This means that if you are trying to get back a list of subscriptions for a customer, you need to access the parent of every field you want.
The package needs to be configured with your site's API key, which is available under Configure Chargebee Section. Refer [here](https://www.chargebee.com/docs/2.0/api_keys.html) for more details.
```typescript
chargebee.subscription.list({/* params */})
.request(function(error,result) {
if(error){
//handle error
console.log(error);
}else{
// An empty Result object
console.log(result)
// A list of empty Result objects
console.log(result.list)
// A list of Subscription objects
console.log(result.list.map((obj) => obj.subscription))
}
import { ChargeBee } from 'chargebee-typescript';
const chargebee = new ChargeBee();
chargebee.configure({
site: 'YOUR_SITE_NAME',
api_key: 'YOUR_API_KEY',
});
```
### Using Async / Await
```typescript
try {
const { customer } = await chargebee.customer
.create({
email: 'john@test.com',
// other params
})
.request();
} catch (err) {
// handle error
}
```
### Using Promises
```typescript
chargebee.customer
.create({
email: 'john@test.com',
// other params
})
.request()
.then((result) => {
// handle result
// access customer as result.customer;
})
.catch((err) => {
// handle error
});
```
If you have a `result` (or children further down the line) and are unsure what properties are available, you can use `Object.keys` to get a list of available accessor properties. Using `Object.keys` in the previous example would yield
### Using callbacks
```typescript
// ['list', 'next_offset']
console.log(Object.keys(result))
// ['1', '2', '3'], e.g. `result.list` is an array with 3 entries
console.log(Object.keys(result.list))
// ['activated_at', 'base_currency_code', ...]
// ['activated_at', 'base_currency_code', ...]
// ['activated_at', 'base_currency_code', ...]
// Which means we've reached the bottom and should have all the information available from this request
console.log(result.list.map((obj) => obj.subscription))
chargebee.customer
.create({
email: 'john@test.com',
// other params
})
.request(function (error, result) {
if (error) {
// handle error
} else {
// handle result
}
});
```
### To create a customer & subscription
### Using typings
```typescript
import {
ChargeBee,
_subscription
} from 'chargebee-typescript';
import { ChargeBee, _customer } from 'chargebee-typescript';
const chargebee = new ChargeBee();
var chargebee = new ChargeBee();
chargebee.configure({
site: 'YOUR_SITE_NAME',
api_key: 'YOUR_API_KEY',
});
chargebee.configure({site : "{site}", api_key : "{site_api_key}"});
chargebee.subscription.create({
plan_id : "basic",
auto_collection : "off",
billing_address : {
first_name : "John",
last_name : "Doe",
line1 : "PO Box 9999",
city : "Walnut",
state : "California",
zip : "91789",
country : "US"
},
customer : {
first_name : "John",
last_name : "Doe",
email : "john@user.com"
}
}).request(function(error,result) {
if(error){
//handle error
console.log(error);
}else{
console.log(`${result}`);
var subscription: typeof chargebee.subscription = result.subscription;
var customer: typeof chargebee.customer = result.customer;
var card: typeof chargebee.card = result.card;
var invoice: typeof chargebee.invoice = result.invoice;
var unbilled_charges: Array<typeof chargebee.unbilled_charge> = result.unbilled_charges;
}
});
const createCustomer = async () => {
const params: _customer.create_params = {
email: 'john@test.com',
first_name: 'John',
last_name: 'Doe',
};
const { customer } = await chargebee.customer.create(params).request();
console.log(customer);
};
createCustomer();
```
### Use of Filters In List API
### Accessing the response object
The response object returned by the `request()` method is generic response wrapper. You need to access the resource from it. For example,
- To access customer object.
```typescript
import {
ChargeBee,
_subscription
} from 'chargebee-typescript';
const result = await chargebee.customer.create({ email: 'john@test.com' }).request();
console.log(result.customer);
```
var chargebee = new ChargeBee();
Other resources can be accessed by the same approach. For subscription, it will be `result.subscription`
chargebee.configure({site : "{site}", api_key : "{site_api_key}"});
chargebee.subscription.list({
limit : 2,
plan_id : { in : ["basic","no-trial"] }
}).request(function(error,result) {
if(error){
//handle error
console.log(error);
}else{
for(var i = 0; i < result.list.length;i++){
var entry=result.list[i]
console.log(`${entry}`);
var subscription: typeof chargebee.subscription = entry.subscription;
var customer: typeof chargebee.customer = entry.customer;
var card: typeof chargebee.card = entry.card;
/*
For pagination: offset is the paramter that is being used.
The value used for this parameter must be the value returned for next_offset parameter in the previous API call.
usage: result.next_offset
*/
}
}
});
- To access list response.
```typescript
const result = await chargebee.subscription
.list({
/* params */
})
.request();
// A list of Subscription objects
console.log(result.list.map((obj) => obj.subscription));
```
### To create subscription with custom headers and custom fields:
**Note**
If you have a `result` (or children further down the line) and are unsure what properties are available, you can use `Object.keys` to get a list of available accessor properties. Using `Object.keys` in the previous example would yield
```typescript
import {
ChargeBee,
_subscription
} from 'chargebee-typescript';
// ['list', 'next_offset']
console.log(Object.keys(result));
// ['1', '2', '3'], e.g. `result.list` is an array with 3 entries
console.log(Object.keys(result.list));
// ['activated_at', 'base_currency_code', ...]
// ['activated_at', 'base_currency_code', ...]
// ['activated_at', 'base_currency_code', ...]
// Which means we've reached the bottom and should have all the information available from this request
console.log(result.list.map((obj) => obj.subscription));
```
var chargebee = new ChargeBee();
#### Using filters in the List API
chargebee.subscription.create({
plan_id : "basic"
}).param({
"cf_host_url" : "http://xyz.com",
"customer[cf_host_url]" : "http://xyz.com"
}).headers({
"chargebee-event-email" : "all-disabled", // To disable webhooks
"chargebee-request-origin-ip": "192.168.1.2"
}).request(function(error,result) {
if(error){
console.log(error);
}else{
var subscription = result.subscription
var customer = result.customer
console.log(subscription.cf_host_url);
console.log(customer.cf_host_url);
}
});
For pagination: `offset` is the parameter that is being used. The value used for this parameter must be the value returned for `next_offset` parameter in the previous API call.
```typescript
const fetchCustomers = async (offset?: any) => {
const params: _customer.customer_list_params = {
offset,
limit: 2,
first_name: {
is: 'John',
},
};
const result = await chargebee.customer.list(params).request();
return {
customers: result.list.map((obj) => obj.customer),
next_offset: result.next_offset,
};
};
const { customers, next_offset } = fetchCustomers();
// Fetching next set of customers
fetchCustomers(next_offset);
```
### Create an idempotent request
#### Using custom headers and custom fields:
[Idempotency keys](https://apidocs.chargebee.com/docs/api) are passed along with request headers to allow a safe retry of POST requests.
```typescript
chargebee.customer
.create({ email: 'john@test.com' })
.param({
cf_host_url: 'http://xyz.com',
})
.headers({
'chargebee-event-email': 'all-disabled', // To disable webhooks
'chargebee-request-origin-ip': '192.168.1.2',
})
.request()
.then((result) => {
const customer = result.customer;
console.log(customer.cf_host_url);
});
```
#### Create an idempotent request
[Idempotency keys](https://apidocs.chargebee.com/docs/api/idempotency?prod_cat_ver=2) are passed along with request headers to allow a safe retry of POST requests.
```typescript
import {
ChargeBee,
_customer
} from 'chargebee-typescript';
var chargebee = new ChargeBee();
chargebee.configure({site : "{site}", api_key : "{site_api_key}"});
chargebee.customer.create({
first_name : "John",
last_name : "Doe",
email : "john@test.com",
locale : "fr-CA",
billing_address : {
first_name : "Jsohn",
last_name : "Doe",
line1 : "PO Box 9999",
city : "Walnut",
state : "Califorsnia",
zip : "91789",
country : "US"
}
import { ChargeBee } from 'chargebee-typescript';
chargebee.customer
.create({
email: 'john@test.com',
})
.setIdempotencyKey("<<UUID>>") // Replace <<UUID>> with a unique string
.request(function(error,result) {
if(error){
//handle error
console.log(error);
}else{
var customer: typeof chargebee.customer = result.customer;
var card: typeof chargebee.card = result.card;
const responseHeaders = result.getResponseHeaders(); // Retrieves response headers
console.log(responseHeaders);
const idempotencyReplayedValue = result.isIdempotencyReplayed(); // Retrieves idempotency replayed header value
console.log(idempotencyReplayedValue);
}
.setIdempotencyKey('<<UUID>>') // Replace <<UUID>> with a unique string
.request()
.then((result) => {
const customer: typeof chargebee.customer = result.customer;
const responseHeaders = result.getResponseHeaders(); // Retrieves response headers
console.log(responseHeaders);
const idempotencyReplayedValue = result.isIdempotencyReplayed(); // Retrieves idempotency replayed header value
console.log(idempotencyReplayedValue);
});
```
`isIdempotencyReplayed()` method can be accessed to differentiate between original and replayed requests.
Note: `isIdempotencyReplayed()` method can be accessed to differentiate between original and replayed requests.
### Error handling:
```typescript
import {
ChargeBee,
_subscription
} from 'chargebee-typescript';
var chargebee = new ChargeBee();
All asynchronous errors will be available as the first argument of `request()` method's callback or in the form of a rejected promise. Detailed documentation on error handling is available [here](https://apidocs.chargebee.com/docs/api/error-handling?prod_cat_ver=2).
```typescript
//The callback function that you provide needs to take in two arguments. The first being error object and the
//second being the response. Incase of error, the error object is passed.
chargebee.subscription.create({
//create params...
}).request(function(error, result) {
if (error) {
handleCreateSubscriptionError(error);
} else {
console.log(result);
}
});
chargebee.subscription
.create({
//create params...
})
.request(function (error, result) {
if (error) {
handleCreateSubscriptionError(error);
} else {
console.log(result.subscription);
}
});
function handleCreateSubscriptionError(ex) {
if (ex.type == "payment") {
if (ex.type == 'payment') {
// First check for card parameters entered by the user.
// We recommend you to validate the input at the client side itself to catch simple mistakes.
if ("card[number]" == ex.param) {
if ('card[number]' == ex.param) {
// Ask your user to recheck the card number. A better way is to use
// Stripe's https://github.com/stripe/jquery.payment for validating it in the client side itself.
//}else if(<other card params> == ex.param){
//}else if(<other card params> == ex.param){
//Similarly check for other card parameters entered by the user.
//....
} else {

@@ -241,12 +260,11 @@ // Verfication or processing failures.

}
} else if (ex.type == "invalid_request") {
} else if (ex.type == 'invalid_request') {
// For coupons you could decide to provide specific messages by using
// the 'api_error_code' attribute in the ex.
if ("coupon" == ex.param) {
if ("resource_not_found" == ex.api_error_code) {
if ('coupon' == ex.param) {
if ('resource_not_found' == ex.api_error_code) {
// Inform user to recheck his coupon code.
} else if ("resource_limit_exhausted" == ex.api_error_code) {
} else if ('resource_limit_exhausted' == ex.api_error_code) {
// Inform user that the coupon code has expired.
} else if ("invalid_request" == ex.api_error_code) {
} else if ('invalid_request' == ex.api_error_code) {
// Inform user that the coupon code is not applicable for his plan(/addons).

@@ -260,3 +278,3 @@ } else {

}
} else if (ex.type == "operation_failed") {
} else if (ex.type == 'operation_failed') {
// Indicates that the request parameters were right but the request couldn't be completed.

@@ -266,3 +284,3 @@ // The reasons might be "api_request_limit_exceeded" or could be due to an issue in ChargeBee side.

// You could ask your user to retry after some time.
} else if (ex.type == "io_error") {
} else if (ex.type == 'io_error') {
// Handle IO exceptions such as connection timeout, request timeout etc.

@@ -276,3 +294,2 @@ // You could give a generic message to the customer retry after some time.

}
```

@@ -282,10 +299,8 @@

The full documentation can be found on the chargebee site here:
The full documentation can be found on the Chargebee API Docs:
[https://apidocs.chargebee.com/docs/api?lang=typescript](https://apidocs.chargebee.com/docs/api?lang=typescript)
## License
See the LICENSE file.
See the [LICENSE](./LICENSE) file.

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc