Kaizen #20 - Node JS SDK

Kaizen #20 - Node JS SDK

Hello everyone!
Welcome to another week of Kaizen!
In today's post, we will discuss the Node JS SDK.

What is the Node JS SDK for Zoho CRM?
Node JS SDK allows you to create client Node JS applications that you can integrate with Zoho CRM, effortlessly. It serves as a wrapper for the REST APIs, thus making it easier to use the services of Zoho CRM.

What can you do with the Node JS SDK?
  • Exchange data between Zoho CRM and the client application where the CRM entities are modelled as functions.
  • Authenticate your application easily every time you sync data between Zoho CRM and your application, as the SDK takes care of generating the access/refresh tokens automatically.
How to start using the Node JS SDK?
Follow the below steps:
  • Step-1: Register your application (Self Client or Web-based client)
  • Step-2: Install the SDK
  • Step-3: Import the SDK in your project
  • Step-4: Initialize the SDK
    4.a. Choose the token persistence method
    4.b. Setup the configuration files or dictionary
    4.c. Generate the tokens
  • Step-5: Connect to Zoho CRM through the available functions

Let us now discuss these steps in detail.

Step-1: Register your application
All the Zoho CRM APIs are authenticated by the OAuth2.0 standards. It is mandatory to authenticate your application with Zoho.
You can register your application either as a Self Client (single user app) or a web-based app (multiple users app).

1.a. Self Client
  • Go to https://api-console.zoho.com.
  • Click ADD CLIENT
  • Choose the Client Type as Self Client, and click CREATE.
  • You will receive a client ID and a client secret upon successful registration.


1.b. Web-based Client
  • Go to https://api-console.zoho.com.
  • Click ADD CLIENT
  • Choose the client as Web based and click CREATE NOW.
  • Specify the client name, homepage URL of your application's UI, and a redirect URI to which you want to redirect the users after they grant consent to your application.
  • Click CREATE. Your Client ID and Client Secret will be displayed.


Step-2: Install the SDK
You can install the Node JS SDK through npm package manager. Run the below command.

npm install zcrmsdk

Run the below command to update your SDK to the latest version.

npm install --upgrade zcrmsdk
After the installation, a package named 'zcrmsdk' will be created in the node modules folder in your machine.

Step-3: Import the SDK in your project
Use the below statement in your code to import the downloaded SDK.

var ZCRMRestClient = require('zcrmsdk')

Step-4: Initialize the SDK 
Initializing the SDK involves the following steps.
  • Step 4.a - Choosing the token persistence method
  • Step 4.b - Setting up the oauth and configuration properties files
  • Step 4.c - Generating the tokens

4.a. Token Persistence
Your application should retain tokens (grant, access, and refresh tokens) to automate the process of data sync between your Node JS application and Zoho CRM.

You can choose to persist (store) the tokens in two ways.
      a. MySQL Persistence (default)
      b. Custom DB Persistence

a. MySQL Persistence
When you want to store the tokens in the MySQL DB, include the following keys in the configuration.properties file (discussed in the next section) or the configuration JSON array, along with other mandatory keys.

username=mysql_username
password=mysql_password

Note
When you use MySQL persistence, ensure that
  • MySQL runs in the same machine serving at the mentioned port (by default 3306).
  • There is a database named zohooauth.
  • There is a table name oauthtokens with the columns useridentifier (varchar(100)), accesstoken (varchar(100)), refreshtoken (varchar(100)) and expirytime (bigint).
b. Custom DB Persistence
To use custom DB persistence, you must write a custom implementation of the following functions:
  • getOAuthTokens() - This method returns the user identifier, access and refresh tokens, and their respective expiry time.
  • saveOAuthTokens(token_obj) - This method saves the access and refresh tokens, their respective expiry time. This method is called when you generate the access token through the grant token or the refresh token.
  • updateOAuthTokens(token_obj) - This method updates the access token and the expiry time every time an access token is refreshed. This method is called when the access token expires.

Include the absolute path of the file that contains the above methods in the following key of the configuration.properties file.

api.tokenmanagement=absolute_path_to _the_custom_implementation

The below images contain a sample of the custom implementation of the above three methods. You can find the code for the same as an attachment to this post.
This implementation of custom persistence creates a token file named zcrm_oauthtokens.txt and this file will contain the below keys with their values.

{"tokens": [{"access_token":"1000.xxxxx","expires_in":1582804396157,"user_identifier":"Patricia.boyle@abc.com","refresh_token":"xxx"}]}
getOAuthTokens()


updateOAuthTokens()


saveOAuthTokens()


Note
  • While updating the tokens, the next execution happens irrespective of the response. So, you must exercise care to handle this in your module.
  • All methods must return a Promise.
4.b. Configuration
You can set the configuration details in property files (oauth_configuration.properties and configuration.properties) or pass the details during run time as JSON key-value pairs.

oauth_configuration.properties
This file must contain the below client details.

[zoho]
crm.iamurl=accounts.zoho.com
crm.clientid=1000.xxxxxxx.6WJ
crm.clientsecret=99xxxxx0e16
crm.redirecturl=https://www.zoho.com

Where,
  • crm.iamurl - The domain-specific accounts URL from which you generate the grant token (authorization code). Possible domains are accounts.zoho.com (US), accounts.zoho.eu (EU), accounts.zoho.in (India), accounts.zoho.com.cn(China), accounts.zoho.com.au (Australia). The default value is accounts.zoho.com.
  • crm.clientid, crm.clientsecret - The client ID and client secret, respectively, you received while registering your application.
  • crm.redirecturl - The redirect URI you specified while registering your client. For self client apps, you can specify a dummy value for this key.
configuration.properties

This file must contain the below details.

[crm]
api.url=www.zohoapis.com
api.user_identifier=p.boyle@abc.com
[customDB]//If you want to use custom DB persistence
api.tokenmanagement=
[mysql]//If you want to use MySQL DB persistence
username=*****
password=*****

Where,
  • api.url - The domain-specific URL from which your app must make API calls to Zoho CRM. Possible URLs are www.zohoapis.com (US), www.zohoapis.eu (EU), www.zohoapis.in (India), www.zohoapis.com.cn(China), www.zohoapis.com.au (Australia). The default value is www.zohoapis.com.
  • api.user_identifier - The email ID of the current user.
  • api.tokenmanagement - The absolute or relative path to the file that contains the token storage mechanism. This key is mandatory for custom DB persistence.
  • username, password - The MySQL username and password, respectively. These keys are mandatory for MySQL DB persistence.
Note
Both these files must be placed under the resources folder of your project.

Config JSON Array
Instead of specifying the configuration details in properties files, you can choose to pass the details to the SDK during run time as JSON key-value pairs, as shown below.

var ZCRMRestClient = require('zcrmsdk');
var configJson={
        "client_id":"{client_id}",//mandatory
        "client_secret":"{client_secret}",//mandatory
        "redirect_uri":"{redirect_url}",//mandatory
        "user_identifier":"{user_identifier}",
        "mysql_username":"{mysql_username}",//optional ,"root" is default value
        "mysql_password":"{mysql_password}",//optional ,"" is default value
        "base_url":"{api_base_url}",//optional ,"www.zohoapis.com" is default value
        "iamurl":"{accounts_url}",//optional ,"accounts.zoho.com" is default value
        "version":"{api_version}",//optional ,"v2" is default value
        "tokenmanagement":"{token_management_module}"//optional ,mysql module is default
}
ZCRMRestClient.initialize(configJson).then(function()
{
//do whatever required after initialize
})

Now that you have created and registered your app with Zoho, you must authenticate it. 

4.c. Generating the tokens
As the V2 Zoho CRM APIs follow the OAuth2.0 protocol, it is mandatory to authorize the OAuth2.0 app before using the SDK functions with an access token.
You can generate an access token from a grant token.
You can generate the grant token in two ways based on the type of client.

For Self Client Applications
  • Log in to Zoho and go to Zoho Developer Console.
  • Select your Self Client.
  • Provide the necessary scopes separated by commas, along with the scope aaaserver.profile.READ
  • Select the Time Duration from the drop-down. This is the time the grant token is valid for.
  • Provide a description for the scopes. Click GENERATE.
  • Copy the grant token.
For Web-based Applications
It is the responsibility of your client app to generate the grant token for the users trying to login.
Your Application's UI must have the Login with Zoho option to open the grant token URL of Zoho, which would prompt for the user's OAuth2.0 authorization.
Upon the successful login of the user, the grant token will be sent as a parameter to your registered redirect URL.

Generating an access token from the grant token
Use the below code snippet in your main class.

ZCRMRestClient.generateAuthTokens(user_identifier,grant_token).then(function(auth_response){
console.log("access token :"+auth_response.access_token);
console.log("refresh token :"+auth_response.refresh_token);
console.log("expires in :"+auth_response.expires_in);
});

Note
  • The code snippet to generate the access token from the grant token is valid only once per grant token. If the grant token expires before you generate the access token, you must generate a new grant token only.
  • Generating access and refresh tokens is a one-time process. After the tokens are generated the first time, the SDK persists them based on the keys defined in the configuration dictionary or the properties file, and refreshes the access token as and when required.

Step-5: Connect to Zoho CRM through the available methods

Here is a sample to insert a lead. You can find the code for this sample in the attachment.



The isTokenGenerated Method

You need to add this method to check if the access token has already been generated or not. It returns a Boolean value.

true - The access token has already been generated. 
false - The access token has not been generated previously, thus, it shifts the control to the code snippet that leads to access token generation.

For more sample codes, refer to REST API samples.


We hope you found this post useful. Stay tuned for more!
Cheers!




    Access your files securely from anywhere

          Zoho Developer Community




                                    Zoho Desk Resources

                                    • Desk Community Learning Series


                                    • Digest


                                    • Functions


                                    • Meetups


                                    • Kbase


                                    • Resources


                                    • Glossary


                                    • Desk Marketplace


                                    • MVP Corner


                                    • Word of the Day



                                        Zoho Marketing Automation


                                                Manage your brands on social media



                                                      Zoho TeamInbox Resources

                                                        Zoho DataPrep Resources



                                                          Zoho CRM Plus Resources

                                                            Zoho Books Resources


                                                              Zoho Subscriptions Resources

                                                                Zoho Projects Resources


                                                                  Zoho Sprints Resources


                                                                    Qntrl Resources


                                                                      Zoho Creator Resources



                                                                          Zoho Campaigns Resources


                                                                            Zoho CRM Resources

                                                                            • CRM Community Learning Series

                                                                              CRM Community Learning Series


                                                                            • Kaizen

                                                                              Kaizen

                                                                            • Functions

                                                                              Functions

                                                                            • Meetups

                                                                              Meetups

                                                                            • Kbase

                                                                              Kbase

                                                                            • Resources

                                                                              Resources

                                                                            • Digest

                                                                              Digest

                                                                            • CRM Marketplace

                                                                              CRM Marketplace

                                                                            • MVP Corner

                                                                              MVP Corner





                                                                                Design. Discuss. Deliver.

                                                                                Create visually engaging stories with Zoho Show.

                                                                                Get Started Now


                                                                                  Zoho Show Resources


                                                                                    Zoho Writer Writer

                                                                                    Get Started. Write Away!

                                                                                    Writer is a powerful online word processor, designed for collaborative work.

                                                                                      Zoho CRM コンテンツ






                                                                                        Nederlandse Hulpbronnen


                                                                                            ご検討中の方





                                                                                                  • Recent Topics

                                                                                                  • Pulling Specific Products from Sales Orders in Books to a CRM Record

                                                                                                    We currently process orders directly through our website (woocommerce) as well as through manual sales orders in zoho books. When an order comes through the website, all of the individual products from that order show up in the CRM record of that customer.
                                                                                                  • Você já viu os cursos do Zoho Mind?

                                                                                                    Pessoal, Tem uma plataforma da Zoho chamada Zoho Mind, muito interessante os cursos e vídeos tutoriais que lá possui. Para a turma do Zoho Creator, tem uma dica de Buscar dados em Formulário, segue o link e clique em Zoho Creator. https://www.zohomind.com.br/#/videostutoriais
                                                                                                  • Como gerar gatilhos para pagamento de impostos no Zoho Books?

                                                                                                    Olá Pessoal, boa tarde! Gostaria de saber como vocês estão escriturando os impostos a pagar no Zoho Books. Vi que temos a opção de Bills, porém se eu escriturar nesta aba do Zoho Books para gerar lembretes de tempo de vencimento por exemplo vai refletir
                                                                                                  • Subform Time field to string.

                                                                                                    Good afternoon All. I have a Subform 'Delivery_Receiving_Hours' that captures Day (Dropdown), Time_Open (Time), and Time_Close (Time). I need to capture this data and send it to a multiline field in the CRM. The code, posted below, below will capture
                                                                                                  • workflow for bounced email gets triggered, but email is status = opened

                                                                                                    Hello, I have a workflow that sends me an email if outgoing email are bounced. Now I got some kind of this emails, but the corrosponding contacts have status = open at the email. Why this bounce-workflow is triggered? Reports > Email Reports > Bounce
                                                                                                  • Data export

                                                                                                    I need to export our customer's data and projects' data for our purpose but am unable to export full data i only get around 3160 projects and around 2k customer can you please help me to get full data, please
                                                                                                  • Adjusting Physical Inventory

                                                                                                    Not getting very far with support on this one, they say they are going to fix it but nothings happened since November. Please give this a thumbs up if you would like to see this feature or comment if you have some insight. Use Case: Inventory set to be
                                                                                                  • Zoho Marketing Plus : Un outil tout-en-un pour la création de pages, la collaboration et la gestion du calendrier marketing

                                                                                                    Nous sommes ravis de vous présenter trois nouvelles fonctionnalités puissantes de Zoho Marketing Plus s’enrichit désormais d’un page web (l'éditeur de pages), qui vous permet de créer des pages attrayantes et à fort taux de conversion pour vos campagnes
                                                                                                  • Grouping payments to match deposits

                                                                                                    Is there a way to group multiple invoice payments together so they match credit card batches and grouped deposits in the bank account? Basically, we are creating invoices for each of our transactions, and applying a payment to each of the invoices. Our payments are either credit cards or checks. We want to be able to group payments together so when our bank account reflects a credit card batch made up of many transactions, or the deposit we took to the bank that has multiple checks from different
                                                                                                  • Employees can not add some expenses suddenly

                                                                                                    Zoho expense was working fine and whenever there was a new merchant, it would automatically add and also the same auto added in Zoho Books (due to merchant-vendor sync) untill now. From today, it is having problems in searching the existing vendors and
                                                                                                  • Zoho email setup in office365

                                                                                                    When i am trying to setup zoho mail setup using my domain in office365 and it is not working and it says that we couldn't log on to the incoming (IMAP) server and please check your email address and password and try again. I was able to login using my
                                                                                                  • iOS 10: Caller ID new feature?

                                                                                                    Hi, in the update history of the iOS App (for iOS10) - v.3.2 - i found the point "caller identification" has this feature been deactivated again? i cannot find anything on my iphone on how to activate this feature. or does it just work from the beginning?
                                                                                                  • Recommendations to store meeting notes for easy access from Contacts, Accounts & Deals module records?

                                                                                                    I would like your advice on how to achieve this use case for my organization. It’s related to where/how best to store meeting notes from a conversation with Contact(s) working at an Account (Company) in the context of a Deal. The ideal solution (from
                                                                                                  • Bank reconciliation. Match Transaction -filter

                                                                                                    When matching an imported bank statement file we only get a match if it is an excact match on both amount and date. Then a suggestions comes up with a very broad selection regarding amount, and no default "between" dates. I can then go an manually adjust the filter, and have to put in from-to amounts and dates. How do I set a default from-to date?  As an example, I would like the date to be +- 3 days, Thanks.
                                                                                                  • Added new staff but does not appear in other organization list

                                                                                                    Hi, I added the new staff under Sales Manager in the contacts, but it does not appear in the other organization list where I need to create a contact, and I can't select the newly added Sales Manager
                                                                                                  • Integrating Calendly with Zoho Calendar in Zoho Mail

                                                                                                    I moved my office into a business incubator space that uses Calendly for meeting management and events. Calendly doesn't have a integration with Zoho Calendar and vice versa. I was directed to Zapier for integration but it doesn't have an integration
                                                                                                  • Map fields from module X to a lookup field in subform in module Y

                                                                                                    Hi there In the 1st screenshot attached, you can see a subform in myLeads module. You can see that there is a number already filled there - that is the 'Property ID' and it is a single line field. It is the 'Property ID' of an entry I have in another
                                                                                                  • 🎄 Jingle, Mingle, and Automate: Spread Christmas Cheer with Zoho Desk Auto-Replies! 🎄

                                                                                                    Hello Everyone! Welcome to this week's episode of the Community Learning Series. Christmas is in the air, and I’m sure we can all feel the jingle and the mingle of the season! The folks at Zylker Techfix are no exception—they’re busy with holiday plans
                                                                                                  • how to create a new line in string in Client Script?

                                                                                                    I want to show an alert using client script, I need to add a new line in String, I assume I can use \n\n inside a string, but unfortunately it doesnt work ZDK.Client.showAlert("First Line \n\nI expect this is in second line");
                                                                                                  • Surely it's time Inline editing from views

                                                                                                    I think the first request I found for in-line editing from grids was approximately 12 years ago - that post was locked because it was suggested Zoho sheetview solved the problem. However, it's now 2024, and in-line editing from grids is just a basic expectation.
                                                                                                  • Multi branding issue with sender addresses

                                                                                                    Hello, I'm currently working on a project involving two (seperate) brands. Named 'Windeck' and 'Prolance'. They've chosen CRM Plus and I'm currently working on CRM, SalesIQ, Social and Marketing Automation. So far, I'm able to make enough separations
                                                                                                  • How to Replace an Assessment in a Job Opening on Zoho Recruit

                                                                                                    Hi everyone, I’m currently using Zoho Recruit and would like to replace the assessment linked to a specific job opening. I want to remove the existing assessment and add a new one. What is the best way to do this without losing any important data or affecting
                                                                                                  • Is there API Doc for Zoho Survey?

                                                                                                    Hi everyone, Is there API doc for Zoho Survey? Currently evaluating a solution - use case to automate survey administration especially for internal use. But after a brief search, I couldn't find API doc for this. So I thought I should ask here. Than
                                                                                                  • Email Campaigns overview page is missing SENT DATE and # people sent to!

                                                                                                    I would like to see the date the email campaign was sent, so I can understand and track when each email campaign was sent. Right now, unless you go to a contact who received a campaign, you cannot see when the campaign was sent (!!!!!!). So, if my boss
                                                                                                  • SEO recommendation of H1 tag for website tittle

                                                                                                    The exact words are “ It is good practice to place the page title inside the H1tag.” Now I already have one H1 tag on my website but it is not website tittle. In the SEO recommendation that is clear too that I have h1 tag on my page. Now I don’t know
                                                                                                  • How to choose other payment methodes than creditcards

                                                                                                    We have connected stripe as a payment provider in zoho books, booking, commerce and checkout. In stripe we selected al major payment methodes for Belgium (mainly bancontact). However, at checkout customers seems to have only the possibility to pay with
                                                                                                  • Introducing Zia LLM: Zoho’s in-house Generative AI solution for CRM's AI capabilities

                                                                                                    Hello everyone, We're excited to announce the launch of our in-house Large Language Model (LLM) by Zia to power our AI offerings. What is LLM? LLM stands for Large Language Model, a powerful AI technology that processes and generates human-like text based
                                                                                                  • How to call a Creator function which is in a different Creator application?

                                                                                                    How to call a Creator function which is in a different Creator application?
                                                                                                  • Can the code in my "Successful form submission" WF be invoked from a function?

                                                                                                    Can "Successful form submission" be invoked from a function? Data gets into a form manually and programatically. My code in "successful form submission" is good and I want to reuse it/call it, from another function which does Insert Into How to achieve
                                                                                                  • Kaizen #169 - Serialization and Schema Management in Queries

                                                                                                    Hello everyone! Welcome back to another post in the Kaizen series! In Kaizen #166, we discussed handling Variables in Queries and associating the query in Kiosk. This week, we will discuss Serialization and Schema management in Queries. Business Scenario
                                                                                                  • Introducing Keyboard Shortcuts for Zoho CRM

                                                                                                    Dear Customers, We're happy to introduce keyboard shortcuts for Zoho CRM features! Until now, you might have been navigating to modules manually using the mouse, and at times, it could be tedious, especially when you had to search for specific modules
                                                                                                  • Feature Request: Notebooks within notebooks (Tree-like structure)

                                                                                                    Dear Zoho! I already migrated all my stuff from Google Keep, Im really fond of Zoho Notebook so far. One thing that could make the service much more powerful is multi-level notebooks (or tree like structure). For example, entering into Notebook named
                                                                                                  • Can't get authorization for Sandbox environment using the self client

                                                                                                    Hello, After creating a self client, and following the client-credentials method (as it's not optimat to manually generate a code for every 10 minutes), after inputting the sandbox org id for SOID parameter, im getting the error: "error": "no_org". For
                                                                                                  • Create landing pages from Zoho Marketing Plus

                                                                                                    Hey everyone, Over the last few months, we've introduced various features and enhancements to bolster the marketing capabilities of Zoho Marketing Plus and make it simpler for everyone. To that end, we're excited to announce that Zoho LandingPage is now
                                                                                                  • Custom service report or Zoho forms integration

                                                                                                    Hello, So far the experience with Zoho FSM and the integration with Books has been good, however there are limitations with service reports. As with my business, many organisations send technicians to different types of jobs that call for a different
                                                                                                  • Email tracking subdomain

                                                                                                    The Email Tracking configuration screen of the ZeptoMail asks for a subdomain. I have gone through the documentation but could not find more information about how that subdomain is used by ZeptoMail to track the emails. Can someone throw some light about
                                                                                                  • Chart View group X-axis values above a value

                                                                                                    I have a data set with X values ranging from 0 up to 300-400, the Y values are an AVG of the values for the given X. I am interested in the values at the low end of the scale, say 0-10 and want the X values 10 and greater to be grouped into a single category
                                                                                                  • How do I get the Text Account name instead of the Reference number?

                                                                                                    Good Morning everyone! I am very new to zoho analytics. I'm trying to create some pivot tables and when I add the Account or Division name it comes up as a reference number. From my research, I need to use a lookup. I'm having a really hard time understanding
                                                                                                  • Custom API - Need to create a string return value, not only MAP

                                                                                                    @Support: When creating a Custom API it only allows a return from a function of MAP type. The service I'm using requires a string return, how can this be achieved?
                                                                                                  • missing video-urgent

                                                                                                    hi..I have a problem regarding zoho meeting. I already record almost 2hrs for my interview session. After end my session, i'm stop the recording. Its happened when i didn't received any meeting recording at my email.But i received recording 7minutes after
                                                                                                  • Next Page