Skip to content

Commit ed26b6f

Browse files
Adding files to repository
1 parent 40d447e commit ed26b6f

File tree

87 files changed

+15488
-2
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

87 files changed

+15488
-2
lines changed

README.md

Lines changed: 281 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,281 @@
1-
# zcrm-php-sdk
2-
It's a wrapper to Zoho CRM APIs. By using client library, user can build the application with ease
1+
#Zoho CRM API SDK for PHP
2+
------------------------
3+
PHP SDK for Zoho CRM APIs provides wrapper for Zoho CRM APIs. Hence invoking a Zoho CRM API from your client application is just a method call.It supports both single user as well as multi user authentication.
4+
5+
Registering a Zoho Client
6+
-------------------------
7+
Since Zoho CRM APIs are authenticated with OAuth2 standards, you should register your client app with Zoho. To register your app:
8+
1) Visit this page [https://accounts.zoho.com/developerconsole](https://accounts.zoho.com/developerconsole).
9+
2) Click on `Add Client ID`.
10+
3) Enter Client Name, Client Domain and Redirect URI then click `Create`.
11+
4) Your Client app would have been created and displayed by now.
12+
5) The newly registered app's Client ID and Client Secret can be found by clicking `Options``Edit`.
13+
(Options is the three dot icon at the right corner).
14+
15+
Setting Up
16+
----------
17+
PHP SDK is installable through `composer`. Composer is a tool for dependency management in PHP. SDK expects the following from the client app.
18+
19+
>Client app must have PHP 5.6 or above with curl extension enabled.
20+
Client library must be installed into client app though composer.
21+
The function ZCRMRestClient::initialize() must be called on startup of app.
22+
23+
>MySQL should run in the same machine serving at the default port 3306.
24+
The database name should be "zohooauth".
25+
There must be a table "oauthtokens" with the columns "useridentifier"(varchar(100)), "accesstoken"(varchar(100)), "refreshtoken"(varchar(100)), "expirytime"(bigint).
26+
27+
**If `token_persistence_path` provided in `oauth_configuration.properties` file, then persistence happens in file only. In this case, no need of MySQL**
28+
please create a empty file with name **zcrm_oauthtokens.txt** in the mentioned `token_persistence_path`
29+
30+
Installation of SDK through composer
31+
------------------------------------
32+
Install Composer(if not installed)
33+
Run this command to install the composer
34+
35+
>curl -sS https://getcomposer.org/installer | php
36+
37+
To make the composer accessible globally, follow the instructions from the link below
38+
39+
To install composer on mac/ linux machine:
40+
41+
>https://getcomposer.org/doc/00-intro.md#installation-linux-unix-osx
42+
43+
To install composer on windows machine:
44+
45+
>https://getcomposer.org/doc/00-intro.md#installation-windows
46+
47+
Install PHP SDK
48+
---------------
49+
Here's how you install the SDK
50+
navigate to the workspace of your client app
51+
Run the command below:
52+
53+
>composer require zohocrm/php-sdk
54+
55+
Hence, the SDK would be installed and a package named `vendor` would be created in the workspace of your client app.
56+
57+
Configurations
58+
--------------
59+
Your OAuth Client details should be given to the SDK as a property file. In SDK, we have placed a configuration file (oauth_configuration.properties). Please place the respective values in that file. You can find that file under `vendor/zohocrm/php-sdk/src/resources`.
60+
61+
Please fill only the following keys. Based on your domain(EU,CN) please change the value of `accounts_url`. Default value set as US domain
62+
63+
>client_id=
64+
client_secret=
65+
redirect_uri=
66+
accounts_url=https://accounts.zoho.com
67+
token_persistence_path=
68+
69+
Only the keys displayed above are to be filled.
70+
`client_id`, `client_secret` and `redirect_uri` are your OAuth client’s configurations that you get after registering your Zoho client.
71+
`token_persistence_path` is the path to store the OAuth related tokens in file. If this is set then, no need of `database` for persistence. Persistence happens through `file` only.
72+
`access_type` must be set to offline only because online OAuth client is not supported by the SDK as of now.
73+
`persistence_handler_class` is the implementation of the ZohoOAuthPersistenceInterface
74+
75+
Create a file named `ZCRMClientLibrary.log` in your client app machine and mention the absolute path of the created file in `configuration.properties` for the key `applicationLogFilePath`. You can find that file under `vendor/zohocrm/php-sdk/src/resources`. This file is to log the exceptions occurred during the usage of SDK.
76+
77+
Please fill only the following key
78+
79+
>applicationLogFilePath=
80+
81+
If your application needs only a single user authentication then you have to set the user EmailId in configurations.properties file as given below:
82+
83+
>currentUserEmail=user@email.com
84+
85+
In order to work with multi user authentication, you need to set the user EmailId in PHP super global variable ‘$_SERVER’ as given below:
86+
87+
>$_SERVER[‘user_email_id’]=“user@email.com
88+
89+
You can use `$_SERVER` variable for single user authentication as well, but it is recommended to go with setting up of email Id in `configuration.properties` file.
90+
91+
If you do not set the user email in super global variable then SDK expect it from `configuration.properties` file. If user email is not set in any of these two then SDK will throw exception.
92+
93+
94+
Initialization
95+
--------------
96+
The app would be ready to be initialized after defining the OAuth configuration file.
97+
98+
99+
Generating self-authorized grant token
100+
--------------------------------------
101+
For self client apps, the self authorized grant token should be generated from the Zoho Developer Console (https://accounts.zoho.com/developerconsole)
102+
103+
>1) Visit https://accounts.zoho.com/developerconsole
104+
2) Click Options → Self Client of the client for which you wish to authorize.
105+
3) Enter one or more(comma separated) valid Zoho CRM scopes, that you wish to authorize, in the “Scope” field and choose a time of expiry.
106+
4) Copy the grant token.
107+
5) Generate refresh_token from grant token by using below URL
108+
109+
>https://accounts.zoho.com/oauth/v2/token?code={grant_token}&redirect_uri={redirect_uri}&client_id={client_id}&client_secret={client_secret}&grant_type=authorization_code
110+
It's a POST request
111+
112+
Copy the refresh_token for backup
113+
114+
Please note that the generated grant token is valid only for the stipulated time you choose while generating it. Hence, refresh token should be generated within that time.
115+
116+
Generating access token
117+
-----------------------
118+
The following code snippet should be executed from your main class to get access token. Please paste the copied refresh token in the string literal mentioned below. This is a one-time process.
119+
120+
>ZCRMRestClient::initialize();
121+
$oAuthClient = ZohoOAuth::getClientInstance();
122+
$refreshToken = “paste_the_refresh_token_here”;
123+
$userIdentifier = “provide_user_identifier_like_email_here”;
124+
$oAuthTokens = $oAuthClient->generateAccessTokenFromRefreshToken($refreshToken,$userIdentifier);
125+
126+
Upon successful execution of the above code snippet, the generated access token and given refresh token would have been persisted through our persistence handler class.
127+
128+
Once the OAuth tokens have been persisted, subsequent API calls would use the persisted access and refresh tokens. The SDK will take care of refreshing the access token using refresh token, as and when required.
129+
130+
131+
App Startup
132+
-----------
133+
The SDK requires the following line of code invoked every time your client app is started.
134+
135+
>ZCRMRestClient::initialize();
136+
137+
Once the SDK has been initialized by the above line, you could use any APIs of the library to get proper results.
138+
139+
140+
Using the SDK
141+
-------------
142+
Add the below line in your client app PHP files, where you would like to make use of SDK.
143+
144+
>require 'vendor/autoload.php'
145+
146+
Through this line, you can access all the functionalities of the PHP SDK.
147+
148+
149+
150+
Class Hierarchy
151+
---------------
152+
All Zoho CRM entities are modelled as classes having properties and functions applicable to that particular entity. ZCRMRestClient is the base class of the SDK. ZCRMRestClient has functions to get instances of various other Zoho CRM entities.
153+
154+
The class relations and hierarchy of the library follows the entity hierarchy inside Zoho CRM. The class hierarchy of various Zoho CRM entities are given below:
155+
156+
- ZCRMRestClient
157+
- ZCRMOrganization
158+
- ZCRMUser
159+
- ZCRMUserTheme
160+
- ZCRMUserCustomizeInfo
161+
- ZCRMRole
162+
- ZCRMProfile
163+
- ZCRMPermission
164+
- ZCRMProfileSection
165+
- ZCRMProfileCategory
166+
- ZCRMModule
167+
- ZCRMLayout
168+
- ZCRMSection
169+
- ZCRMField
170+
- ZCRMPickListValue
171+
- ZCRMLookupField
172+
- ZCRMLeadConvertMapping
173+
- ZCRMLeadConvertMappingField
174+
- ZCRMCustomView
175+
- ZCRMCustomViewCategory
176+
- ZCRMCustomViewCriteria
177+
- ZCRMRelatedListProperties
178+
- ZCRMModuleRelatedList
179+
- ZCRMRecord
180+
- ZCRMNote
181+
- ZCRMAttachment
182+
- ZCRMInventoryLineItem
183+
- ZCRMTax
184+
- ZCRMEventParticipant
185+
- ZCRMPriceBookPricing
186+
- ZCRMModuleRelation
187+
- ZCRMJunctionRecord
188+
- ZCRMTrashRecord
189+
190+
Each entity class has functions to fetch its own properties and to fetch data of its immediate child entities through an API call.
191+
192+
For example: a Zoho CRM module (ZCRMModule) object will have member functions to get a module’s properties like display name, module Id, etc, and will also have functions to fetch all its child objects (like ZCRMLayout).
193+
194+
Instance object
195+
---------------
196+
It isn’t always effective to follow the complete class hierarchy from the top to fetch the data of an entity at some lower level, since this would involve API calls at each level. In order to handle this, every entity class has a getInstance() function to get its own dummy object and functions to get dummy objects of its child entities.
197+
198+
Please note that the getInstance() function would not have any of its properties filled because it would not fire an API call. This would just return a dummy object that shall be only used to access the non-static functions of the class.
199+
200+
Summing it up
201+
-------------
202+
ZCRMRestClient::getModule(“Contacts”) would return the actual Contacts module, that has all the properties of the Contacts module filled through an API call.
203+
ZCRMRestClient::getModuleInstance(“Contacts”) would return a dummy ZCRMModule object that would refer to the Contacts module, with no properties filled, since this doesn’t make an API call.
204+
Hence, to get records from a module, it is not necessary that you need to start from ZCRMRestClient. Instead, you could get a ZCRMModule instance with ZCRMModule::getInstance() and then invoke its non-static getRecords() function from the created instance. This would avoid the API call which would have been triggered to populate the ZCRMModule object.
205+
206+
Accessing record properties
207+
---------------------------
208+
Since record properties are dynamic across modules, only the fields like createdTime, createBy, owner etc, are given as ZCRMRecord’s default properties. All other record properties are available as a map in ZCRMRecord object.
209+
210+
To access the individual field values of a record, use the getter and setter functions available. The keys of the record properties map are the API names of the module’s fields. All fields API names of all modules are available under Setup → Marketplace → APIs → CRM API → API Names.
211+
212+
To get a field value, use $record → getFieldValue($fieldAPIName);
213+
To set a field value, use $record → setFieldValue($fieldAPIName, $newValue);
214+
While setting a field value, make sure that the set value is of the apt data type of the field to which you are going to set it.
215+
216+
Response Handling
217+
-----------------
218+
`APIResponse` and `BulkAPIResponse` are wrapper objects for Zoho CRM APIs’ responses. All API calling functions would return one of these two objects.
219+
220+
DownloadFile and downloadPhoto returns `FileAPIResponse` instead of APIResponse.
221+
A function which seeks a single entity would return an APIResponse, and a function which seeks a list of entities would return a BulkAPIResponse object.
222+
Use the `getData()` function to get the entity data alone from the response wrapper objects.
223+
`APIResponse → getData()` would return a single Zoho CRM entity object, whereas `BulkAPIResponse → getData()`` would return a list of Zoho CRM entity objects.
224+
Other than data, these response wrapper objects have the following properties:
225+
226+
`ResponseHeaders` - remaining API counts for the present day/window and time elapsed for the present window reset.
227+
`ResponseInfo` - any other information, if provided by the API, in addition to the actual data.
228+
`Array of EntityResponse(s)` - status of individual entities in a bulk API. For example: an insert records API may partially fail because of a few records. This array gives the individual records’ creation status.
229+
230+
Exceptions
231+
----------
232+
All unexpected behaviours like faulty API responses, library anomalies are handled by the SDK and are thrown only as a single exception - `ZCRMException`. Hence, it is enough to catch this exception alone in the client app code.
233+
234+
Examples:
235+
---------
236+
Sample Request for insert records:
237+
---------------------------------
238+
>$zcrmModuleIns = ZCRMModule::getInstance("Invoices");
239+
$bulkAPIResponse=$zcrmModuleIns->createRecords($recordsArray); // $recordsArray - array of ZCRMRecord instances filled with required data for creation.
240+
$entityResponses = $bulkAPIResponse->getEntityResponses();
241+
foreach($entityResponses as $entityResponse)
242+
{
243+
if("success"==$entityResponse->getStatus())
244+
{
245+
echo "Status:".$entityResponse->getStatus();
246+
echo "Message:".$entityResponse->getMessage();
247+
echo "Code:".$entityResponse->getCode();
248+
$createdRecordInstance=$entityResponse->getData();
249+
echo "EntityID:".$createdRecordInstance->getEntityId();
250+
echo "moduleAPIName:".$createdRecordInstance->getModuleAPIName();
251+
….
252+
}
253+
}
254+
255+
Sample Invoice record instance with filled data
256+
-----------------------------------------------
257+
$record=ZCRMRecord::getInstance("Invoices",null);
258+
$record->setFieldValue("Subject","Iphone sale to John");
259+
$record->setFieldValue("Account_Name","410405000001016021");
260+
$productInstance=ZCRMRecord::getInstance("Products",410405000001108011);
261+
$lineItem=ZCRMInventoryLineItem::getInstance($productInstance);
262+
$taxInstance1=ZCRMTax::getInstance("Sales Tax");
263+
$taxInstance1->setPercentage(2);
264+
$taxInstance1->setValue(10);
265+
$lineItem->addLineTax($taxInstance1);
266+
$taxInstance1=ZCRMTax::getInstance("Vat");
267+
$taxInstance1->setPercentage(12);
268+
$taxInstance1->setValue(60);
269+
$lineItem->addLineTax($taxInstance1);
270+
$lineItem->setQuantity(100);
271+
$lineItem->setDiscount(0.5);
272+
$record->addLineItem($lineItem);
273+
274+
275+
Sample Request to fetch records:
276+
--------------------------------
277+
>$zcrmModuleIns = ZCRMModule::getInstance("Contacts");
278+
$bulkAPIResponse=$zcrmModuleIns->getRecords();
279+
$recordsArray = $bulkAPIResponse->getData(); // $recordsArray - array of ZCRMRecord instances
280+
281+
For more APIs, please refer [this link](https://www.zoho.com/crm/help/api/v2/#api-reference)

composer.json

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
{
2+
"name": "zohocrm/php-sdk",
3+
"description": "Zoho CRM API SDK for PHP",
4+
"type": "SDK",
5+
"homepage": "https://github.com/zoho/zcrm-php-sdk",
6+
"authors": [
7+
{
8+
"name": "Zoho CRM API Team",
9+
"email":"support@zohocrm.com",
10+
"homepage": "https://www.zoho.com/crm/help/customer-support.html",
11+
"role": "Developer"
12+
}
13+
],
14+
"require": {
15+
"php": ">=5.6"
16+
},
17+
"require-dev": {
18+
"phpunit/phpunit": ">=5.7"
19+
},
20+
"autoload": {
21+
"psr-4": {
22+
"ClientLibrary\\": "src"
23+
},
24+
"files": ["src/index.php"]
25+
}
26+
}

src/Test/resources/image.png

46.2 KB
Loading
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
<?php
2+
class PHPUnitTestUtil extends \PHPUnit_Framework_TestCase
3+
{
4+
public function assertEqualsCheck($expectedValue,$actualValue)
5+
{
6+
$this->assertEquals($expectedValue,$actualValue);
7+
}
8+
9+
public function assertNotEqualsCheck($expectedValue,$actualValue)
10+
{
11+
$this->assertNotEquals($expectedValue,$actualValue);
12+
}
13+
14+
public function assertNullCheck($value)
15+
{
16+
$this->assertNull($value);
17+
}
18+
19+
public function assertNotNullCheck($value)
20+
{
21+
$this->assertNotNull($value);
22+
}
23+
24+
}
25+
26+
?>

0 commit comments

Comments
 (0)