PHP code example of zohocrm / php-sdk-2.1

1. Go to this page and download the library: Download zohocrm/php-sdk-2.1 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-2.1 example snippets


     

/*
* Create an instance of TokenStore.
* host -> DataBase host name. Default "jdbc:mysql://localhost"
* databaseName -> DataBase name. Default "zohooauth"
* userName -> DataBase user name. Default "root"
* tableName -> DataBase table name. Default "oauthtoken"
* password -> DataBase password. Default ""
* portNumber -> DataBase port number. Default "3306"
*/
// $tokenstore = (new DBBuilder())->build();
$tokenstore = (new DBBuilder())
->host("hostName")
->databaseName("databaseName")
->userName("userName")
->portNumber("portNumber")
->tableName("tableName")
->password("password")
->build();

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

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.
    }

    /**
      * @param id A string.
      * @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 getTokenById($id, $token)
    {
      // Add code to get the token using unique id
      return null;
    }
}

    //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();
    

    $token = (new OAuthBuilder())
    ->clientId("clientId")
    ->clientSecret("clientSecret")
    ->grantToken("grantToken")
    ->redirectURL("redirectURL")
    ->build();
    

    $token = (new OAuthBuilder())
    ->clientId("clientId")
    ->clientSecret("clientSecret")
    ->refreshToken("refreshToken")
    ->redirectURL("redirectURL")
    ->build();
  

    $token = (new OAuthBuilder())
    ->accessToken("accessToken")
    ->build();
  

    /*
    * Create an instance of Logger Class that d. Can be configured by typing Levels "::" and choose any level from the list displayed.
    * filePath -> Absolute file path, where messages need to be logged.
    */
    $logger = (new LogBuilder())
    ->level(Levels::INFO)
    ->filePath("/Documents/php_sdk_log.log")
    ->build();
    

    /*
    * Create an instance of DBStore that  "localhost"
    * databaseName -> DataBase name. Default  value "zohooauth"
    * userName -> DataBase user name. Default value "root"
    * password -> DataBase password. Default value ""
    * portNumber -> DataBase port number. Default value "3306"
    * tabletName -> DataBase table name. Default value "oauthtoken"
    */
    $tokenstore = (new DBBuilder())
    ->host("hostName")
    ->databaseName("dataBaseName")
    ->userName("userName")
    ->password("password")
    ->portNumber("portNumber")
    ->tableName("tableName")
    ->build();
    

    $tokenstore = new FileStore("absolute_file_path");
    

    $tokenstore = new CustomStore();
    

    /*
    * By default, the SDK creates the SDKConfig instance
    * 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;
    //The number of seconds to wait while trying to connect. Use 0 to wait indefinitely.
    $connectionTimeout = 2;
    //The maximum number of seconds to allow cURL functions to execute.
    $timeout = 2;
    $sdkConfig = (new SDKConfigBuilder())
    ->autoRefreshFields($autoRefreshFields)
    ->pickListValidation($pickListValidation)
    ->sslVerification($enableSSLVerification)
    ->connectionTimeout($connectionTimeout)
    ->timeout($timeout)
    ->build();
    

     $requestProxy = (new ProxyBuilder())
     ->host("proxyHost")
     ->port("proxyPort")
     ->user("proxyUser")
     ->password("password")
     ->build();
    

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


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;
    ->redirectURL("redirectURL")
    ->build();
    $tokenstore = (new DBBuilder())
    ->host("hostName")
    ->databaseName("dataBaseName")
    ->userName("userName")
    ->password("password")
    ->portNumber("portNumber")
    ->tableName("tableName")
    ->build();
    $autoRefreshFields = false;
    $pickListValidation = false;
    $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())
    ->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();
  }
}

  (new InitializeBuilder())
  ->user($user)
  ->environment($environment)
  ->token($token)
  ->SDKConfig($configInstance)
  ->switchUser();

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


use com\zoho\api\authenticator\OAuthBuilder;
use com\zoho\crm\api\InitializeBuilder;
use com\zoho\crm\api\UserSignature;
use com\zoho\crm\api\dc\USDataCenter;
use com\zoho\crm\api\dc\EUDataCenter;
use com\zoho\crm\api\Initializer;
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;
nment1)
    ->token($token1)
    ->initialize();
    $this->getRecords("Leads");

    $environment2 = EUDataCenter::PRODUCTION();
    $user2 = new UserSignature("[email protected]");
    $token2 = (new OAuthBuilder())
    ->clientId("clientId2")
    ->clientSecret("clientSecret2")
    ->refreshToken("refreshToken2")
    ->redirectURL("redirectURL2")
    ->build();
    // Initializer::removeUserConfiguration($user1, $environment1);

    (new InitializeBuilder())
    ->user($user2)
    ->environment($environment2)
    ->token($token2)
    ->switchUser();
    $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);
      $response = $recordOperations->getRecords($moduleAPIName,$paramInstance, $headerInstance);
      echo($response->getStatusCode() . "\n");
      print_r($response->getObject());
      echo("\n");
    }
    catch (\Exception $e)
    {
      print_r($e);
    }
  }
}
$obj = new MultiUser();
$obj->main();


use com\zoho\api\authenticator\OAuthBuilder;
use com\zoho\crm\api\InitializeBuilder;
use com\zoho\crm\api\UserSignature;
use com\zoho\crm\api\dc\USDataCenter;
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;
en($token)
    ->initialize();
  }

  public function getRecord()
  {
    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";
      $response = $recordOperations->getRecords($moduleAPIName, $paramInstance, $headerInstance);
      if($response != null)
      {
        echo("Status Code: " . $response->getStatusCode() . "\n");
        $responseHandler = $response->getObject();
        if($responseHandler instanceof ResponseWrapper)
        {
          $responseWrapper = $responseHandler;
          $records = $responseWrapper->getData();
          if($records != null)
          {
            $recordClass = 'com\zoho\crm\api\record\Record';
            foreach($records as $record)
            {
              echo("Record ID: " . $record->getId() . "\n");
              $createdBy = $record->getCreatedBy();
              if($createdBy != null)
              {
                echo("Record Created By User-ID: " . $createdBy->getId() . "\n");
                echo("Record Created By User-Name: " . $createdBy->getName() . "\n");
                echo("Record Created By User-Email: " . $createdBy->getEmail() . "\n");
              }
              echo("Record CreatedTime: ");
              print_r($record->getCreatedTime());
              echo("\n");
              $modifiedBy = $record->getModifiedBy();
              if($modifiedBy != null)
              {
                echo("Record Modified By User-ID: " . $modifiedBy->getId() . "\n");
                echo("Record Modified By User-Name: " . $modifiedBy->getName() . "\n");
                echo("Record Modified By User-Email: " . $modifiedBy->getEmail() . "\n");
              }
              echo("Record ModifiedTime: ");
              print_r($record->getModifiedTime());
              print_r("\n");
              $tags = $record->getTag();
              if($tags != null)
              {
                foreach($tags as $tag)
                {
                  echo("Record Tag Name: " . $tag->getName() . "\n");
                  echo("Record Tag ID: " . $tag->getId() . "\n");
                }
              }
              echo("Record Field Value: " . $record->getKeyValue("Last_Name") . "\n");
              echo("Record KeyValues : \n" );
              foreach($record->getKeyValues() as $keyName => $value)
              {
                echo("Field APIName" . $keyName . " \tValue : ");

                print_r($value);

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

$obj = new Record();
$obj->initialize();
$obj->getRecord();
sh
    curl -sS https://getcomposer.org/installer | php
    
sh
    composer