Hello and welcome to another Kaizen week!
In this week's post, we'll show you how to get started with Zoho CRM's PHP SDK, and walk you through the configuration and initialization process.
PHP Software Development Kit
PHP SDK allows you to create client PHP applications that can be integrated with Zoho CRM effortlessly. It serves as a wrapper for the
REST APIs, thus making it easier to use the services of Zoho CRM.
Why PHP SDK?
Easy authentication: You don't have to worry about manually managing authentication because the PHP SDK takes care of generating access/refresh tokens for you.
Easy and Efficient data exchange: With the PHP SDK, you can easily exchange data between Zoho CRM and your client PHP application, where the CRM entities are modelled as classes. You can declare and define CRM API equivalents as simple functions in your PHP application.
Prerequisites
- The client app must have PHP 7 or above with a cURL extension. cURL extension is used to connect and communicate with the Zoho CRM APIs.
- The client app must have the PHP SDK installed through Composer.
How to start using the PHP SDK?
- Prerequisite : Register your application with Zoho CRM.
- Install the PHP SDK.
- Knowledge Base : Token Persistence
- Configuration
- initialization.
1. Register your application with Zoho CRM
Registering your application with Zoho CRM is a mandatory step in order to authenticate and authorize API calls using the OAuth2.0 standards.
- Go to https://api-console.zoho.com
- Click on Get Started or +ADD CLIENT.
- Choose the Client Type.
- Fill in the necessary details and click CREATE. Once you successfully register your self-client, you will receive a Client ID and Client Secret.

2. Install PHP SDK
1. Install Composer, if not already installed. Please check the corresponding link for installation instructions.
2. Install PHP-SDK using Composer
3. To use the SDK in your project, add the following line in your project PHP files. This loads and includes our PHP-SDK library in your project. If you skip this step, you will get a fatal error in response due to the missing libraries.
require 'vendor/autoload.php'; |
3. Token Persistence
Token persistence refers to storing and utilizing authentication tokens provided by Zoho, enabling the SDK to refresh the access tokens without the need for user intervention. The SDK offers three types of persistence - File, DB, and Custom - with file persistence being the default method.
The persistence is achieved by writing an implementation of the inbuilt TokenStore interface, which has the following callback methods.
Method | Description |
getToken($user, $token) | Invoked before firing a request to fetch the saved tokens. This method returns an implementation of Token interface object for the library to process it. |
saveToken($user, $token) | Invoked after fetching access and refresh tokens from Zoho. This method saves the token details. |
deleteToken($token) | This method is used to delete the given token details. |
getTokens() | This method is used 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 the unique ID. |
a. Token Persistence using a Database
Database persistence is a technique that involves storing and retrieving data from a database. If you prefer using database persistence, you can use MySQL.
Create a table in your database with the required columns. For example, if you want to persist your tokens in a table named token in database named zoho, use the following:
CREATE DATABASE zoho; // use this to create database named zoho // use this to create a table named token, with the necessary columns CREATE TABLE token ( 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) ); |
In this example, your tokens will be persisted in the token table in your zoho database.
b. File Persistence
File Persistence allows storing and retrieving the authentication tokens from the given file path. The file contains
id, user_mail, client_id, client_secret, refresh_token, access_token, grant_token, expiry_time and
redirect_url. c. Custom Persistence
Custom Persistence refers to a technique where users can create their own method of storing and retrieving authentication tokens. To use this method, users need to implement the TokenStore interface and override its methods according to their own logic.
4. Configuration
Configuration is a critical step in which you set up SDK's configuration details like user authentication, token persistence, logging and API call timeout settings, and more. Listed below are the keys that you define in this step.
Key | Description |
| Represents the mail id, which is used to identify and fetch tokens from the File or DB. |
| Represents the data centre details in Domain::Environment pattern. Domains : USDataCenter, EUDataCenter, INDataCenter, CNDataCenter, AUDataCenter Environments : PRODUCTION(), DEVELOPER(), SANDBOX() |
| Contains user token details. Depending on the tokens, you can choose grantToken flow, refreshToken flow or accessToken flow. |
| Contains the configuration for logging exceptions and API call information. By default, the logs will be available in the workspace as sdk_logs.log. |
| Contains details for the Token Persistence object. You can choose between DB Store, File Store or Custom Store, and configure accordingly. |
| Contains additional configuration details like timeout, autorefresh fields, picklistvalidation, etc |
| Contains the details of the proxy, if you are using a proxy server to authenticate and make the API calls. |
| The path containing the absolute directory path to store user specific files containing the module fields information. |
Let us discuss how to configure each of them, in detail.
a. user : The user key will be used to store and identify the tokenstore details in the DB or File Storage for token persistence. Create an instance of UserSignature that identifies the current user with the following :
b. environment : The API environment which decides the domain and the URL to make API calls.
- $environment = USDataCenter::PRODUCTION();
c. token : Create an instance of OAuthToken with the information that you get after registering your Zoho client. Depending on the tokens available with you, you can choose one of the following flows.
Note : You need to generate the tokens (grant/access/refresh) beforehand.
d. logger : Create an instance of Logger Class to log exception and API information. You can set the level you want to log (FATAL, ERROR, WARNING, INFO, DEBUG, TRACE, ALL, OFF), and also configure the file path and file name for the log file.
$logger = (new LogBuilder()) ->level(Levels::INFO) ->filePath("/Documents/php_sdk_log.log") ->build(); |
e. store : Configure your token persistence using this method. If this is skipped, the SDK creates the sdk_tokens.txt in the current working directory to persist the tokens by default.
Custom Store - In this method, you can implement your own method for storing and retrieving the tokens. Please note that to do so, you must implement the TokenStore interface, and override its callback methods (getToken, saveToken, deleteToken, getTokens, deleteTokens, getTokenById).
$tokenstore = new CustomStore(); |
Note : The corresponding storage will have id, user_mail, client_id, client_secret, refresh_token, access_token, grant_token, expiry_time and redirect_url. The id is a unique system generated key.
f. SDKConfig : The additional SDK configurations are taken care of with this method.
Configuration Key | Description |
autoRefreshFields Default Value : False | A boolean configuration key to enable or disable automatic refreshing of module fields in the background. If set to true, fields are refreshed every hour, and if set to false, fields must be manually refreshed or deleted. |
pickListValidation Default Value : True | This field enables or disables pick list validation. If enabled, user input for pick list fields is validated, and if the value does not exist in the pick list, the SDK throws an error. If disabled, the input is not validated and the API call is made. |
enableSSLVerification Default Value : True | A boolean field to enable or disable curl certificate verification. If set to true, the SDK verifies the authenticity of certificate. If set to false, the SDK skips the verification. |
connectionTimeout Default Value : 0 | The maximum time (in seconds) to wait while trying to connect. Use 0 to wait indefinitely. |
| The maximum time (in seconds) to allow cURL functions to execute. Use 0 to wait indefinitely. |
- $autoRefreshFields = false;
- $pickListValidation = false;
- $enableSSLVerification = true;
- $connectionTimeout = 2;
- $timeout = 2;
- $sdkConfig = (new SDKConfigBuilder())
- ->autoRefreshFields($autoRefreshFields)
- ->pickListValidation($pickListValidation)
- ->sslVerification($enableSSLVerification)
- ->connectionTimeout($connectionTimeout)
- ->timeout($timeout)
- ->build();
g. requestProxy : Create an instance of RequestProxy containing the proxy properties of the user. Configure this only if you're using a proxy server to make the API calls.
$requestProxy = (new ProxyBuilder()) ->host("proxyHost") ->port("proxyPort") ->user("proxyUser") ->password("password") ->build(); |
h. resourcePath : Configure path containing the absolute directory path to store user specific files containing module fields information.
$resourcePath = "/Documents/phpsdk-application"; |
5. Initilization
Once you have completed the configuration process, you can move on to initializing the SDK and begin making API requests.
Here is a sample code to initialize the SDK, using refresh token flow and DB Persistence.
<?php use com\zoho\api\authenticator\OAuthBuilder; use com\zoho\api\authenticator\store\DBBuilder; use com\zoho\api\authenticator\store\FileStore; use com\zoho\crm\api\InitializeBuilder; use com\zoho\crm\api\UserSignature; use com\zoho\crm\api\dc\USDataCenter; use com\zoho\api\logger\LogBuilder; use com\zoho\api\logger\Levels; use com\zoho\crm\api\SDKConfigBuilder; use com\zoho\crm\api\ProxyBuilder; use com\zoho\api\authenticator\store\DBBuilder;
require_once "vendor/autoload.php";
class Initialize { public static function initialize() { $environment = USDataCenter::PRODUCTION(); $token = (new OAuthBuilder()) ->clientId("1000.xxxxxxxxxxxxxxxx") ->clientSecret("554a9776d10ff016a92c1eb01xxxxxxxxxx") ->refreshToken("1000.xxxxxxxxxxxxxxxxxxxx") ->build(); $logger = (new LogBuilder()) ->level(Levels::INFO) ->filePath("/Documents/php_sdk_log.log") ->build(); $tokenstore = (new DBBuilder()) ->host("insert_your_hostname_here") ->databaseName("insert_your_database_name_here") ->userName("insert_your_db_username_here") ->password("insert_your_db_password_here") ->portNumber("insert_your_portnumber_here") ->tableName("insert_your_table_name_here") ->build(); $autoRefreshFields = false; $pickListValidation = false; $connectionTimeout = 2; $timeout = 2; $sdkConfig = (new SDKConfigBuilder()) ->autoRefreshFields($autoRefreshFields) ->pickListValidation($pickListValidation) ->sslVerification($enableSSLVerification) ->connectionTimeout($connectionTimeout) ->timeout($timeout) ->build(); $resourcePath = "/Documents/phpsdk-application"; $requestProxy = (new ProxyBuilder()) ->host("proxyHost") ->port("proxyPort") ->user("proxyUser") ->password("password") ->build(); (new InitializeBuilder()) ->user($user) ->environment($environment) ->token($token) ->store($tokenstore) ->SDKConfig($configInstance) ->resourcePath($resourcePath) ->logger($logger) ->requestProxy($requestProxy) ->initialize(); } } ?> |
You are now all set to explore the functionalities of SDK. Here is a sample code to get the records from Leads module, with the ifmodifiedsince header.
<?php use com\zoho\api\authenticator\OAuthBuilder; use com\zoho\crm\api\dc\USDataCenter; use com\zoho\crm\api\InitializeBuilder; use com\zoho\crm\api\UserSignature; use com\zoho\crm\api\record\RecordOperations; use com\zoho\crm\api\record\GetRecordsHeader; use com\zoho\crm\api\HeaderMap; use com\zoho\crm\api\ParameterMap; require_once "vendor/autoload.php";
class Record { public static function initialize() { $environment = USDataCenter::PRODUCTION(); $token = (new OAuthBuilder()) ->clientId("1000.xxxxxxx") ->clientSecret("4b5baxxxxxxxxxxxxf") ->grantToken("1000.xxxxx") ->build(); (new InitializeBuilder()) ->user($user) ->environment($environment) ->token($token) ->initialize(); }
public static function getRecords() { $recordOperations = new RecordOperations(); $paramInstance = new ParameterMap(); $headerInstance = new HeaderMap(); $ifmodifiedsince = date_create("2022-06-01T12:00:00+05:30")->setTimezone(new \DateTimeZone(date_default_timezone_get())); $headerInstance->add(GetRecordsHeader::IfModifiedSince(), $ifmodifiedsince); $response = $recordOperations->getRecords("Leads", $paramInstance, $headerInstance); echo($response->getStatusCode() . "\n"); print_r($response); } } Record::initialize(); Record::getRecords(); |
Next week, we will dive deeper and provide more sample codes to help you further. Stay tuned!
If you have any queries, let us know the comments below, or drop an email to
support@zohocrm.com. We would love to hear from you.

Recent Topics
How to create auto populate field based on custom module in Zoho CRM?
Hello, i'm still new to Zoho CRM and work as administrator in my company. Currently, I'm configuring layout for Quotes Module. So, the idea is, I've created a read-only field in Quotes called "Spec". I want this field automatically filled with Specification
Rich Text For Notes in Zoho CRM
Hello everyone, As you know, notes are essential for recording information and ensuring smooth communication across your records. With our latest update, you can now use Rich Text formatting to organize and structure your notes more efficiently. By using
Change Last Name to not required in Leads
I would like to upload 500 target companies as leads but I don't yet have contact people for them. Can you enable the option for me to turn this requirement off to need a Second Name? Moderation update (10-Jun-23): As we explore potential solutions for
Office 365 and CRM mail integration: permission required
Has anyone run into this weird problem? My email server is Office 365. When I try to configure Zoho CRM to use this server, a Microsoft popup window opens requesting user and password. After entering that, I get a message in the Microsoft window saying
Tables improvement ideas / features
Heya, I've been using Zoho Tables for a few months now and wanted to post some features that I think will be greatly beneficial for the tool: 1. Ability to delete a record in automation or move a record in automation. - Usecase: I move a record from one
Deluge - Can't get phone number SalesIQ
Hey folks, I’m building a custom plug for SalesIQ that’s supposed to register leads into Zoho CRM. The SalesIQ chat is being implemented on WhatsApp, and in my plug I’m using this line: mobile_clean = session.get("phone").get("value"); From what I understand,
Zoho Desk - Community
As a regular user of Zoho Cares Community I would really love to see the publish date of articles. For example, when I look at Announcements, it would be very beneficial to see which ones were posted recently, over those which have just and a recent comment.
access to quartz for my customers
Hi how can I have access to the application quartz you use for us to send you screen rocording, this feature would be immensely useful for our customers support https://quartz.zoho.com/
Issue with Inline Images in Email Reply via Zoho Desk API
Hi, I am attempting to send inline images in an email reply using the Zoho Desk API, but the images are not being displayed inline for the recipient. I have followed this documentation: https://desk.zoho.com/DeskAPIDocument#Uploads https://desk.zoho.com/DeskAPIDocument#Threads#Threads_SendEmailReply
How to search a value stored in a subform?
Hello, We store serial numbers in subforms but now we would like to be able to search the values to be able to easily find the record with the serial number. I saw that it's not possible to search such values through global search but is it possible to do it an other way? Thank you,
Field Dependency Not Working on Detail Page in Zoho Desk
Hi Support Team, I’ve created field dependencies between two fields in Zoho Desk, and they are working correctly on the Create and Edit layouts. However, on the Detail page, the fields are not displaying according to the dependencies I’ve set — they appear
How do the keyword critera work?
Hi, I'm working on automated assignment of tickets based on keywords. How does this feature work? Where does this criteria look for keywords - email address, subject, email body? Can you please clarify this as I want to avoid overlapping with criteria
Error: Unsupported content type: text/html;charset=UTF-8 after tryeing to get the token for n8n automation
I am working on ZOHO Desk automation and need to get the ZOHO auth token for n8n I have created the app in ZOHO Desk API, got client id and client secret. Added all data required to get a token in n8n. After I sign in with my ZOHO credentials in ZOHO
Improving Collaboration Features in Zoho Portal
Hello Zoho Community, I’ve recently started exploring Zoho services and I’m really impressed with the wide range of features. However, I feel there is still room for improvement in the collaboration area. For example, it would be really helpful if we
Automated Shopify Emails Not Being Delivered
I have an ecommerce store with Shopify. I recently set up my email to be served through Zoho. Since doing this, customers are not receiving some of our automated emails from Shopify itself. Our initial email that confirms their purchase goes through but our Shipping Notification that is automatically sent out upon fulfillment is not going through. Sometimes we get a notice that it's been classified as spam, sometimes nothing. I can send/receive email via Outlook on my desktop and I can send/receive
I can't log in to my account on Thunderbird
I've just had to rebuild my PC (calamitous mess from Microsoft with Win10/Win 11 'upgrade' - they confirmed I had to start with a new build). I have used Zoho mail for years via Mozilla Thunderbird, but now I've had to download the latest version of TBird,
Send a campaign to one recipient.
Very often I speak to a customer and they say they didn't see my email (maybe it went in Junk, maybe they deleted it). Anyway, I just want to go into the Campaign and send it to one person. You already have a feature very close to this - when sending a Test. While developing a campaign, I can send tests to anyone. Why can't we have this AFTER the campaign has been sent? I know, there's a caveat, and that's in the use of merge tags. Most of the time I only use FNAME, but maybe you could check if
Try FSM again for our business
We already have our customers individual equipment in CRM with serial numbers, install dates, warranty length and importantly next service which is generally 2 years. a month before the service date is due we get get a report and send out service reminders.
Use Zoho Books to bill for work done in Zoho Desk??
I'm trying to see if something is possible (and if yes, how). We use Zoho One to manage our business. We have a lot of clients that will put in a ticket (via portal) to have work done. Out techs will pick up the ticket, do the work, and then log the time
Get Cliq Meetings in my O365 calendar
Hi, we are currently evaluating to replace the Teams Messaging and Meetings with Cliq. We currently still have all our email and calendars in O365. What i want to achieve is, to create a (ZOHO) meeting from Cliq and have this meeting added to my Outlook/O365
Issue with Zoho Help Portal – Tickets Missing or Not Answered
Hi, How are you? I think there may be an issue with the Zoho Help Portal. I opened a few tickets directly in the help portal a some time ago but never received any response I also opened ticket 148356451 by email. I did receive a reply to it, but the
DUNS & Bradstreet and Credit risk monitoring integration with Zoho books
Small businesses not being paid by bigger clients and clients of all sizes is a huge problem. It will be nice if Zoho develops integration with DUNS & Bradstreet(D&B) and Credit risk monitoring integration with Zoho books. That have small businesses can
Zoho Forms - Form Rules based on attachment fields
Many businesses use forms to collect documents and images from customers. In many cases, you may want to trigger a notification or other automation based on whether or not an attachment was added. I've noticed that attachment fields do not appear in Rules
Add multiple users to a task
When I´m assigning a task it is almost always related to more than one person. Practical situation: When a client request some improvement the related department opens the task with the situation and people related to it as the client itself, the salesman
Can't open draft email for editing
Last night I started composing an email and I let it save in drafts. This morning I want to continue working on the email. It is in my Drafts folder but it will not open. The only option there is to delete it. This is not the first time it has happened. On previous occasions I have just deleted the draft and started afresh, but I really want this one back. Windows 10 with Pale Moon 28.10.0 browser.
Open filtered deals from campaign
Do you think a feature like this would be feasible? Say you are seeing campaign "XYZ" in CRM. The campaign has a related list of deals. If you want to see the related deals in a deal view, you should navigate to the Deals module, open the campaign filter,
Change scheduling emails time
When sending an individual email there is a great feature to schedule them to send later. I could only use the one time that is suggested. Is there a way to select another time? Regards, Glenn
Zoho CRM: how can I control which contacts to sync with Outlook?
I was just playing around syncing contacts from Zoho to MS Outlook (MS365 account.) The problem is our firm has hundreds of thousands of contacts and I don't want to bury my contacts list in outlook. Any help with this is greatly appreciated.
How to overcome limitations in meetings
As a company, one of our deliverables is a meeting between two other companies, where we act as facilitators. So, if we recorded this meeting in Zoho CRM, it should be connected to 2 accounts, 2 contacts, and 1 campaign (a campaign, in our use, is the
Different MRP / Pricing for same product but different batches
We often face the following situations where MRP of a particular product changes on every purchase and hence we have to charge the customer accordingly. This can't be solved by Batch tracking as of now so far as I understand Zoho. How do you manage it as of now?
Add a 'Log a Call' link to three dot icon in Canvas
Hi, There's a three dot element when creating a canvas called 'More'. I would like to modify this to add a link that says 'Log a Call' in order to quickly record the details of a cellphone call. I'd also like this to be a simple 'contact' selection and
Syncing Zoho Forms with Bigin - Embedding issue?
Hello everyone, I created a Zoho Form for a page on my GoDaddy website to collect leads, which then transfers the data to Bigin. However, I'm facing an issue where it doesn't seem to work properly. I've integrated Zoho Forms with Bigin and tried embedding
Can not add fields to a Section
I feel like I'm missing something obvious: I can add new Sections to my form but I can not add fields to the Sections. I've tried fields already on the form as well as dragging and dropping new fields into the Section but nothing will go into it. What
Record Logged in User while using CRM lookup field
Is it possible, while using the Zoho CRM lookup field, to automatically use the user account logged into Zoho CRM in a hidden field? I was hoping to add employee accounts to my current plan. But would like a record on the Form submission of who submitted
Form Rules for Suburb Categories to alternate landing pages or Making a Fields Contents ALL CAPS
I need to send differentform submissions to two to three different thank-you URLs (for Meta/Google pixels) depending on which suburb a user selects in a form. I have ~400 suburbs split into two categories (A and B, based on business value). Current challenges:
Collaps Notes
There are times when long/large notes are added to a record i.e. Accounts or Deals etc. Currently, the full note is displayed in the notes related list section. It would be great if by default only 5 to 10 rows of the note are displayed when the note
Zoho Down
I have a drop in my Zoho One services.
Runing RPA Agents on Headless Windows 11 Machines
Has anyone tried this? Anything to be aware of regarding screen resolution?
Problem for EU users connecting Zoho CRM through Google Ads for Enhanced conversions
Has anyone else experienced this problem when trying to connect Zoho CRM through Google Ads interface to setup enhanced conversions? Did you guys get it fixed somehow? The Problem: The current Google Ads integration is hardcoded to use Zoho's US authentication
Why am I getting event Pop-up Notification for events that have been cancelled?
Why is Calendar Notification still popping up for events that have been cancelled or changed? Each time events are cancelled or changed, I have observed that I am still getting notifications for them. Below is a sample pop-up notification for one of the
Next Page