Skip to content

Latest commit

 

History

History
575 lines (405 loc) · 30 KB

README.md

File metadata and controls

575 lines (405 loc) · 30 KB

Node.js wrapper for Help Scout Mailbox API 2.0 Travis Build Status JavaScript Standard Style NPM Version

The Node.js wrapper for the Help Scout Mailbox API 2.0. It supports the OAuth 2.0 and Client Credentials flows.

Disclaimer: This module is not in any way affiliated to or supported by Help Scout Inc. It is provided as an open-source project under the MIT license.

Installation

This library is distributed via npm. To add it as a dependency, run the following command:

npm install helpscout-mailbox-api

Authentication and authorization

There are two primary ways to authenticate to the Help Scout Mailbox 2.0 API:

  • The OAuth2 flow - is used for integrations to be used by other Help Scout users.
  • The Client Credentials flow - is used for internal integrations.

Regardless of the flow you chose, you will have to create an OAuth2 application in your Help Scout's account at first. Please, do it before proceeding further.

OAuth2 flow

This library can help you to implement the OAuth2 flow. It allows you to generate an authorization URI, swap a code for tokens, refresh them when they are expired and many more.

Creating an instance

At first, you need to create an instance of the HelpScout class. authenticationFlow has to be set to 'OAuth2':

const HelpScout = require('helpscout-mailbox-api');
const helpscout = new HelpScout({
    clientId: 'your_client_id',
    clientSecret: 'your_client_secret',
    authenticationFlow: 'OAuth2'
});

Generate an authorization URI

After creating an instance you can generate an authorization URI where a user should be redirected to authorize your application:

const authorizeUri = helpscout.generateAuthorizationUri();

The function above will return a Help Scout authorization URI with your client ID appended as a query parameter. You should redirect your user to this URI. It will look like:

https://secure.helpscout.net/authentication/authorizeClientApplication?client_id=your_client_id

You can also pass a state as a parameter:

const authorizeUri = helpscout.generateAuthorizationUri('your_secret');

In this case, you will get:

https://secure.helpscout.net/authentication/authorizeClientApplication?client_id=your_client_id&state=your_secret

Redirect back to your backend

After a user authorizes your application, Help Scout will redirect him/her back to a redirection URL that is defined in your app. A URI will contain a code query parameter and optionally a state parameter if it was passed earlier.

Get access and refresh tokens

To get access and refresh tokens you should:

const tokens = await helpscout.getTokens(code);

You have to save these tokens somewhere in your database. You will need them later during setting the credentials. The tokens retrieved via the OAuth2 flow have to be saved in order to complete the flow successfully. Keep in mind that you have to refresh the tokens when they are expired. Fortunately, the library does it for you out of the box. Read more about how refreshing tokens works here.

Client Credentials flow

This library can help you to implement the Client Credentials flow. It is much easier than the previous flow since it requires only a few simple steps.

Creating an instance

At first, you need to create an instance of the HelpScout class. authenticationFlow has to be set to 'clientCredentials':

const HelpScout = require('helpscout-mailbox-api');
const helpscout = new HelpScout({
    clientId: 'your_application_id',
    clientSecret: 'your_application_secret',
    authenticationFlow: 'clientCredentials'
});

Get an access token

After creating an instance you can get an access token:

const tokens = await helpscout.getTokens();

It would be better to save an access token in your database as well, but it is not required. The Help Scout documentation says:

This token is valid for 2 days and you should create a new one only after the existing token expires.

Frankly speaking, I tried to generate an access token using this flow a few times in a row and everything worked well. Maybe, Help Scout won't allow us to generate the new access token until the previous one expired in the future. In this case, you will have to save it.

However, I advise you to save an access token and replace the old one with the new one. It is more about security. It is better to have only one valid access token at a time and refresh it when it is expired rather than having dozens or even hundreds of valid access tokens. Read more about how refreshing tokens works here.

Refresh tokens

You do not need to refresh tokens by yourself because the library does it for you under the hood. You should always store the latest tokens, and in order to do that the library is emitting a tokens event each time, it refreshes them.

Keep in mind that you have to listen to this event if you use OAuth2 flow. If the tokens were refreshed and you did not replace the old tokens with the new ones, your OAuth2 flow will be broken since you have the old tokens and the old refresh token won't be longer valid because it has been already used. So, the library won't be able to refresh the tokens using the old refresh token. It is not the library's limitations, it is how the OAuth2 flow works.

helpscout.on('tokens', tokens => {
   // Save the new tokens somewhere in your database and use them next time.
});

The library refreshes tokens for both authentication flows. You do not need to run helpscout.setCredentials(tokens) with these new tokens. The library replaces them under the hood.

Start using the library

Set credentials

When you got your tokens either using OAuth2 or Client Credentials flow, you should set credentials on the client in order to start using it.

helpscout.setCredentials(tokens);

From this point, you can start using the library. Please, see the list of available methods below.

Update requests options

The library uses Axios to make requests. If you need to update Axios options you can use this method:

helpscout.updateRequestOptions({
   // pass any new options here. 
});

Please, update the Axios options only in case if you know what you are doing. Be aware that Axios baseUrl option can not be updated.

Available methods

Each method returns a Promise. So, you are free to use promises or async/await styles. The library does not support a callback style at the moment. If you really need it, please create a feature request and I will see what I can do.

A promise resolves with an Axios response schema and rejects with an Axios error schema.

In all the methods below, a params parameter is optional.

Conversations

The following methods are available on the helpscout.conversations object: create, delete, get, list, update.

helpscout.conversations.create(data);
helpscout.conversations.delete(conversationId);
helpscout.conversations.get(conversationId, params);
helpscout.conversations.list(params);
helpscout.conversations.update(conversationId, data);
Attachments

The following methods are available on the helpscout.conversations.attachments object: delete, getData, upload.

helpscout.conversations.attachments.delete(conversationId, attachmentId);
helpscout.conversations.attachments.getData(conversationId, attachmentId);
helpscout.conversations.attachments.upload(conversationId, attachmentId, data);
Custom Fields

The following methods are available on the helpscout.conversations.customFields object: update.

helpscout.conversations.customFields.update(conversationId, data);
Tags

The following methods are available on the helpscout.conversations.tags object: update.

helpscout.conversations.tags.update(conversationId, data);
Threads

The following methods are available on the helpscout.conversations.threads object: createChat, createCustomer, createNote, createPhone, createReply, get, list, update.

helpscout.conversations.threads.createChat(conversationId, data);
helpscout.conversations.threads.createCustomer(conversationId, data);
helpscout.conversations.threads.createNote(conversationId, data);
helpscout.conversations.threads.createPhone(conversationId, data);
helpscout.conversations.threads.createReply(conversationId, data);
helpscout.conversations.threads.get(onversationId, threadId);
helpscout.conversations.threads.list(conversationId, params);
helpscout.conversations.threads.update(conversationId, threadId, data);

Customer properties

The following methods are available on the helpscout.customerProperties object: list.

helpscout.customerProperties.list(params);

Customers

The following methods are available on the helpscout.customers object: create, get, list, overwrite, update.

helpscout.customers.create(data);
helpscout.customers.get(customerId, params);
helpscout.customers.list(params);
helpscout.customers.overwrite(customerId, data);
helpscout.customers.update(customerId, data);
Addresses

The following methods are available on the helpscout.customers.addresses object: create, delete, get, update.

helpscout.customers.addresses.create(customerId, data);
helpscout.customers.addresses.delete(customerId);
helpscout.customers.addresses.get(customerId);
helpscout.customers.addresses.update(customerId, data);
Chat Handles

The following methods are available on the helpscout.customers.chatHandles object: create, delete, list, update.

helpscout.customers.chatHandles.create(customerId, data);
helpscout.customers.chatHandles.delete(customerId, chatId);
helpscout.customers.chatHandles.list(customerId, params);
helpscout.customers.chatHandles.update(customerId, chatId, data);
Emails

The following methods are available on the helpscout.customers.emails object: create, delete, list, update.

helpscout.customers.emails.create(customerId, data);
helpscout.customers.emails.delete(customerId, emailId);
helpscout.customers.emails.list(customerId, params);
helpscout.customers.emails.update(customerId, emailId, data);
Phones

The following methods are available on the helpscout.customers.phones object: create, delete, list, update.

helpscout.customers.phones.create(customerId, data);
helpscout.customers.phones.delete(customerId, phoneId);
helpscout.customers.phones.list(customerId, params);
helpscout.customers.phones.update(customerId, phoneId, data);
Properties

The following methods are available on the helpscout.customers.properties object: update.

helpscout.customers.properties.update(customerId, data);
Social Profiles

The following methods are available on the helpscout.customers.socialProfiles object: create, delete, list, update.

helpscout.customers.socialProfiles.create(customerId, data);
helpscout.customers.socialProfiles.delete(customerId, socialProfileId);
helpscout.customers.socialProfiles.list(customerId, params);
helpscout.customers.socialProfiles.update(customerId, socialProfileId, data);
Websites

The following methods are available on the helpscout.customers.websites object: create, delete, list, update.

helpscout.customers.websites.create(customerId, data);
helpscout.customers.websites.delete(customerId, websiteId);
helpscout.customers.websites.list(customerId, params);
helpscout.customers.websites.update(customerId, websiteId, data);

Mailboxes

The following methods are available on the helpscout.mailboxes object: get, list.

helpscout.mailboxes.get(mailboxId);
helpscout.mailboxes.list(params);
Custom fields

The following methods are available on the helpscout.mailboxes.customFields object: list.

helpscout.mailboxes.customFields.list(mailboxId, params);
Folders

The following methods are available on the helpscout.mailboxes.folders object: list.

helpscout.mailboxes.folders.list(mailboxId, params);

Ratings

The following methods are available on the helpscout.ratings object: get.

helpscout.ratings.get(ratingId);

Reports

The following methods are available on the helpscout.reports object: getChatReport, getEmailReport, getPhoneReport.

helpscout.reports.getChatReport(params);
helpscout.reports.getEmailReport(params);
helpscout.reports.getPhoneReport(params);
Company

The following methods are available on the helpscout.reports.company object: getOverallReport, getCustomersHelpedReport, getDrilldownReport.

helpscout.reports.company.getOverallReport(params);
helpscout.reports.company.getCustomersHelpedReport(params);
helpscout.reports.company.getDrilldownReport(params);
Conversation

The following methods are available on the helpscout.reports.conversation object: getOverallReport, getVolumesByChannelReport, getBusiesTimeOfDayReport, getDrilldownReport, getDrilldownByFieldReport, getNewConversationsReport, getNewConversationsDrilldownReport, getReceivedMessagesReport.

helpscout.reports.conversation.getOverallReport(params);
helpscout.reports.conversation.getVolumesByChannelReport(params);
helpscout.reports.conversation.getBusiesTimeOfDayReport(params);
helpscout.reports.conversation.getDrilldownReport(params);
helpscout.reports.conversation.getDrilldownByFieldReport(params);
helpscout.reports.conversation.getNewConversationsReport(params);
helpscout.reports.conversation.getNewConversationsDrilldownReport(params);
helpscout.reports.conversation.getReceivedMessagesReport(params);
Docs

The following methods are available on the helpscout.reports.docs object: getOverallReport.

helpscout.reports.docs.getOverallReport(params);
Happiness

The following methods are available on the helpscout.reports.happiness object: getOverallReport, getRatingsReport.

helpscout.reports.happiness.getOverallReport(params);
helpscout.reports.happiness.getRatingsReport(params);)
Productivity

The following methods are available on the helpscout.reports.productivity object: getOverallReport, getFirstResponseTimeReport, getRepliesSentReport, getResolutionTimeReport, getResolvedReport, getResponseTimeReport.

helpscout.reports.productivity.getOverallReport(params);
helpscout.reports.productivity.getFirstResponseTimeReport(params);
helpscout.reports.productivity.getRepliesSentReport(params);
helpscout.reports.productivity.getResolutionTimeReport(params);
helpscout.reports.productivity.getResolvedReport(params);
helpscout.reports.productivity.getResponseTimeReport(params);
User

The following methods are available on the helpscout.reports.user object: getOverallReport, getConversationHistoryReport, getCustomersHelpedReport, getDrilldownReport, getHappinessReport, getHappinessDrilldownReport, getRepliesReport, getResolutionsReport.

helpscout.reports.user.getOverallReport(params);
helpscout.reports.user.getConversationHistoryReport(params);
helpscout.reports.user.getCustomersHelpedReport(params);
helpscout.reports.user.getDrilldownReport(params);
helpscout.reports.user.getHappinessReport(params);
helpscout.reports.user.getHappinessDrilldownReport(params);
helpscout.reports.user.getRepliesReport(params);
helpscout.reports.user.getResolutionsReport(params);

Tags

The following methods are available on the helpscout.tags object: list.

helpscout.tags.list(params);

Teams

The following methods are available on the helpscout.teams object: list.

helpscout.teams.list(params);
Team members

The following methods are available on the helpscout.teams.teamMembers object: list.

helpscout.teams.teamMembers.list(teamId, params);

Users

The following methods are available on the helpscout.users object: get, list, me.

helpscout.users.get(userId);
helpscout.users.list(params);
helpscout.users.me();

Webhooks

The following methods are available on the helpscout.webhooks object: create, delete, get, list, update.

helpscout.webhooks.create(data);
helpscout.webhooks.delete(webhookId);
helpscout.webhooks.get(webhookId);
helpscout.webhooks.list(params);
helpscout.webhooks.update(webhookId, data);

Workflows

The following methods are available on the helpscout.workflows object: list, runManual, update.

helpscout.workflows.list(params);
helpscout.workflows.runManual(workflowId, data);
helpscout.workflows.update(workflowId, data);

Pagination

The client exposes a useful method for getting the next page's results:

const firstPageResults = await helpscout.conversations.list();
const { _embedded, _links, page } = firstPageResults;

if (_links.next) {
    const secondPageResults = await helpscout.nextPage(_links);
}

You can write a recursion function to get, for example, all the conversations or customers using this method.

Rate limiting

The library uses the great Bottleneck library in order to implement a Help Scout rate-limiting policy.

Requests are limited to 400 requests per minute per account. All users associated with the same account count against the same minute rate limit. Response code 429 is returned when the throttle limit has been reached. Write requests (POST, PUT, DELETE, PATCH) count as 2 requests toward the rate limit._

This means that we can make 400 GET or only 200 write requests per minute, or 300 GET and 50 write ones. I hope you got the idea.

The default Bottleneck options are:

{
    maxConcurrent: 2,
    minTime: 125,
    reservoir: 400,
    reservoirRefreshAmount: 400,
    reservoirRefreshInterval: 60 * 1000
}

The library uses weight of 2 as a job option for write requests (POST, PUT, DELETE, PATCH) since Help Scout counts them as 2 requests toward the rate limit.

You can update the Bottleneck options using this method:

helpscout.updateBottleneckOptions({
    // pass any new options here.
});

Under the hood, the library will execute the Bottleneck updateSettings method. Please, update the Bottleneck options only in case if you know what you are doing.

License

MIT