ZOHO CRM TYPESCRIPT SDK
Table Of Contents
Overview
Zoho CRM TypeScript SDK offers a way to create client TypeScript 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
TypeScript SDK is installable through npm. npm is a tool for dependency management in TypeScript. 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 TypeScript NPM package.
npm install -g typescript
-
Install TypeScript SDK
- Navigate to the workspace of your client app.
- Run the command below:
npm install @zohocrm/typescript-sdk
-
The TypeScript SDK will be installed and a package named @zohocrm/typescript-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 Class, which has the following callback methods.
-
getToken(user : UserSignature, token : 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: UserSignature, token : Token) - invoked after fetching access and refresh tokens from Zoho.
-
deleteToken(token : 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.
DataBase Persistence
In case the user prefers to use default DataBase persistence, MySQL can be used.
MySQL Query
create table oauthtoken(id int(11) not null auto_increment, user_mail varchar(255) not null, client_id varchar(255), refresh_token varchar(255), access_token varchar(255), grant_token varchar(255), expiry_time varchar(20), primary key (id));
alter table oauthtoken auto_increment = 1;
Create DBStore object
import {DBStore} from "@zohocrm/typescript-sdk/models/authenticator/store/db_store";
let tokenstore: DBStore = new DBStore();
let tokenstore: DBStore = new DBStore("hostName", "dataBaseName", "userName", "password", "portNumber");
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
-
user_mail
-
client_id
-
refresh_token
-
access_token
-
grant_token
-
expiry_time
Create FileStore object
import {FileStore} from "@zohocrm/typescript-sdk/models/authenticator/store/file_store";
let tokenstore: FileStore = new FileStore("/Users/username/Documents/ts_sdk_tokens.txt");
Custom Persistence
To use Custom Persistence, the user must extend TokenStore Class (@zohocrm/typescript-sdk/models/authenticator/store/token_store) and override the methods.
import { TokenStore } from "@zohocrm/typescript-sdk/models/authenticator/store/token_store";
export class CustomStore implements TokenStore {
constructor(){
}
async getToken(user: UserSignature, token: Token): Promise<Token | undefined> {
return undefined;
}
async saveToken(user: UserSignature, token: Token): Promise<void>{
}
async deleteToken(token: Token): Promise<void> {
}
async getTokens(): Promise<Token[]> {
}
deleteTokens(): void {
}
}
module.exports = {CustomStore}
Configuration
Before you get started with creating your TypeScript 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.
import {Levels,Logger} from "@zohocrm/typescript-sdk/routes/logger/logger"
let logger: Logger = Logger.getInstance(Levels.INFO, "/Users/user_name/Documents/ts_sdk_log.log");
-
Create an instance of UserSignature Class that identifies the current user.
import {UserSignature} from "@zohocrm/typescript-sdk/routes/user_signature"
let user: UserSignature = new UserSignature("abc@zoho.com");
-
Configure API environment which decides the domain and the URL to make API calls.
import {USDataCenter} from "@zohocrm/typescript-sdk/routes/dc/us_data_center"
let environment: Environment = USDataCenter.PRODUCTION();
-
Create an instance of OAuthToken with the information that you get after registering your Zoho client.
import { OAuthToken,TokenType } from "@zohocrm/typescript-sdk/models/authenticator/oauth_token"
let token: OAuthToken = new OAuthToken("clientId", "clientSecret", "REFRESH/ GRANT Token", TokenType.REFRESH/TokenType.GRANT, "redirectURL");
-
Create an instance of TokenStore to persist tokens, used for authenticating all the requests.
import {DBStore} from "@zohocrm/typescript-sdk/models/authenticator/store/db_store"
import {FileStore} from "@zohocrm/typescript-sdk/models/authenticator/store/file_store"
let tokenstore: DBStore = new DBStore();
let tokenstore: DBStore = new DBStore("hostName", "dataBaseName", "userName", "password", "portNumber");
-
Create an instance of SDKConfig containing the SDK configuration.
import {SDKConfig} from "@zohocrm/typescript-sdk/routes/sdk_config";
import {SDKConfigBuilder} from "@zohocrm/typescript-sdk/routes/sdk_config_builder";
let sdkConfig: SDKConfig = new SDKConfigBuilder().setPickListValidation(false).setAutoRefreshFields(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: string = "/Users/user_name/Documents/typescript-app";
-
Create an instance of RequestProxy containing the proxy properties of the user.
import { RequestProxy} from "@zohocrm/typescript-sdk/routes/request_proxy";
let requestProxy: RequestProxy = new RequestProxy("proxyHost", 80, "proxyUser", "password");
Initializing the Application
Initialize the SDK using the following code.
import {UserSignature} from "@zohocrm/typescript-sdk/routes/user_signature"
import {SDKConfigBuilder} from "@zohocrm/typescript-sdk/routes/sdk_config_builder"
import {DBStore} from "@zohocrm/typescript-sdk/models/authenticator/store/db_store"
import {FileStore} from "@zohocrm/typescript-sdk/models/authenticator/store/file_store"
import {SDKConfig} from "@zohocrm/typescript-sdk/routes/sdk_config"
import {Levels,Logger} from "@zohocrm/typescript-sdk/routes/logger/logger"
import {Environment} from "@zohocrm/typescript-sdk/routes/dc/environment"
import {USDataCenter} from "@zohocrm/typescript-sdk/routes/dc/us_data_center"
import {OAuthToken,TokenType} from "@zohocrm/typescript-sdk/models/authenticator/oauth_token"
import {Initializer} from "@zohocrm/typescript-sdk/routes/initializer"
import {RequestProxy} from "@zohocrm/typescript-sdk/routes/request_proxy"
export class Initializer{
public static async initialize(){
let logger: Logger = Logger.getInstance(Levels.INFO, "/Users/user_name/Documents/ts_sdk_log.log");
let user: UserSignature = new UserSignature("abc@zoho.com");
let environment: Environment = USDataCenter.PRODUCTION();
let token: OAuthToken = new OAuthToken("clientId", "clientSecret", "REFRESH/ GRANT Token", TokenType.REFRESH/TokenType.GRANT, "redirectURL");
let tokenstore: DBStore = new DBStore("hostName", "dataBaseName", "userName", "password", "portNumber");
let sdkConfig: SDKConfig = new SDKConfigBuilder().setPickListValidation(false).setAutoRefreshFields(true).build();
let resourcePath: string = "/Users/user_name/Documents/tsssdk-application";
let proxy: RequestProxy = new RequestProxy("proxyHost", 80);
let proxy: RequestProxy = new RequestProxy("proxyHost", 80, "proxyUser", "password");
await Initializer.initialize(user, environment, token, store, sdkConfig, resourcePath, logger, proxy);
}
}
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
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
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
-
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 TypeScript SDK
The TypeScript SDK (from version 1.x.x) supports both single-user and multi-user app.
Multi-user App
Multi-users functionality is achieved using Initializer's static switchUser() method.
await Initializer.switchUser(user, environment, token, sdkConfig, requestProxy)
await Initializer.switchUser(user, environment, token, sdkConfig)
To Remove a user's configuration in SDK. Use the below code
await Initializer.removeUserConfiguration(user, environment)
Sample Multi-user code
import {UserSignature} from "@zohocrm/typescript-sdk/routes/user_signature"
import {SDKConfigBuilder} from "@zohocrm/typescript-sdk/routes/sdk_config_builder"
import {DBStore} from "@zohocrm/typescript-sdk/models/authenticator/store/db_store"
import {FileStore} from "@zohocrm/typescript-sdk/models/authenticator/store/file_store"
import {SDKConfig} from "@zohocrm/typescript-sdk/routes/sdk_config"
import {Levels,Logger} from "@zohocrm/typescript-sdk/routes/logger/logger"
import {Environment} from "@zohocrm/typescript-sdk/routes/dc/environment"
import {USDataCenter} from "@zohocrm/typescript-sdk/routes/dc/us_data_center"
import {EUDataCenter} from "@zohocrm/typescript-sdk/routes/dc/eu_data_center"
import { OAuthToken,TokenType } from "@zohocrm/typescript-sdk/models/authenticator/oauth_token"
import { Initializer} from "@zohocrm/typescript-sdk/routes/initializer"
import { RequestProxy} from "@zohocrm/typescript-sdk/routes/request_proxy"
import {RecordOperations, GetRecordsHeader, GetRecordsParam} from "@zohocrm/typescript-sdk/core/com/zoho/crm/api/record/record_operations";
import {ResponseWrapper} from "@zohocrm/typescript-sdk/core/com/zoho/crm/api/record/response_wrapper";
import {ResponseHandler} from "@zohocrm/typescript-sdk/core/com/zoho/crm/api/record/response_handler";
import {Record} from "@zohocrm/typescript-sdk/core/com/zoho/crm/api/record/record";
import {Tag} from "@zohocrm/typescript-sdk/core/com/zoho/crm/api/tags/tag";
import {APIResponse} from "@zohocrm/typescript-sdk/routes/controllers/api_response";
import { SDKException } from "@zohocrm/typescript-sdk/core/com/zoho/crm/api/exception/sdk_exception";
import {ParameterMap} from "@zohocrm/typescript-sdk/routes/parameter_map";
import {HeaderMap} from "@zohocrm/typescript-sdk/routes/header_map";
class SampleRecord{
public static async call(){
let logger = Logger.getInstance(Levels.INFO, "/Users/user_name/Documents/ts_sdk_log.log");
let user1 = new UserSignature("abc@zoho.com");
let environment1: Environment = USDataCenter.PRODUCTION();
let token1 = new OAuthToken("clientId1", "clientSecret1", "REFRESH/ GRANT Token", TokenType.REFRESH/TokenType.GRANT, "redirectURL");
let store: DBStore = new DBStore();
let store: DBStore = new DBStore("hostName", "dataBaseName", "userName", "password", "portNumber");
let store: FileStore = new FileStore("/Users/username/Documents/ts_sdk_tokens.txt");
let sdkConfig: SDKConfig = new SDKConfigBuilder().setPickListValidation(false).setAutoRefreshFields(true).build();
let resourcePath: string = "/Users/user_name/Documents/ts-app";
await Initializer.initialize(user1, environment1, token1, store, sdkConfig, resourcePath, logger);
await SampleRecord.getRecords("Leads");
await Initializer.removeUserConfiguration(user1, environment1);
let user2: UserSignature = new UserSignature("abc2@zoho.eu");
let environment2: Environment = EUDataCenter.SANDBOX();
let token2: OAuthToken = new OAuthToken("clientId2", "clientSecret2", "REFRESH/ GRANT Token", TokenType.REFRESH, "redirectURL");
let requestProxy: RequestProxy = new RequestProxy("proxyHost", 80, "proxyUser", "password");
let sdkConfig2: SDKConfig = new SDKConfigBuilder().setPickListValidation(true).setAutoRefreshFields(true).build();
await Initializer.switchUser(user2, environment2, token2, sdkConfig2, requestProxy);
await SampleRecord.getRecords("Leads");
}
static async getRecords(moduleAPIName: string){
try {
let moduleAPIName = "Leads";
let recordOperations: RecordOperations = new RecordOperations();
let paramInstance: ParameterMap = new ParameterMap();
await paramInstance.add(GetRecordsParam.APPROVED, "both");
let headerInstance: HeaderMap = new HeaderMap();
await headerInstance.add(GetRecordsHeader.IF_MODIFIED_SINCE, new Date("2020-01-01T00:00:00+05:30"));
let response: APIResponse<ResponseHandler> = 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: ResponseHandler = response.getObject();
if(responseObject != null){
if(responseObject instanceof ResponseWrapper){
let records: Record[] = responseObject.getData();
for (let record of records) {
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: Tag[] = record.getTag();
if(tags != null){
tags.forEach(tag => {
console.log("Record Tag Name: " + tag.getName());
console.log("Record Tag ID: " + tag.getId());
});
}
console.log("Record Field Value: " + record.getKeyValue("Last_Name"));
console.log("Record KeyValues: " );
let keyValues: Map<string,any> = record.getKeyValues();
let keyArray: string[] = Array.from(keyValues.keys());
for (let keyName of keyArray) {
let value: any = keyValues.get(keyName);
console.log(keyName + " : " + value);
}
}
}
}
}
} catch (error) {
console.log(error);
}
}
}
SampleRecord.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 SampleRecord.getRecords(moduleAPIName) will fetch records.
SDK Sample code
import {UserSignature} from "@zohocrm/typescript-sdk/routes/user_signature"
import {SDKConfigBuilder} from "@zohocrm/typescript-sdk/routes/sdk_config_builder"
import {DBStore} from "@zohocrm/typescript-sdk/models/authenticator/store/db_store"
import {FileStore} from "@zohocrm/typescript-sdk/models/authenticator/store/file_store"
import {SDKConfig} from "@zohocrm/typescript-sdk/routes/sdk_config"
import {Levels,Logger} from "@zohocrm/typescript-sdk/routes/logger/logger"
import {Environment} from "@zohocrm/typescript-sdk/routes/dc/environment"
import {USDataCenter} from "@zohocrm/typescript-sdk/routes/dc/us_data_center"
import { OAuthToken,TokenType } from "@zohocrm/typescript-sdk/models/authenticator/oauth_token"
import { Initializer} from "@zohocrm/typescript-sdk/routes/initializer"
import {RecordOperations, GetRecordsHeader, GetRecordsParam} from "@zohocrm/typescript-sdk/core/com/zoho/crm/api/record/record_operations";
import {ParameterMap} from "@zohocrm/typescript-sdk/routes/parameter_map";
import {HeaderMap} from "@zohocrm/typescript-sdk/routes/header_map";
import {ResponseWrapper} from "@zohocrm/typescript-sdk/core/com/zoho/crm/api/record/response_wrapper";
import {ResponseHandler} from "@zohocrm/typescript-sdk/core/com/zoho/crm/api/record/response_handler";
import {Record} from "@zohocrm/typescript-sdk/core/com/zoho/crm/api/record/record";
import {Tag} from "@zohocrm/typescript-sdk/core/com/zoho/crm/api/tags/tag";
import {APIResponse} from "@zohocrm/typescript-sdk/routes/controllers/api_response";
class SampleRecord {
public static async getRecords(){
let user: UserSignature = new UserSignature("abc@zoho.com");
let myLogger: Logger = Logger.getInstance(Levels.INFO, "/Users/user_name/Documents/ts_sdk_log.log");
let dc: Environment = USDataCenter.PRODUCTION();
let sdkConfig: SDKConfig = new SDKConfigBuilder().setAutoRefreshFields(false).setPickListValidation(true).build();
let store: FileStore = new FileStore("/Users/username/Documents/ts_sdk_tokens.txt");
let oauth: OAuthToken = new OAuthToken("clientId", "clientSecret", "REFRESH/ GRANT Token", TokenType.REFRESH/TokenType.GRANT);
let path: string = "/Users/user_name/Documents/ts-app";
await Initializer.initialize(user, dc, oauth, store, sdkConfig, path, myLogger);
try {
let moduleAPIName = "Leads";
let recordOperations: RecordOperations = new RecordOperations();
let paramInstance: ParameterMap = new ParameterMap();
await paramInstance.add(GetRecordsParam.APPROVED, "both");
let headerInstance: HeaderMap = new HeaderMap();
await headerInstance.add(GetRecordsHeader.IF_MODIFIED_SINCE, new Date("2020-01-01T00:00:00+05:30"));
let response: APIResponse<ResponseHandler> = 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: ResponseHandler = response.getObject();
if(responseObject != null){
if(responseObject instanceof ResponseWrapper){
let records: Record[] = responseObject.getData();
for (let record of records) {
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: Tag[] = record.getTag();
if(tags != null){
tags.forEach(tag => {
console.log("Record Tag Name: " + tag.getName());
console.log("Record Tag ID: " + tag.getId());
});
}
console.log("Record Field Value: " + record.getKeyValue("Last_Name"));
console.log("Record KeyValues: " );
let keyValues: Map<string,any> = record.getKeyValues();
let keyArray: string[] = Array.from(keyValues.keys());
for (let keyName of keyArray) {
let value: any = keyValues.get(keyName);
console.log(keyName + " : " + value);
}
}
}
}
}
} catch (error) {
console.log(error);
}
}
}
SampleRecord.getRecords();