PHP code example of zohocrm / php-sdk

1. Go to this page and download the library: Download zohocrm/php-sdk library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

zohocrm / php-sdk example snippets


     

/*
* 1 -> DataBase host name. Default value "localhost"
* 2 -> DataBase name. Default  value "zohooauth"
* 3 -> DataBase user name. Default value "root"
* 4 -> DataBase password. Default value ""
* 5 -> DataBase port number. Default value "3306"
*/
$tokenstore = new DBStore();

$tokenstore = new DBStore("hostName", "dataBaseName", "userName", "password", "portNumber");

//Parameter containing the absolute file path to store tokens
$tokenstore = new FileStore("/Users/username/Documents/php_sdk_token.txt");

namespace store;

use com\zoho\api\authenticator\Token;

use com\zoho\crm\api\exception\SDKException;

use com\zoho\crm\api\UserSignature;

use com\zoho\api\authenticator\store\TokenStore;

class CustomStore implements TokenStore
{
    /**
        * @param user A UserSignature class instance.
        * @param token A Token (com\zoho\api\authenticator\OAuthToken) class instance.
        * @return A Token class instance representing the user token details.
        * @throws SDKException if any problem occurs.
    */
    public function getToken($user, $token)
    {
        // Add code to get the token
        return null;
    }

    /**
        * @param user A UserSignature class instance.
        * @param token A Token (com\zoho\api\authenticator\OAuthToken) class instance.
        * @throws SDKException if any problem occurs.
    */
    public function saveToken($user, $token)
    {
        // Add code to save the token
    }

    /**
        * @param token A Token (com\zoho\api\authenticator\OAuthToken) class instance.
        * @throws SDKException if any problem occurs.
    */
    public function deleteToken($token)
    {
        // Add code to delete the token
    }

  /**
   * @return array  An array of Token (com\zoho\api\authenticator\OAuthToken) class instances
   */
    public function getTokens()
    {
        //Add code to retrieve all the stored tokens
    }

    public function deleteTokens()
    {
        //Add code to delete all the stored tokens.
    }
}

    /*
    * Create an instance of Logger Class that takes two parameters
    * 1 -> Level of the log messages to be logged. Can be configured by typing Levels "::" and choose any level from the list displayed.
    * 2 -> Absolute file path, where messages need to be logged.
    */
    $logger = Logger::getInstance(Levels::INFO, "/Users/user_name/Documents/php_sdk_log.log");
    

    //Create an UserSignature instance that takes user Email as parameter
    $user = new UserSignature("[email protected]");
    

    /*
    * Configure the environment
    * which is of the pattern Domain.Environment
    * Available Domains: USDataCenter, EUDataCenter, INDataCenter, CNDataCenter, AUDataCenter
    * Available Environments: PRODUCTION(), DEVELOPER(), SANDBOX()
    */
    $environment = USDataCenter::PRODUCTION();
    

    /*
    * Create a Token instance
    * 1 -> OAuth client id.
    * 2 -> OAuth client secret.
    * 3 -> REFRESH/GRANT token.
    * 4 -> Token type(REFRESH/GRANT).
    * 5 -> OAuth redirect URL. (optional)
    */
    $token = new OAuthToken("clientId", "clientSecret", "REFRESH/GRANT token", TokenType::REFRESH/GRANT, "redirectURL");
    

    /*
    * Create an instance of DBStore.
    * 1 -> DataBase host name. Default value "localhost"
    * 2 -> DataBase name. Default  value "zohooauth"
    * 3 -> DataBase user name. Default value "root"
    * 4 -> DataBase password. Default value ""
    * 5 -> DataBase port number. Default value "3306"
    */
    //$tokenstore = new DBStore();

    $tokenstore = new DBStore("hostName", "dataBaseName", "userName", "password", "portNumber");

    // $tokenstore = new FileStore("absolute_file_path");
    

    /*
    * autoRefreshFields (default value is false)
    * true - all the modules' fields will be auto-refreshed in the background, every hour.
    * false - the fields will not be auto-refreshed in the background. The user can manually delete the file(s) or refresh the fields using methods from ModuleFieldsHandler(com\zoho\crm\api\util\ModuleFieldsHandler)
    *
    * pickListValidation (default value is true)
    * A boolean field that validates user input for a pick list field and allows or disallows the addition of a new value to the list.
    * true - the SDK validates the input. If the value does not exist in the pick list, the SDK throws an error.
    * false - the SDK does not validate the input and makes the API request with the user’s input to the pick list
    *
    * enableSSLVerification (default value is true)
    * A boolean field to enable or disable curl certificate verification
    * true - the SDK verifies the authenticity of certificate
    * false - the SDK skips the verification
    */
    $autoRefreshFields = false;

    $pickListValidation = false;

    $enableSSLVerification = true;

    $connectionTimeout = 2; //The number of seconds to wait while trying to connect. Use 0 to wait indefinitely.

    $timeout = 2; //The maximum number of seconds to allow cURL functions to execute.

    $sdkConfig = (new SDKConfigBuilder())->setAutoRefreshFields($autoRefreshFields)->setPickListValidation($pickListValidation)->setSSLVerification($enableSSLVerification)->connectionTimeout($connectionTimeout)->timeout($timeout)->build();
    

     $requestProxy = new RequestProxy("proxyHost", "proxyPort", "proxyUser", "password");
    

    $resourcePath = "/Users/user_name/Documents/phpsdk-application";
    


namespace com\zoho\crm\sample\initializer;

use com\zoho\api\authenticator\OAuthToken;

use com\zoho\api\authenticator\TokenType;

use com\zoho\api\authenticator\store\DBStore;

use com\zoho\api\authenticator\store\FileStore;

use com\zoho\crm\api\Initializer;

use com\zoho\crm\api\UserSignature;

use com\zoho\crm\api\SDKConfigBuilder;

use com\zoho\crm\api\dc\USDataCenter;

use com\zoho\api\logger\Logger;

use com\zoho\api\logger\Levels;

class Initialize
{
    public static function initialize()
    {
        /*
            * Create an instance of Logger Class that takes two parameters
            * 1 -> Level of the log messages to be logged. Can be configured by typing Levels "::" and choose any level from the list displayed.
            * 2 -> Absolute file path, where messages need to be logged.
        */
        $logger = Logger::getInstance(Levels::INFO, "/Users/user_name/Documents/php_sdk_log.log");

        //Create an UserSignature instance that takes user Email as parameter
        $user = new UserSignature("[email protected]");

        /*
            * Configure the environment
            * which is of the pattern Domain.Environment
            * Available Domains: USDataCenter, EUDataCenter, INDataCenter, CNDataCenter, AUDataCenter
            * Available Environments: PRODUCTION(), DEVELOPER(), SANDBOX()
        */
        $environment = USDataCenter::PRODUCTION();

        /*
            * Create a Token instance
            * 1 -> OAuth client id.
            * 2 -> OAuth client secret.
            * 3 -> REFRESH/GRANT token.
            * 4 -> Token type(REFRESH/GRANT).
            * 5 -> OAuth redirect URL.
        */
        $token = new OAuthToken("clientId", "clientSecret", "REFRESH/GRANT token", TokenType::REFRESH/GRANT, "redirectURL");

        /*
        * Create an instance of DBStore.
        * 1 -> DataBase host name. Default value "localhost"
        * 2 -> DataBase name. Default  value "zohooauth"
        * 3 -> DataBase user name. Default value "root"
        * 4 -> DataBase password. Default value ""
        * 5 -> DataBase port number. Default value "3306"
        */
        //$tokenstore = new DBStore();

        $tokenstore = new DBStore("hostName", "dataBaseName", "userName", "password", "portNumber");

        // $tokenstore = new FileStore("absolute_file_path");

        $autoRefreshFields = false;

        $pickListValidation = false;

        $connectionTimeout = 2;

        $timeout = 2;

        $sdkConfig = (new SDKConfigBuilder())->setAutoRefreshFields($autoRefreshFields)->setPickListValidation($pickListValidation)->setSSLVerification($enableSSLVerification)->connectionTimeout($connectionTimeout)->timeout($timeout)->build();

        $resourcePath = "/Users/user_name/Documents/phpsdk-application";

        //Create an instance of RequestProxy
        $requestProxy = new RequestProxy("proxyHost", "proxyPort", "proxyUser", "password");

        /*
          * Call static initialize method of Initializer class that takes the following arguments
          * 1 -> UserSignature instance
          * 2 -> Environment instance
          * 3 -> Token instance
          * 4 -> TokenStore instance
          * 5 -> SDKConfig instance
          * 6 -> resourcePath - A String
          * 7 -> Log instance (optional)
          * 8 -> RequestProxy instance (optional)
        */
        Initializer::initialize($user, $environment, $token, $tokenstore, $sdkConfig, $resourcePath, $logger, $requestProxy);
    }
}

Initializer::switchUser($user, $environment, $token, $sdkConfig, $proxy);

Initializer::removeUserConfiguration($user, $environment);


namespace multiuser;

use com\zoho\api\authenticator\OAuthToken;

use com\zoho\api\authenticator\TokenType;

use com\zoho\api\authenticator\store\FileStore;

use com\zoho\crm\api\Initializer;

use com\zoho\crm\api\UserSignature;

use com\zoho\crm\api\SDKConfigBuilder;

use com\zoho\crm\api\dc\USDataCenter;

use com\zoho\api\logger\Logger;

use com\zoho\api\logger\Levels;

use com\zoho\crm\api\HeaderMap;

use com\zoho\crm\api\ParameterMap;

use com\zoho\crm\api\record\RecordOperations;

use com\zoho\crm\api\record\GetRecordsHeader;

use com\zoho\crm\api\record\GetRecordsParam;

use com\zoho\crm\api\dc\EUDataCenter;

 (new SDKConfigBuilder())->setAutoRefreshFields($autoRefreshFields)->setPickListValidation($pickListValidation)->setSSLVerification($enableSSLVerification)->connectionTimeout($connectionTimeout)->timeout($timeout)->build();

        $resourcePath ="/Users/user_name/Documents/phpsdk-application";

        Initializer::initialize($user1, $environment1, $token1, $tokenstore, $sdkConfig, $resourcePath, $logger);

        $this->getRecords("Leads");

        $environment2 = EUDataCenter::PRODUCTION();

        $user2 = new UserSignature("[email protected]");

        $token2 = new OAuthToken("clientId2", "clientSecrect2", "REFRESH/GRANT token", TokenType.REFRESH/GRANT);

        Initializer::switchUser($user2, $environment2, $token2, $sdkConfig);

        // Initializer::removeUserConfiguration($user1, $environment1);

        $this->getRecords("Students");

        Initializer::switchUser($user1, $environment1, $token1, $sdkConfig);

        $this->getRecords("Contacts");
    }

    public function getRecords($moduleAPIName)
    {
        try
        {
            $recordOperations = new RecordOperations();

            $paramInstance = new ParameterMap();

            $paramInstance->add(GetRecordsParam::approved(), "false");

            $headerInstance = new HeaderMap();

            $ifmodifiedsince = date_create("2020-06-02T11:03:06+05:30")->setTimezone(new \DateTimeZone(date_default_timezone_get()));

            $headerInstance->add(GetRecordsHeader::IfModifiedSince(), $ifmodifiedsince);

            //Call getRecord method that takes paramInstance, moduleAPIName as parameter
            $response = $recordOperations->getRecords($moduleAPIName,$paramInstance, $headerInstance);

            echo($response->getStatusCode() . "\n");

            print_r($response->getObject());

            echo("\n");
        }
        catch (\Exception $e)
        {
            print_r($e);
        }
    }
}

$obj = new MultiThread();

$obj->main();


namespace index;

use com\zoho\api\authenticator\OAuthToken;

use com\zoho\api\authenticator\TokenType;

use com\zoho\api\authenticator\store\DBStore;

use com\zoho\api\authenticator\store\FileStore;

use com\zoho\crm\api\Initializer;

use com\zoho\crm\api\UserSignature;

use com\zoho\crm\api\SDKConfigBuilder;

use com\zoho\crm\api\dc\USDataCenter;

use com\zoho\api\logger\Logger;

use com\zoho\api\logger\Levels;

use com\zoho\crm\api\record\RecordOperations;

use com\zoho\crm\api\HeaderMap;

use com\zoho\crm\api\ParameterMap;

use com\zoho\crm\api\record\GetRecordsHeader;

use com\zoho\crm\api\record\GetRecordsParam;

use com\zoho\crm\api\record\ResponseWrapper;

s of the pattern Domain.Environment
            * Available Domains: USDataCenter, EUDataCenter, INDataCenter, CNDataCenter, AUDataCenter
            * Available Environments: PRODUCTION(), DEVELOPER(), SANDBOX()
        */
        $environment = USDataCenter::PRODUCTION();

        //Create a Token instance
        $token = new OAuthToken("clientId", "clientSecrect", "REFRESH/GRANT token", TokenType.REFRESH/GRANT, "redirectURL");

        //Create an instance of TokenStore
        // $tokenstore = new DBStore();

        $tokenstore = new FileStore("/Users/user_name/Documents/php_sdk_token.txt");

        $autoRefreshFields = false;

        $pickListValidation = false;

        $connectionTimeout = 2;

        $timeout = 2;

        $sdkConfig = (new SDKConfigBuilder())->setAutoRefreshFields($autoRefreshFields)->setPickListValidation($pickListValidation)->setSSLVerification($enableSSLVerification)->connectionTimeout($connectionTimeout)->timeout($timeout)->build();

        $resourcePath ="/Users/user_name/Documents/phpsdk-application";

       /*
        * Call static initialize method of Initializer class that takes the following arguments
        * 1 -> UserSignature instance
        * 2 -> Environment instance
        * 3 -> Token instance
        * 4 -> TokenStore instance
        * 5 -> SDKConfig instance
        * 6 -> resourcePath -A String
        * 7 -> Log instance (optional)
        * 8 -> RequestProxy instance (optional)
        */
        Initializer::initialize($user, $environment, $token, $tokenstore, $sdkConfig, $resourcePath, $logger);

        try
        {
            $recordOperations = new RecordOperations();

            $paramInstance = new ParameterMap();

            $paramInstance->add(GetRecordsParam::approved(), "both");

            $headerInstance = new HeaderMap();

            $ifmodifiedsince = date_create("2020-06-02T11:03:06+05:30")->setTimezone(new \DateTimeZone(date_default_timezone_get()));

            $headerInstance->add(GetRecordsHeader::IfModifiedSince(), $ifmodifiedsince);

            $moduleAPIName = "Leads";

            //Call getRecord method that takes paramInstance, moduleAPIName as parameter
            $response = $recordOperations->getRecords($moduleAPIName,$paramInstance, $headerInstance);

            if($response != null)
            {
                //Get the status code from response
                echo("Status Code: " . $response->getStatusCode() . "\n");

                //Get object from response
                $responseHandler = $response->getObject();

                if($responseHandler instanceof ResponseWrapper)
                {
                    //Get the received ResponseWrapper instance
                    $responseWrapper = $responseHandler;

                    //Get the list of obtained Record instances
                    $records = $responseWrapper->getData();

                    if($records != null)
                    {
                        $recordClass = 'com\zoho\crm\api\record\Record';

                        foreach($records as $record)
                        {
                            //Get the ID of each Record
                            echo("Record ID: " . $record->getId() . "\n");

                            //Get the createdBy User instance of each Record
                            $createdBy = $record->getCreatedBy();

                            //Check if createdBy is not null
                            if($createdBy != null)
                            {
                                //Get the ID of the createdBy User
                                echo("Record Created By User-ID: " . $createdBy->getId() . "\n");

                                //Get the name of the createdBy User
                                echo("Record Created By User-Name: " . $createdBy->getName() . "\n");

                                //Get the Email of the createdBy User
                                echo("Record Created By User-Email: " . $createdBy->getEmail() . "\n");
                            }

                            //Get the CreatedTime of each Record
                            echo("Record CreatedTime: ");

                            print_r($record->getCreatedTime());

                            echo("\n");

                            //Get the modifiedBy User instance of each Record
                            $modifiedBy = $record->getModifiedBy();

                            //Check if modifiedBy is not null
                            if($modifiedBy != null)
                            {
                                //Get the ID of the modifiedBy User
                                echo("Record Modified By User-ID: " . $modifiedBy->getId() . "\n");

                                //Get the name of the modifiedBy User
                                echo("Record Modified By User-Name: " . $modifiedBy->getName() . "\n");

                                //Get the Email of the modifiedBy User
                                echo("Record Modified By User-Email: " . $modifiedBy->getEmail() . "\n");
                            }

                            //Get the ModifiedTime of each Record
                            echo("Record ModifiedTime: ");

                            print_r($record->getModifiedTime());

                            print_r("\n");

                            //Get the list of Tag instance each Record
                            $tags = $record->getTag();

                            //Check if tags is not null
                            if($tags != null)
                            {
                                foreach($tags as $tag)
                                {
                                    //Get the Name of each Tag
                                    echo("Record Tag Name: " . $tag->getName() . "\n");

                                    //Get the Id of each Tag
                                    echo("Record Tag ID: " . $tag->getId() . "\n");
                                }
                            }

                            //To get particular field value
                            echo("Record Field Value: " . $record->getKeyValue("Last_Name") . "\n");// FieldApiName

                            echo("Record KeyValues : \n" );
                            //Get the KeyValue map
                            foreach($record->getKeyValues() as $keyName => $value)
                            {
                                echo("Field APIName" . $keyName . " \tValue : ");

                                print_r($value);

                                echo("\n");
                            }
                        }
                    }
                }
            }
        }
        catch (\Exception $e)
        {
            print_r($e);
        }
    }
}

Record::getRecord();

sh
    curl -sS https://getcomposer.org/installer | php
    
sh
    composer