Download the PHP package tristanjahier/zoho-crm-php without Composer
On this page you can find all versions of the php package tristanjahier/zoho-crm-php. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download tristanjahier/zoho-crm-php
More information about tristanjahier/zoho-crm-php
Files in tristanjahier/zoho-crm-php
Package zoho-crm-php
Short Description A PHP client for the API of Zoho CRM.
License MIT
Homepage https://github.com/tristanjahier/zoho-crm-php
Informations about the package zoho-crm-php
Zoho CRM API client (PHP)
This is an API client library for Zoho CRM, written in PHP.
It aims to cover the whole API (every module and method), while providing a great abstraction and very easy-to-use methods.
Requirements
- PHP :
8.0+
- Implementations of PSR-7 (HTTP messages), PSR-17 (HTTP factories) and PSR-18 (HTTP client)
Installation
The recommended way to install this package is through Composer.
Edit your composer.json
file:
or simply run this command:
If you do not know what "PSR-7, PSR-17 and PSR-18 implementations" are, basically it means that you need a standard-compliant HTTP client library installed. If you do not want to bother picking one, we recommend you to install the popular Guzzle:
Getting started
TL;DR - A quick example
Here are just a few examples of what is possible to do with this library:
The basics
The main component of this library is the Client
class. This is the starting point for each API request.
To create a client object you need an "access token broker" first. It is an object which sole purpose is to provide your client with fresh API access tokens. It MUST implement Zoho\Crm\Contracts\AccessTokenBrokerInterface
.
Zoho\Crm\V2\AccessTokenBroker
is the default implementation and it should suit most use cases. To create an instance you need to provide the credentials of your registered API client. In that order, the client ID, the client secret, and the refresh token:
Then you can create your client using that token broker:
It is sufficient to start making requests to the API of Zoho CRM. However, in this configuration, the API access token (that is used to authenticate requests) will only live as long as the $client
instance. It means that as soon as your client is garbage-collected or your PHP script stops executing, you will lose your access token, even though it was probably still valid for many minutes!
To prevent wasting fresh access tokens, it is strongly recommended to use an "access token store" to enable persistency across multiple PHP lifecycles:
- A token store is an object solely meant to handle the storage of the access token used by the client.
- It MUST implement
Zoho\Crm\Contracts\AccessTokenStoreInterface
. - It shall be passed as the 2nd argument of the client constructor.
This library provides a few implementations in Zoho\Crm\AccessTokenStorage
. To quickly get started you may use the FileStore
, which, as its name suggests, simply stores the access token in the local file system. Example:
Finally, you need to make sure that your client has a valid access token (not expired):
You are now ready to make API requests! One possibility is to follow the HTTP specifications of the API and manually craft any request you want using "raw requests":
Creating a request object does not make any HTTP request to the API, you need to execute it:
If the request is successful, it returns a Response
instance. The API response is parsed and cleaned up for you, you simply have to use getContent()
to get your data:
All summarized:
If you do not want to bother with the formal Response
object, you can call the get()
method on any request. It will execute the request and return its response content:
But... that's still a bit verbose, isn't it? Yes. This is just the most basic way to make an API request. Read the next sections to learn how to make better use of the library.
The client sub-APIs
The API support is divided into "sub-APIs", which are helpers that regroup multiple related features of the API. They are attached to the client and you can access them as public properties (e.g.: $client->theSubApi
). The currently available sub-APIs are:
Client accessor | Class |
---|---|
records |
Zoho\Crm\V2\Records\SubApi |
users |
Zoho\Crm\V2\Users\SubApi |
The purpose of a sub-API is to provide to the developer a fluent, eloquent and concise interface to manipulate one or multiple related aspects of the API.
For example, let's consider this request from a previous example, to retrieve the second page of records from the Contacts module that were modified after April 1st, 2019:
Using the Records sub-API, it can be rewritten like so:
Creating a new contact is very straightforward:
Retrieving all users from your Zoho CRM organization is as simple as:
These are just a couple of examples. Sub-APIs bring many more features. Look at the dedicated documentation and explore the code to find out.
Request pagination
When requesting records from Zoho, you will get a maximum of 200 records per response. Thus, if you want to get more than 200 records, you need to make multiple requests. This is done with the "page" URL parameter. Iterating on this parameter is called pagination.
In this library, pagination is made simple thanks to a request method called autoPaginated()
. All you have to do is to call this method on a compatible request object (implementing Zoho\Crm\Contracts\PaginatedRequestInterface
) and the library will fetch every page of records until there is no more data (or before if you set a limit). Example:
[!NOTE] The request objects returned by the
all()
methods of Records and Users sub-APIs have auto-pagination already enabled.
By default, request pagination is synchronous. It simply means that every new page is only fetched once the previous one has been executed and returned a response. This library also supports asynchronous request execution, and it usually makes pagination faster. Once again, this is really simple to use. All you have to do is to call the concurrency()
method on the request:
This method takes a single argument: a positive non-zero integer (> 0). It is the number of concurrent API requests. If you pass 1
, pagination will be synchronous. You can also pass null
to disable asynchronous pagination.
Asynchronous pagination can speed up your paginated requests a lot, depending on the concurrency setting. If you need to retrieve thousands of records, it will save you a lot of execution time.
[!WARNING] With X concurrent requests, you can waste up to X-1 API requests. Use it wisely.
Response types
The type of a response content depends on the sub-API method you use. It can be a scalar like a string, an array, a boolean or null. But in most cases, you will get either an entity or a collection of entities.
Entities are objects containing a set of coherent data. For example, a Zoho record (contact, call, lead etc.) is an entity.
When the response contains (or should contain) multiple entities, you get an entity collection.
Entities
An entity is an instance of Zoho\Crm\Entities\Entity
(or any subclass).
It encapsulates the attributes of common API objects like records or users for example.
It provides a few useful methods:
has($attribute)
: check if an attribute is definedget($attribute)
: get the value of an attributeset($attribute, $value)
: set the value of an attributegetId()
: get the entity IDtoArray()
: get the raw attributes array
It implements magic methods __get()
and __set()
which lets you manipulate its attributes like public properties:
Entity collections
An entity collection is an instance of Zoho\Crm\Entities\Collection
.
A collection is an array wrapper which provide a fluent interface to manipulate its items. In the case of an entity collection, these items are entities.
It provides a bunch of useful methods. To name a few:
has($key)
: determine if an item exists at a given indexget($key, $default = null)
: get the item at a given indexcount()
: get the number of items in the collectionisEmpty()
: determine if the collection is emptyfirst(callable $callback = null, $default = null)
: get the first item in the collectionfirstWhere($key, $operator, $value = null)
: get the first item matching the given (key, [operator,] value) tuplelast(callable $callback = null, $default = null)
: get the last item in the collectionlastWhere($key, $operator, $value = null)
: get the last item matching the given (key, [operator,] value) tuplemap(callable $callback)
: apply a callback over each item and return a new collection with the resultssum($property = null)
: compute the sum of the itemsfilter(callable $callback = null)
: filter the collection items with a callbackwhere($key, $operator, $value = null)
: filter items based on a comparison tuple: (key, [operator,] value)pluck($value, $key = null)
: get the values of a given item property by key
Look at the code of Zoho\Crm\Support\Collection
for more details.
It implements ArrayAccess
and IteratorAggregate
which lets you manipulate it like an array:
Sub-APIs reference
Records
The Records sub-API provides a single method, module()
, used to create an instance of Zoho\Crm\V2\Records\ModuleHelper
, which in turn provides a variety of features related to records.
It also implements the magic method __get()
, so that you can get a module helper using the module name in camel case as a public property:
The rest of this section details the methods available on the module helper.
all()
Instance of Zoho\Crm\V2\Records\ListRequest
with auto-pagination enabled.
deleted()
Instance of Zoho\Crm\V2\Records\ListDeletedRequest
with auto-pagination enabled.
search(string $criteria)
Instance of Zoho\Crm\V2\Records\SearchRequest
with auto-pagination enabled.
searchBy(string $field, string $value)
Instance of Zoho\Crm\V2\Records\SearchRequest
with auto-pagination enabled.
relationsOf(string $recordId, string $relatedModule)
List the records from another module related to a given record.
Instance of Zoho\Crm\V2\Records\ListRelatedRequest
with auto-pagination enabled.
relatedTo(string $relatedModule, string $recordId)
List the records related to a given record from another module. Inverse of relationsOf()
.
Instance of Zoho\Crm\V2\Records\ListRelatedRequest
with auto-pagination enabled.
find(string $id)
Retrieve a record by its ID.
Returns an instance of Zoho\Crm\V2\Records\Record
, or null
if not found.
insert($record, array $triggers = null)
Insert a new record.
Accepts a Record
instance, or an array of attributes.
Returns an array containing information about the result of the operation.
insertMany($records, array $triggers = null)
Insert multiple new records at the same time.
Returns an array of arrays containing information about the results of the operation.
update(string $id, $data, array $triggers = null)
Update an existing record.
Returns an array containing information about the result of the operation.
updateMany($records, array $triggers = null)
Update multiple existing records at the same time.
Returns an array of arrays containing information about the results of the operation.
upsert($record, array $duplicateCheckFields = null, array $triggers = null)
Upsert (update or insert) a record.
Returns an array containing information about the result of the operation.
upsertMany($records, array $duplicateCheckFields = null, array $triggers = null)
Upsert (update or insert) multiple records at the same time.
Returns an array of arrays containing information about the results of the operation.
delete(string $id)
Delete a record.
Returns an array containing information about the result of the operation.
deleteMany(array $ids)
Delete multiple records at the same time.
Returns an array of arrays containing information about the results of the operation.
Users
all()
Instance of Zoho\Crm\V2\Users\ListRequest
with auto-pagination enabled.
Advanced topics
Use a different API endpoint
By default the endpoint is https://www.zohoapis.com/crm/v2/
. You may want to use another one: https://www.zoho.com/crm/developer/docs/api/v2/multi-dc.html.
For that, you can use the setEndpoint()
method:
Similarly, if you are using the default access token broker, you can change the authorization endpoint:
Refresh the access token automatically
Out of the box, you need to deal with the access token validity by yourself. Meaning that you need to check on the expiry date regularly, and make a request to ask for a new token when it has expired.
The client has an option to automatically refresh its access token when needed. You simply have to set the 'access_token_auto_refresh_limit'
preference to the number of seconds of remaining validity below which it should be refreshed as soon as possible:
In the above example, the client will request a fresh access token when it needs to make a request to the API and its current access token will expire in less than a minute.
Before and after request execution hooks
If you need to, you can register a callback that will be executed before or after each request.
In both cases, the callback is a closure or any callable
taking 2 arguments:
- a copy of the request object ;
- a unique ID of the execution (random 16 chars string), in case you need to match the "before" and "after" hooks.
Use the beforeEachRequest()
method to register a callback that will be invoked just before each request is executed, but only after a successful request validation.
Use the afterEachRequest()
method to register a callback that will be invoked just after each request is executed and the API has returned a response. If an error or an exception is thrown from the HTTP request layer, the callback will not be invoked.
Example:
[!NOTE] Paginated requests will not trigger these hooks directly, but their subsequent requests (per page) will. In other words, only the requests that directly lead to an API HTTP request will trigger the hooks.
You can uniquely identify callbacks at registration:
And then you can deregister these identified callbacks so that they will never be invoked anymore:
Request middleware
If you need to, you can register custom middleware that will be applied to each request before it is converted into an HTTP request. Unlike execution hooks, middleware can modify the request object. Actually, this is exactly the point of middleware.
Use the registerMiddleware()
method, which only takes a callable
. So, you can pass a closure or an object implementing Zoho\Crm\Contracts\MiddlewareInterface
.
Example:
Notice that you don't need to return the request object. In fact, the return value will simply be ignored.
[!NOTE] As with execution hooks, paginated requests will not pass through the middleware directly, but their subsequent requests (per page) will.
All versions of zoho-crm-php with dependencies
guzzlehttp/guzzle Version ^6.2|^7.0
doctrine/inflector Version ^1.4|^2.0