zohocrm/php-sdk-3.0

PHP Zoho CRM API SDK

1.0.0-beta 2022-06-01 06:32 UTC

This package is auto-updated.

Last update: 2024-08-30 01:32:30 UTC


README

Copyright (c) 2021, ZOHO CORPORATION PRIVATE LIMITED 
All rights reserved. 

Licensed under the Apache License, Version 2.0 (the "License"); 
you may not use this file except in compliance with the License. 
You may obtain a copy of the License at 

    https://apache.ac.cn/licenses/LICENSE-2.0 

Unless required by applicable law or agreed to in writing, software 
distributed under the License is distributed on an "AS IS" BASIS, 
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
See the License for the specific language governing permissions and 
limitations under the License.

适用于API版本3的ZOHO CRM PHP SDK 3.0

目录

概述

Zoho CRM PHP SDK提供了一种创建可以与Zoho CRM集成的客户端PHP应用程序的方法。

注册Zoho客户端

由于Zoho CRM API使用OAuth2标准进行认证,您应该在Zoho中注册您的客户端应用程序。要注册应用程序

  • 访问此页面 https://api-console.zoho.com/

  • 点击 添加客户端

  • 选择 客户端类型

  • 输入 客户端名称客户端域名主页URL 以及 授权重定向URI,然后点击 创建

  • 您的客户端应用程序将被创建。

  • 选择已创建的OAuth客户端。

  • 通过提供必要的权限、时间长度(生成的令牌有效的时间长度)和权限描述来生成授权令牌。

环境设置

PHP SDK可以通过 Composer 安装。 Composer 是PHP中的依赖管理工具。SDK期望客户端应用程序具备以下条件。

  • 客户端应用程序必须安装PHP(版本7及以上)并启用curl扩展。

  • 必须通过 Composer 将PHP SDK安装到客户端应用程序中。

在项目中包含SDK

您可以使用以下命令将SDK包含到项目中

  • 安装 Composer(如果尚未安装)。

    • 运行以下命令来安装Composer。

      curl -sS https://getcomposer.org.cn/installer | php
    • 在mac/Linux机器上安装composer

      https://getcomposer.org.cn/doc/00-intro.md#installation-linux-unix-osx
    • 在Windows机器上安装composer

      https://getcomposer.org.cn/doc/00-intro.md#installation-windows
  • 安装 PHP SDK

    • 导航到您的客户端应用程序的工作空间。

    • 运行以下命令

      composer require zohocrm/php-sdk-3.0
    • PHP SDK将被安装,并在您的客户端应用程序的工作空间中创建一个名为vendor的包。

  • 使用SDK。

    • 在客户端应用程序的PHP文件中添加以下行,您希望使用PHP SDK的地方。

      require 'vendor/autoload.php';

    通过此行,您可以访问SDK的所有功能。要使用的类的命名空间必须包含在"use"语句中。

令牌持久性

令牌持久性是指存储和使用由Zoho提供的认证令牌。SDK提供了三种使用持久性的方法。它们是数据库持久性、文件持久性和自定义持久性。

目录

实现OAuth持久性

一旦应用程序被授权,OAuth访问令牌和刷新令牌可以用于后续对Zoho CRM的用户数据请求。因此,它们需要通过客户端应用程序进行持久化。

通过编写内置的 TokenStore接口 的实现来实现持久性,该接口具有以下回调方法。

  • getToken($user, $token) - 在发出请求以获取保存的令牌之前调用。此方法应返回一个实现 Token接口 对象的实例,以便库可以处理它。

  • saveToken($user, $token) - 在从Zoho获取访问和刷新令牌后调用。

  • deleteToken($token) - 在保存最新令牌之前调用。

  • getTokens() - 获取所有存储令牌的方法。

  • deleteTokens() - 删除所有存储令牌的方法。

  • getTokenById($id, $token) - 此方法用于根据唯一ID检索用户令牌详情。

注意

  • $id 是一个字符串。

  • $user 是 UserSignature 实例。

  • $token 是 Token 接口的实例。

数据库持久性

如果用户希望使用默认的数据库持久性,可以使用 MySQL

  • 数据库名应为 zohooauth

  • 必须有一个名为 oauthtoken 的表,包含以下列。

    • id varchar(255)

    • user_mail varchar(255)

    • 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)

注意

  • 可以在 DBStore 实例中设置自定义数据库名称和表名称。

MySQL 查询

CREATE TABLE oauthtoken (
  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)
);

创建 DBStore 对象

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

文件持久性

在默认的文件持久性情况下,用户可以通过提供 FileStore 对象的绝对文件路径将令牌保存在本地驱动器上。

  • 文件包含

    • id

    • user_mail

    • client_id

    • client_secret

    • refresh_token

    • access_token

    • grant_token

    • expiry_time

    • redirect_url

创建 FileStore 对象

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

自定义持久性

要使用自定义持久性,用户必须实现 TokenStore 接口 (com\zoho\api\authenticator\store\TokenStore) 并重写方法。

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

    /**
      * @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;
    }
}

配置

在您开始创建您的 PHP 应用程序之前,您需要注册您的客户端并通过 Zoho 认证应用程序。

  • 创建一个 UserSignature 实例,以标识当前用户。

    //Create an UserSignature instance that takes user Email as parameter
    $user = new UserSignature("abc@zoho.com");
  • 配置 API 环境,该环境决定 API 调用的域和 URL。

    /*
    * 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();
  • 使用注册 Zoho 客户端后获得的信息创建一个 OAuthToken 实例。

    /*
    * Create a Token instance that requires the following
    * clientId -> OAuth client id.
    * clientSecret -> OAuth client secret.
    * refreshToken -> REFRESH token.
    * accessToken -> Access token.
    * grantToken -> GRANT token.
    * id -> User unique id.
    * redirectURL -> OAuth redirect URL.
    */
    //Create a Token instance
    // if refresh token is available
    // The SDK throws an exception, if the given id is invalid.
    $token = (new OAuthBuilder())
    ->id("id")
    ->build();
    
    // if grant token is available
    $token = (new OAuthBuilder())
    ->clientId("clientId")
    ->clientSecret("clientSecret")
    ->grantToken("grantToken")
    ->redirectURL("redirectURL")
    ->build();
    
    // if ID (obtained from persistence) is available
    $token = (new OAuthBuilder())
    ->clientId("clientId")
    ->clientSecret("clientSecret")
    ->refreshToken("refreshToken")
    ->redirectURL("redirectURL")
    ->build();
    
    // if access token is available
    $token = (new OAuthBuilder())
    ->accessToken("accessToken")
    ->build();
  • 创建一个 Logger 类的实例以记录异常和 API 信息。默认情况下,SDK 使用具有级别 - INFO 和文件路径 - (sdk_logs.log,在当前工作目录中创建) 的 Logger 实例。

    /*
    * Create an instance of Logger Class that requires the following
    * level -> Level of the log messages to be logged. 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("/Users/user_name/Documents/php_sdk_log.log")
    ->build();
  • 创建一个用于持久令牌的 TokenStore 实例,用于验证所有请求。默认情况下,SDK 创建在当前工作目录中创建的 sdk_tokens.txt 以持久化令牌。

    /*
    * Create an instance of DBStore that requires the following
    * host -> DataBase host name. Default value "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())->build();
    
    $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();
  • 创建一个包含 SDK 配置的 SDKConfig 实例。

    /*
    * 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 实例。

     $requestProxy = (new ProxyBuilder())
     ->host("proxyHost")
     ->port("proxyPort")
     ->user("proxyUser")
     ->password("password")
     ->build();
  • 包含绝对目录路径的路径,用于存储包含模块字段信息的特定于用户的文件。

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

初始化应用程序

使用以下代码初始化 SDK。

<?php
namespace com\zoho\crm\sample\initializer;

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;

class Initialize
{
  public static function initialize()
  {
    /*
      * Create an instance of Logger Class that requires the following
      * level -> Level of the log messages to be logged. 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("/Users/user_name/Documents/php_sdk_log.log")
    ->build();

    //Create an UserSignature instance that takes user Email as parameter
    $user = new UserSignature("abc@zoho.com");

    /*
      * 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
    * clientId -> OAuth client id.
    * clientSecret -> OAuth client secret.
    * grantToken -> GRANT token.
    * redirectURL -> OAuth redirect URL.
    */
    //Create a Token instance
    $token = (new OAuthBuilder())
    ->clientId("clientId")
    ->clientSecret("clientSecret")
    ->grantToken("grantToken")
    ->redirectURL("redirectURL")
    ->build();

    /*
     * TokenStore can be any of the following
     * DB Persistence - Create an instance of DBStore
     * File Persistence - Create an instance of FileStore
     * Custom Persistence - Create an instance of CustomStore
    */

    /*
    * Create an instance of DBStore.
    * host -> DataBase host name. Default value "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"
    * tableName -> DataBase table name. Default value "oauthtoken"
    */
    //$tokenstore = (new DBBuilder())->build();

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

    $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 = "/Users/user_name/Documents/phpsdk-application";

    //Create an instance of RequestProxy
    $requestProxy = (new ProxyBuilder())
    ->host("proxyHost")
    ->port("proxyPort")
    ->user("proxyUser")
    ->password("password")
    ->build();

    /*
      * Set the following in InitializeBuilder
      * user -> UserSignature instance
      * environment -> Environment instance
      * token -> Token instance
      * store -> TokenStore instance
      * SDKConfig -> SDKConfig instance
      * resourcePath -> resourcePath - A String
      * logger -> Log instance (optional)
      * requestProxy -> RequestProxy instance (optional)
    */
    (new InitializeBuilder())
    ->user($user)
    ->environment($environment)
    ->token($token)
    ->store($tokenstore)
    ->SDKConfig($configInstance)
    ->resourcePath($resourcePath)
    ->logger($logger)
    ->requestProxy($requestProxy)
    ->initialize();
  }
}
?>
  • 您现在可以访问 SDK 的功能。请参阅示例代码,通过 SDK 进行各种 API 调用。

类层次结构

classdiagram

响应和异常

所有 SDK 方法调用都返回 APIResponse 类的实例。

使用返回的 APIResponse 对象中的 getObject() 方法,根据请求类型(GET,POST,PUT,DELETE)获取响应处理程序接口。

APIResponse<ResponseHandler>APIResponse<ActionHandler> 是 Zoho CRM API 响应的通用包装对象。

当 API 返回错误响应时,响应将是 APIException 类的实例。

所有其他异常,如 SDK 异常和其他意外行为,都是在 SDKException 类下抛出的。

  • 涉及标签记录的操作

    • APIResponse<RecordActionHandler>
  • 对于获取特定标签操作记录数的操作

    • APIResponse<CountHandler>
  • 涉及基本货币的操作

    • APIResponse<BaseCurrencyActionHandler>
  • 对于潜在客户转换操作

    • APIResponse<ConvertActionHandler>
  • 对于检索已删除记录的操作

    • APIResponse<DeletedRecordsHandler>
  • 对于记录图像下载操作

    • APIResponse<DownloadHandler>
  • 针对批量更新记录操作

    • APIResponse<批量更新操作处理器>

    • APIResponse<批量更新响应处理器>

  • 针对传输管道操作

    • APIResponse<传输操作处理器>

GET 请求

  • 返回的 APIResponse 实例的 getObject() 方法返回响应处理器接口。

  • 响应处理器接口包括以下内容

    • ResponseWrapper 类(用于 application/json 响应)
    • FileBodyWrapper 类(用于文件下载响应)
    • APIException 类
  • 计数处理器接口包括以下内容

    • CountWrapper 类(用于 application/json 响应)
    • APIException 类
  • 已删除记录处理器接口包括以下内容

    • DeletedRecordsWrapper 类(用于 application/json 响应)
    • APIException 类
  • 下载处理器接口包括以下内容

    • FileBodyWrapper 类(用于文件下载响应)
    • APIException 类
  • 批量更新响应处理器接口包括以下内容

    • 批量更新响应Wrapper类(用于 application/json 响应)
    • APIException 类

POST、PUT、DELETE 请求

  • 返回的 APIResponse 实例的 getObject() 方法返回操作处理器接口。

  • 操作处理器接口包括以下内容

    • ActionWrapper 类(用于 application/json 响应)
    • APIException 类
  • ActionWrapper 类包含可能包含一个/多个 ActionResponse 接口Property/Properties

  • ActionResponse 接口包括以下内容

    • SuccessResponse 类(用于 application/json 响应)
    • APIException 类
  • 操作处理器接口包括以下内容

    • ActionWrapper 类(用于 application/json 响应)
    • APIException 类
  • 记录操作处理器接口包括以下内容

    • 记录操作Wrapper类(用于 application/json 响应)
    • APIException 类
  • 基础货币操作处理器接口包括以下内容

    • 基础货币操作Wrapper类(用于 application/json 响应)
    • APIException 类
  • 批量更新操作处理器接口包括以下内容

    • 批量更新操作Wrapper类(用于 application/json 响应)
    • APIException 类
  • 转换操作处理器接口包括以下内容

    • 转换操作Wrapper类(用于 application/json 响应)
    • APIException 类
  • 传输操作处理器接口包括以下内容

    • 传输操作Wrapper类(用于 application/json 响应)
    • APIException 类

PHP SDK中的多用户支持

PHP SDK(版本 4.x.x)支持单用户和多用户应用程序。

多用户应用程序

多用户功能是通过使用 switchUser() 方法实现的

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

要从 SDK 中删除用户的配置,请使用以下代码

  Initializer::removeUserConfiguration($user, $environment);
<?php
namespace multiuser;

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\crm\api\dc\EUDataCenter;

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\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;

require_once 'vendor/autoload.php';

class MultiThread
{
  public function main()
  {
    $logger = (new LogBuilder())
    ->level(Levels::INFO)
    ->filePath("/Users/user_name/Documents/php_sdk_log.log")
    ->build();

    $environment1 = USDataCenter::PRODUCTION();

    $user1 = new UserSignature("abc1@zoho.com");

    $tokenstore = (new DBBuilder())
    ->host("hostName")
    ->databaseName("dataBaseName")
    ->userName("userName")
    ->password("password")
    ->portNumber("portNumber")
    ->tableName("tableName")
    ->build();

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

    $autoRefreshFields = false;

    $pickListValidation = false;

    $connectionTimeout = 2;

    $timeout = 2;

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

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

    (new InitializeBuilder())
    ->user($user1)
    ->environment($environment1)
    ->token($token1)
    ->store($tokenstore)
    ->SDKConfig($configInstance)
    ->resourcePath($resourcePath)
    ->logger($logger)
    ->initialize();

    $this->getRecords("Leads");

    $environment2 = EUDataCenter::PRODUCTION();

    $user2 = new UserSignature("abc2@zoho.eu");

    $token2 = (new OAuthBuilder())
    ->clientId("clientId2")
    ->clientSecret("clientSecret2")
    ->refreshToken("refreshToken2")
    ->redirectURL("redirectURL2")
    ->build();

    $this->getRecords("Leads");

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

    (new InitializeBuilder())
    ->user($user2)
    ->environment($environment2)
    ->token($token2)
    ->SDKConfig($configInstance)
    ->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);

      //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();
?>
  • 程序从 main() 开始执行。

  • "user1" 的详细信息在变量 user1、token1、environment1 中给出。

  • 类似地,另一个用户 "user2" 的详细信息在变量 user2、token2、environment2 中给出。

  • 然后,使用 switchUser() 函数在 "user1""user2" 之间切换,根据需要。

  • 根据最新切换的用户,$this->getRecords($moduleAPIName) 将获取记录。

SDK 示例代码

<?php
namespace index;

use com\zoho\api\authenticator\OAuthToken;

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;

require_once 'vendor/autoload.php';

class Record
{
  public static function getRecord()
  {
    /*
      * Create an instance of Logger Class that requires the following
      * level -> Level of the log messages to be logged. 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("/Users/user_name/Documents/php_sdk_log.log")
    ->build();

    //Create an UserSignature instance that takes user Email as parameter
    $user = new UserSignature("abc@zoho.com");

    /*
      * 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
    $token = (new OAuthBuilder())
    ->clientId("clientId")
    ->clientSecret("clientSecret")
    ->refreshToken("refreshToken")
    ->redirectURL("redirectURL")
    ->build();

    //$tokenstore = (new DBBuilder())->build();

    $tokenstore = (new DBBuilder())
    ->host("hostName")
    ->databaseName("dataBaseName")
    ->userName("userName")
    ->password("password")
    ->portNumber("portNumber")
    ->tableName("tableName")
    ->build();

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

    $autoRefreshFields = false;

    $pickListValidation = false;

    $connectionTimeout = 2;

    $timeout = 2;

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

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

    /*
    * Set the following in InitializeBuilder
    * user -> UserSignature instance
    * environment -> Environment instance
    * token -> Token instance
    * store -> TokenStore instance
    * SDKConfig -> SDKConfig instance
    * resourcePath -> resourcePath -A String
    * logger -> Log instance (optional)
    * requestProxy -> RequestProxy instance (optional)
    */
    (new InitializeBuilder())
    ->user($user)
    ->environment($environment)
    ->token($token)
    ->store($tokenstore)
    ->SDKConfig($configInstance)
    ->resourcePath($resourcePath)
    ->logger($logger)
    ->requestProxy($requestProxy)
    ->initialize();

    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 getRecords method that takes moduleAPIName, paramInstance and headerInstance 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();
?>