ZOHO CRM NODEJS SDK - 2.1
Table Of Contents
Overview
Zoho CRM NodeJS SDK offers a way to create client NodeJS applications that can be integrated with Zoho CRM.
Registering a Zoho Client
Since Zoho CRM APIs are authenticated with OAuth2 standards, you should register your client app with Zoho. To register your app:
-
Visit this page https://api-console.zoho.com/
-
Click on ADD CLIENT
.
-
Choose a Client Type
.
-
Enter Client Name, Client Domain or Homepage URL and Authorized Redirect URIs then click CREATE
.
-
Your Client app would have been created and displayed by now.
-
Select the created OAuth client.
-
Generate grant token by providing the necessary scopes, time duration (the duration for which the generated token is valid) and Scope Description.
Environmental Setup
NodeJS SDK is installable through npm. npm is a tool for dependency management in NodeJS. SDK expects the following from the client app.
Including the SDK in your project
You can include the SDK to your project using:
-
Install Node from nodejs.org (if not installed).
-
Install NodeJS SDK
- Navigate to the workspace of your client app.
- Run the command below:
npm install @zohocrm/nodejs-sdk
-
The NodeJS SDK will be installed and a package named @zohocrm/nodejs-sdk will be created in the local machine.
-
Another method to install the SDK
- Add dependencies to the package.json of the node server with the latest version (recommended)
- Run npm install in the directory which installs all the dependencies mentioned in package.json.
Token Persistence
Token persistence refers to storing and utilizing the authentication tokens that are provided by Zoho. There are three ways provided by the SDK in which persistence can be utilized. They are DataBase Persistence, File Persistence and Custom Persistence.
Table of Contents
Implementing OAuth Persistence
Once the application is authorized, OAuth access and refresh tokens can be used for subsequent user data requests to Zoho CRM. Hence, they need to be persisted by the client app.
The persistence is achieved by writing an implementation of the inbuilt TokenStore interface, which has the following callback methods.
-
getToken(user, token) - invoked before firing a request to fetch the saved tokens. This method should return implementation Token Class object for the library to process it.
-
saveToken(user, token) - invoked after fetching access and refresh tokens from Zoho.
-
deleteToken(token) - invoked before saving the latest tokens.
-
getTokens() - The method to retrieve all the stored tokens.
-
deleteTokens() - The method to delete all the stored tokens.
-
getTokenById(id, token) - This method is used to retrieve the user token details based on unique ID.
Note:
DataBase Persistence
In case the user prefers to use default DataBase persistence, MySQL can be used.
Note:
- Custom database name and table name can be set in DBStore instance
MySQL Query
CREATE TABLE oauthtoken (
id varchar(255) NOT NULL,
user_mail varchar(255) NOT NULL,
client_id varchar(255),
client_secret varchar(255),
refresh_token varchar(255),
access_token varchar(255),
grant_token varchar(255),
expiry_time varchar(20),
redirect_url varchar(255),
primary key (id)
);
Create DBStore object
const DBBuilder = require( "@zohocrm/nodejs-sdk/models/authenticator/store/db_builder").DBBuilder;
let tokenstore = new DBStore().build();
let tokenstore = new DBBuilder()
.host("hostName")
.databaseName("databaseName")
.userName("userName")
.portNumber("portNumber")
.tableName("tableName")
.password("password")
.build();
File Persistence
In case of default File Persistence, the user can persist tokens in the local drive, by providing the the absolute file path to the FileStore object. The File contains the following
-
The File contains
-
id
-
user_mail
-
client_id
-
client_secret
-
refresh_token
-
access_token
-
grant_token
-
expiry_time
-
redirect_url
Create FileStore object
const FileStore = require( "@zohocrm/nodejs-sdk/models/authenticator/store/file_store").FileStore;
let tokenstore = new FileStore("/Users/username/Documents/nodejs_sdk_tokens.txt");
Custom Persistence
To use Custom Persistence, the user must extend TokenStore Class and override the methods.
const TokenStore = require('@zohocrm/nodejs-sdk/models/authenticator/store/token_store').TokenStore;
class CustomStore extends TokenStore{
constructor(){
super();
}
getToken(user, token) {
return null;
}
saveToken(user, token) {
}
deleteToken(token) {
}
getTokens() {
}
deleteTokens() {
}
getTokenById(id, token) {
return null;
}
}
module.exports = {CustomStore}
Configuration
Before you get started with creating your NodeJS application, you need to register your client and authenticate the app with Zoho.
-
Create an instance of Logger Class to log exception and API information.
const {Levels} = require("@zohocrm/nodejs-sdk/routes/logger/logger");
const LogBuilder = require("@zohocrm/nodejs-sdk/routes/logger/log_builder").LogBuilder;
let logger = new LogBuilder()
.level(Levels.INFO)
.filePath("/Users/Documents/final-logs.txt")
.build();
-
Create an instance of UserSignature Class that identifies the current user.
const UserSignature = require( "@zohocrm/nodejs-sdk/routes/user_signature").UserSignature;
let user = new UserSignature("abc@zoho.com");
-
Configure API environment which decides the domain and the URL to make API calls.
const USDataCenter = require( "@zohocrm/nodejs-sdk/routes/dc/us_data_center").USDataCenter;
let environment = USDataCenter.PRODUCTION();
-
Create an instance of OAuthToken with the information that you get after registering your Zoho client.
const OAuthBuilder = require("@zohocrm/nodejs-sdk/models/authenticator/oauth_builder").OAuthBuilder;
let token = new OAuthBuilder()
.id("id")
.build();
let token = new OAuthBuilder()
.clientId("clientId")
.clientSecret("clientSecret")
.grantToken("grantToken")
.redirectURL("redirectURL")
.build();
let token = new OAuthBuilder()
.clientId("clientId")
.clientSecret("clientSecret")
.refreshToken("refreshToken")
.redirectURL("redirectURL")
.build();
-
Create an instance of TokenStore to persist tokens, used for authenticating all the requests.
const DBBuilder = require( "@zohocrm/nodejs-sdk/models/authenticator/store/db_builder").DBBuilder;
let tokenstore = new DBStore().build();
let tokenstore = new DBBuilder()
.host("hostName")
.databaseName("databaseName")
.userName("userName")
.portNumber("portNumber")
.tableName("tableName")
.password("password")
.build();
let tokenstore = new FileStore("absolute_file_path");
let tokenstore = new CustomStore();
-
Create an instance of SDKConfig containing the SDK configuration.
const SDKConfigBuilder = require("@zohocrm/nodejs-sdk/routes/sdk_config_builder").SDKConfigBuilder;
let sdkConfig = new SDKConfigBuilder().pickListValidation(false).autoRefreshFields(true).build();
-
The path containing the absolute directory path (in the key resourcePath) to store user-specific files containing information about fields in modules.
let resourcePath = "/Users/user_name/Documents/nodejs-app";
-
Create an instance of RequestProxy containing the proxy properties of the user.
const RequestProxy = require( "@zohocrm/nodejs-sdk/routes/request_proxy").RequestProxy;
let requestProxy = new ProxyBuilder()
.host("proxyHost")
.port("proxyPort")
.user("proxyUser")
.password("password")
.build();
Initializing the Application
Initialize the SDK using the following code.
const InitializeBuilder = require( "@zohocrm/nodejs-sdk/routes/initialize_builder").InitializeBuilder;
const OAuthBuilder = require( "@zohocrm/nodejs-sdk/models/authenticator/oauth_builder").OAuthBuilder;
const UserSignature = require( "@zohocrm/nodejs-sdk/routes/user_signature").UserSignature;
const {Levels} = require( "@zohocrm/nodejs-sdk/routes/logger/logger");
const LogBuilder = require( "@zohocrm/nodejs-sdk/routes/logger/log_builder").LogBuilder;
const USDataCenter = require( "@zohocrm/nodejs-sdk/routes/dc/us_data_center").USDataCenter;
const DBBuilder = require( "@zohocrm/nodejs-sdk/models/authenticator/store/db_builder").DBBuilder;
const FileStore = require( "@zohocrm/nodejs-sdk/models/authenticator/store/file_store").FileStore;
const SDKConfigBuilder = require("@zohocrm/nodejs-sdk/routes/sdk_config_builder").SDKConfigBuilder;
const ProxyBuilder = require( "@zohocrm/nodejs-sdk/routes/proxy_builder").ProxyBuilder;
class Initializer {
static async initialize() {
let logger = new LogBuilder()
.level(Levels.INFO)
.filePath("/Users/user_name/Documents/nodejs_sdk_log.log")
.build();
let user = new UserSignature("abc@zoho.com");
let environment = USDataCenter.PRODUCTION();
let token = new OAuthBuilder()
.clientId("clientId")
.clientSecret("clientSecret")
.grantToken("GRANT Token")
.redirectURL("redirectURL")
.build();
let tokenstore = new DBBuilder()
.host("hostName")
.databaseName("databaseName")
.userName("userName")
.portNumber("portNumber")
.tableName("tableName")
.password("password")
.build();
let sdkConfig = new SDKConfigBuilder().pickListValidation(false).autoRefreshFields(true).build();
let resourcePath = "/Users/user_name/Documents/nodejssdk-application";
let requestProxy = new ProxyBuilder()
.host("proxyHost")
.port("proxyPort")
.user("proxyUser")
.password("password")
.build();
(await new InitializeBuilder())
.user(user)
.environment(environment)
.token(token)
.store(tokenstore)
.SDKConfig(sdkConfig)
.resourcePath(resourcePath)
.logger(logger)
.requestProxy(requestProxy)
.initialize();
}
}
Initializer.initialize()
- You can now access the functionalities of the SDK. Refer to the sample codes to make various API calls through the SDK.
Class Hierarchy
![classdiagram](https://github.com/zoho/zohocrm-nodejs-sdk-2.1/raw/HEAD/class_hierarchy.png)
Responses and Exceptions
All SDK method calls return an instance of APIResponse.
After a successful API request, the getObject() method returns an instance of the ResponseWrapper (for GET) or the ActionWrapper (for POST, PUT, DELETE).
Whenever the API returns an error response, the getObject() returns an instance of APIException class.
ResponseWrapper (for GET requests) and ActionWrapper (for POST, PUT, DELETE requests) are the expected objects for Zoho CRM APIs’ responses
However, some specific operations have different expected objects, such as the following
-
Operations involving records in Tags
-
Getting Record Count for a specific Tag operation
-
Operations involving BaseCurrency
- BaseCurrencyActionWrapper
-
Lead convert operation
-
Retrieving Deleted records operation
-
Record image download operation
-
MassUpdate record operations
- MassUpdateActionWrapper
- MassUpdateResponseWrapper
-
For Transfer Pipeline operation
- APIResponse<TransferActionHandler>
GET Requests
- The getObject() returns instance of one of the following classes, based on the return type.
POST, PUT, DELETE Requests
-
The getObject() returns instance of one of the following classes
- ActionWrapper
- RecordActionWrapper
- BaseCurrencyActionWrapper
- MassUpdateActionWrapper
- ConvertActionWrapper
- APIException
- TransferActionWrapper
-
These wrapper classes may contain one or an array of instances of the following classes, depending on the response
- SuccessResponse Class, if the request was successful.
- APIException Class, if the request was erroneous.
For example, when you insert two records, and one of them was inserted successfully while the other one failed, the ActionWrapper will contain one instance each of the SuccessResponse and APIException classes.
All other exceptions such as SDK anomalies and other unexpected behaviours are thrown under the SDKException class.
Multi-User support in the NodeJS SDK
The NodeJS SDK (version 2.x.x) supports both single-user and multi-user app.
Multi-user App
Multi-users functionality is achieved using switchUser() method.
(await new InitializeBuilder())
.user(user)
.environment(environment)
.token(token)
.store(tokenstore)
.SDKConfig(sdkConfig)
.switchUser();
To Remove a user's configuration in SDK. Use the below code
await Initializer.removeUserConfiguration(user, environment)
Sample Multi-user code
const InitializeBuilder = require( "@zohocrm/nodejs-sdk/routes/initialize_builder").InitializeBuilder;
const OAuthBuilder = require( "@zohocrm/nodejs-sdk/models/authenticator/oauth_builder").OAuthBuilder;
const UserSignature = require( "@zohocrm/nodejs-sdk/routes/user_signature").UserSignature;
const {Levels} = require( "@zohocrm/nodejs-sdk/routes/logger/logger");
const LogBuilder = require( "@zohocrm/nodejs-sdk/routes/logger/log_builder").LogBuilder;
const USDataCenter = require( "@zohocrm/nodejs-sdk/routes/dc/us_data_center").USDataCenter;
const EUDataCenter = require( "@zohocrm/nodejs-sdk/routes/dc/eu_data_center").EUDataCenter;
const DBBuilder = require( "@zohocrm/nodejs-sdk/models/authenticator/store/db_builder").DBBuilder;
const FileStore = require( "@zohocrm/nodejs-sdk/models/authenticator/store/file_store").FileStore;
const {RecordOperations} = require("@zohocrm/nodejs-sdk/core/com/zoho/crm/api/record/record_operations");
const ParameterMap = require("@zohocrm/nodejs-sdk/routes/parameter_map").ParameterMap;
const HeaderMap = require("@zohocrm/nodejs-sdk/routes/header_map").HeaderMap;
const ResponseWrapper = require("@zohocrm/nodejs-sdk/core/com/zoho/crm/api/record/response_wrapper").ResponseWrapper;
const ProxyBuilder = require( "@zohocrm/nodejs-sdk/routes/proxy_builder").ProxyBuilder;
const SDKConfigBuilder = require("@zohocrm/nodejs-sdk/routes/sdk_config_builder").MasterModel;
const GetRecordsParam = require("@zohocrm/nodejs-sdk/core/com/zoho/crm/api/record/record_operations").GetRecordsParam;
const GetRecordsHeader = require("@zohocrm/nodejs-sdk/core/com/zoho/crm/api/record/record_operations").GetRecordsHeader;
class Record {
static async call() {
let logger = new LogBuilder()
.level(Levels.INFO)
.filePath("/Users/username/final-logs.txt")
.build();
let user1 = new UserSignature("abc@zoho.com");
let environment1 = USDataCenter.PRODUCTION();
let token1 = new OAuthBuilder()
.clientId("clientId")
.clientSecret("clientSecret")
.refreshToken("refreshToken")
.redirectURL("redirectURL")
.build();
let tokenstore = new DBStore().build();
let tokenstore = new DBBuilder()
.host("hostName")
.databaseName("databaseName")
.userName("userName")
.portNumber("portNumber")
.tableName("tableName")
.password("password")
.build();
let tokenstore = new FileStore("/Users/username/nodejs_sdk_tokens.txt");
let sdkConfig = new SDKConfigBuilder().pickListValidation(false).autoRefreshFields(true).build();
let resourcePath = "/Users/username";
(await new InitializeBuilder())
.user(user1)
.environment(environment1)
.token(token1)
.store(tokenstore)
.SDKConfig(sdkConfig)
.resourcePath(resourcePath)
.logger(logger)
.initialize();
await Record.getRecords("Leads");
await Initializer.removeUserConfiguration(user1, environment1);
let user2 = new UserSignature("abc2@zoho.eu");
let environment2 = EUDataCenter.SANDBOX();
let token2 = new OAuthBuilder()
.clientId("clientId")
.clientSecret("clientSecret")
.grantToken("GRANT Token")
.refreshToken("REFRESH Token")
.redirectURL("redirectURL")
.build();
let requestProxy = new ProxyBuilder()
.host("proxyHost")
.port("proxyPort")
.user("proxyUser")
.password("password")
.build();
let sdkConfig2 = new SDKConfigBuilder().pickListValidation(true).autoRefreshFields(true).build();
(await new InitializeBuilder())
.user(user2)
.environment(environment2)
.token(token2)
.SDKConfig(sdkConfig2)
.requestProxy(requestProxy)
.switchUser();
await Record.getRecords("Leads");
}
static async getRecords(moduleAPIName){
try {
let recordOperations = new RecordOperations();
let paramInstance = new ParameterMap();
await paramInstance.add(GetRecordsParam.APPROVED, "both");
let headerInstance = new HeaderMap();
await headerInstance.add(GetRecordsHeader.IF_MODIFIED_SINCE, new Date("2020-01-01T00:00:00+05:30"));
let response = await recordOperations.getRecords(moduleAPIName, paramInstance, headerInstance);
if(response != null){
console.log("Status Code: " + response.getStatusCode());
if([204, 304].includes(response.getStatusCode())){
console.log(response.getStatusCode() == 204? "No Content" : "Not Modified");
return;
}
let responseObject = response.getObject();
if(responseObject != null){
if(responseObject instanceof ResponseWrapper){
let records = responseObject.getData();
for (let index = 0; index < records.length; index++) {
let record = records[index];
console.log("Record ID: " + record.getId());
let createdBy = record.getCreatedBy();
if(createdBy != null){
console.log("Record Created By User-ID: " + createdBy.getId());
console.log("Record Created By User-Name: " + createdBy.getName());
console.log("Record Created By User-Email: " + createdBy.getEmail());
}
console.log("Record CreatedTime: " + record.getCreatedTime());
let modifiedBy = record.getModifiedBy();
if(modifiedBy != null){
console.log("Record Modified By User-ID: " + modifiedBy.getId());
console.log("Record Modified By User-Name: " + modifiedBy.getName());
console.log("Record Modified By User-Email: " + modifiedBy.getEmail());
}
console.log("Record ModifiedTime: " + record.getModifiedTime());
let tags = record.getTag();
if(tags != null){
tags.forEach(tag => {
console.log("Record Tag Name: " + tag.getName());
console.log("Record Tag ID: " + tag.getId());
});
}
let keyValues = record.getKeyValues();
let keyArray = Array.from(keyValues.keys());
for (let keyIndex = 0; keyIndex < keyArray.length; keyIndex++) {
const keyName = keyArray[keyIndex];
let value = keyValues.get(keyName);
console.log(keyName + " : " + value);
}
}
}
}
}
} catch (error) {
console.log(error);
}
}
}
Record.call();
-
The program execution starts from call().
-
The details of "user1" are is given in the variables user1, token1, environment1.
-
Similarly, the details of another user "user2" is given in the variables user2, token2, environment2.
-
The switchUser() function is used to switch between the "user1" and "user2" as required.
-
Based on the latest switched user, the Record.getRecords(moduleAPIName) will fetch records.
SDK Sample code
const InitializeBuilder = require( "@zohocrm/nodejs-sdk/routes/initialize_builder").InitializeBuilder;
const OAuthBuilder = require( "@zohocrm/nodejs-sdk/models/authenticator/oauth_builder").OAuthBuilder;
const UserSignature = require( "@zohocrm/nodejs-sdk/routes/user_signature").UserSignature;
const {Levels} = require( "@zohocrm/nodejs-sdk/routes/logger/logger");
const LogBuilder = require( "@zohocrm/nodejs-sdk/routes/logger/log_builder").LogBuilder;
const USDataCenter = require( "@zohocrm/nodejs-sdk/routes/dc/us_data_center").USDataCenter;
const EUDataCenter = require( "@zohocrm/nodejs-sdk/routes/dc/eu_data_center").EUDataCenter;
const DBBuilder = require( "@zohocrm/nodejs-sdk/models/authenticator/store/db_builder").DBBuilder;
const FileStore = require( "@zohocrm/nodejs-sdk/models/authenticator/store/file_store").FileStore;
const {RecordOperations} = require("@zohocrm/nodejs-sdk/core/com/zoho/crm/api/record/record_operations");
const ParameterMap = require("@zohocrm/nodejs-sdk/routes/parameter_map").ParameterMap;
const HeaderMap = require("@zohocrm/nodejs-sdk/routes/header_map").HeaderMap;
const ResponseWrapper = require("@zohocrm/nodejs-sdk/core/com/zoho/crm/api/record/response_wrapper").ResponseWrapper;
const ProxyBuilder = require( "@zohocrm/nodejs-sdk/routes/proxy_builder").ProxyBuilder;
const SDKConfigBuilder = require("@zohocrm/nodejs-sdk/routes/sdk_config_builder").MasterModel;
class Record{
static async getRecords(){
let logger = new LogBuilder()
.level(Levels.INFO)
.filePath("/Users/user_name/nodejs_sdk_log.log")
.build();
let user = new UserSignature("abc@zoho.com");
let environment = USDataCenter.PRODUCTION();
let token1 = new OAuthBuilder()
.clientId("clientId")
.clientSecret("clientSecret")
.grantToken("GRANT Token")
.redirectURL("redirectURL")
.build();
let tokenstore = new DBStore().build();
let tokenstore = new DBBuilder()
.host("hostName")
.databaseName("databaseName")
.userName("userName")
.portNumber("portNumber")
.tableName("tableName")
.password("password")
.build();
let tokenstore = new FileStore("/Users/username/Documents/nodejs_sdk_tokens.txt");
let sdkConfig = new SDKConfigBuilder().pickListValidation(false).autoRefreshFields(true).build();
let resourcePath = "/Users/user_name/Documents/nodejs-app";
(await new InitializeBuilder())
.user(user1)
.environment(environment1)
.token(token1)
.store(tokenstore)
.SDKConfig(sdkConfig)
.resourcePath(resourcePath)
.logger(logger)
.initialize();
try {
let moduleAPIName = "Leads";
let recordOperations = new RecordOperations();
let paramInstance = new ParameterMap();
await paramInstance.add(GetRecordsParam.APPROVED, "both");
let headerInstance = new HeaderMap();
await headerInstance.add(GetRecordsHeader.IF_MODIFIED_SINCE, new Date("2020-01-01T00:00:00+05:30"));
let response = await recordOperations.getRecords(moduleAPIName, paramInstance, headerInstance);
if(response != null){
console.log("Status Code: " + response.getStatusCode());
if([204, 304].includes(response.getStatusCode())){
console.log(response.getStatusCode() == 204? "No Content" : "Not Modified");
return;
}
let responseObject = response.getObject();
if(responseObject != null){
if(responseObject instanceof ResponseWrapper){
let records = responseObject.getData();
for (let index = 0; index < records.length; index++) {
let record = records[index];
console.log("Record ID: " + record.getId());
let createdBy = record.getCreatedBy();
if(createdBy != null){
console.log("Record Created By User-ID: " + createdBy.getId());
console.log("Record Created By User-Name: " + createdBy.getName());
console.log("Record Created By User-Email: " + createdBy.getEmail());
}
console.log("Record CreatedTime: " + record.getCreatedTime());
let modifiedBy = record.getModifiedBy();
if(modifiedBy != null){
console.log("Record Modified By User-ID: " + modifiedBy.getId());
console.log("Record Modified By User-Name: " + modifiedBy.getName());
console.log("Record Modified By User-Email: " + modifiedBy.getEmail());
}
console.log("Record ModifiedTime: " + record.getModifiedTime());
let tags = record.getTag();
if(tags != null){
tags.forEach(tag => {
console.log("Record Tag Name: " + tag.getName());
console.log("Record Tag ID: " + tag.getId());
});
}
let keyValues = record.getKeyValues();
let keyArray = Array.from(keyValues.keys());
for (let keyIndex = 0; keyIndex < keyArray.length; keyIndex++) {
const keyName = keyArray[keyIndex];
let value = keyValues.get(keyName);
console.log(keyName + " : " + value);
}
}
}
}
}
} catch (error) {
console.log(error);
}
}
}
Record.getRecords();