bogdanhabic/help-scout-api

Help Scout API客户端

该软件包的官方仓库似乎已丢失,因此软件包已被冻结。

1.8.2 2016-06-15 14:27 UTC

This package is not auto-updated.

Last update: 2019-06-29 02:17:28 UTC


README

PHP包装的Help Scout API和Webhooks实现。更多详细信息请访问我们的开发者网站

版本1.8.1已发布

请参阅变更日志以获取详细信息。

要求

  • PHP 5.3.x
  • curl
  • shuber/curl

安装

.Zip + Composer

下载.zip文件并解压缩。进入目录后运行composer install

手动安装

require_once '/path/to/shuber/curl/lib/curl.php';
include_once '/path/to/helpscout/helpscout-api-php/src/HelpScout/ApiClient.php'

示例用法:API

include 'HelpScout/ApiClient.php';

use HelpScout\ApiClient;

$hs = ApiClient::getInstance();
$hs->setKey('your-api-key-here');

$mailboxes = $hs->getMailboxes();
if ($mailboxes) {
    // do something
}

$mailbox = $hs->getMailbox(99);
if ($mailbox) {
    $mailboxName = $mailbox->getName();
    $folders = $mailbox->getFolders();
    // do something
}

$conversation = $hs->getConversation(999);
if ($conversation) {
    // do something
    $threads = $conversation->getThreads();
    foreach($threads as $thread) {
        if ($thread instanceof \HelpScout\model\thread\LineItem) {
          // do something else
          continue;
        }
        if ($thread instanceof \HelpScout\model\thread\ConversationThread) {
          // do something again
        }
    }
}

// to get page 2 of a list of conversations:
$list = $hs->getConversationsForMailbox(99, array('page' => 2));

// to get all the closed conversations:
$closed = $hs->getConversationsForMailbox(99, array('page' => 1, 'status' => 'closed'));

// to get page 2 of a list of conversations,
// while only returning the "id" and "number" attributes on a conversation:
$convos = $hs->getConversationsForMailbox(99, array('page' => 2), array('id', 'number'));

// to get page 2 conversations from a specific folder:
$convos = $hs->getConversationsForFolder(99, 22, array('page' => 2)); // where 99=MailboxId and 22=FolderId


// to create a new conversation with a note and an attachment
$at = new \HelpScout\model\Attachment();
$at->load('/path/to/some/image.jpg');

$hs->createAttachment($at);

$note = new \HelpScout\model\thread\Note();
$note->setBody('Hey this is a note');
$note->addAttachment($at);

// if you already know the ID of the Help Scout user, you can simply get a ref
$userRef = $hs->getUserRefProxy(4);

$note->setCreatedBy($userRef);

$convo = new \HelpScout\model\Conversation();
$convo->setMailbox($hs->getMailboxProxy(2431));
$convo->setCreatedBy($userRef);
$convo->setSubject('Note test');

// every conversation must be tied to a customer
$convo->setCustomer($customerRef);

$convo->addLineItem($note);

$hs->createConversation($convo);

字段选择器

字段选择器可以是一个字符串或一个数组。

当使用字段选择器时,将返回一个包含指定字段的JSON对象。如果没有指定字段,将返回正确的对象。例如,以下代码将返回一个包含'名称'和'电子邮件'字段的JSON对象。

$mailbox = ApiClient::getInstance()->getMailbox(99, array('name','email'));

返回的JSON

{
    "name": "My Mailbox",
    "email": "help@mymailbox.com"
}

API客户端方法

邮箱

  • getMailboxes($page=1, $fields=null)
  • getMailbox($mailboxId, $fields=null)

文件夹

  • getFolders($mailboxId, $page=1, $fields=null)

对话

  • getConversationsForFolder($mailboxId, $folderId, array $params=array(), $fields=null)
  • getConversationsForMailbox($mailboxId, array $params=array(), $fields=null)
  • getConversationsForCustomerByMailbox($mailboxId, $customerId, array $params=array(), $fields=null)
  • getConversation($conversationId, $fields=null)
  • createConversation($conversation)
  • createThread($conversationId, $thread)
  • updateConversation($conversation)
  • deleteConversation($id)

附件

  • getAttachmentData($attachmentId)
  • createAttachment($attachment)
  • deleteAttachment($id)

客户

  • getCustomers($page=1, $fields=null)
  • searchCustomers($firstName=null, $lastName=null, $email=null, $page=1, $fields=null)
  • 通过电子邮件搜索客户(searchCustomersByEmail($email, $page=1, $fields=null))
  • 通过姓名搜索客户(searchCustomersByName($firstName, $lastName, $page=1, $fields=null))
  • 获取客户(getCustomer($customerId, $fields=null))
  • 创建客户(createCustomer($customer))
  • 更新客户(updateCustomer($customer))

用户

  • 获取用户(getUsers($page=1, $fields=null))
  • 获取邮箱用户(getUsersForMailbox($mailboxId, $page=1, $fields=null))
  • 获取用户信息(getUser($userId, $fields=null))

报告(通过服务描述可用)

  • 获取对话报告(getConversationsReport())
  • 获取忙碌时间报告(getConversationsBusyTimesReport())
  • 获取新对话报告(getNewConversationsReport())
  • 获取对话钻取报告(getConversationsDrillDownReport())
  • 获取按字段钻取的报告(getConversationsDrillDownByFieldReport())
  • 获取新对话钻取报告(getNewConversationsDrillDownReport())
  • 获取文档报告(getDocsReport())
  • 获取满意度报告(getHappinessReport())
  • 获取满意度评分报告(getHappinessRatingsReport())
  • 获取生产力报告(getProductivityReport())
  • 获取首次响应时间生产力报告(getFirstResponseTimeProductivityReport())
  • 获取发送回复生产力报告(getRepliesSentProductivityReport())
  • 获取已解决生产力报告(getResolvedProductivityReport())
  • 获取解决时间生产力报告(getResolutionTimeProductivityReport())
  • 获取响应时间生产力报告(getResponseTimeProductivityReport())
  • 获取生产力钻取报告(getProductivityDrillDownReport())
  • 获取公司报告(getCompanyReport())
  • 获取受助客户团队报告(getCustomersHelpedTeamReport())
  • 获取公司钻取报告(getCompanyDrillDownReport())
  • 获取用户报告(getUserReport())
  • 获取用户对话历史报告(getUserConversationHistoryReport())
  • 获取用户受助客户报告(getUserCustomersHelpedReport())
  • 获取用户钻取报告(getUserDrillDownReport())
  • 获取用户回复报告(getUserRepliesReport())
  • 获取用户解决报告(getUserResolutionsReport())
  • 获取用户满意度报告(getUserHappinessReport())
  • 获取用户评分报告(getUserRatingsReport())
  • 获取受助客户公司报告(getCustomersHelpedCompanyReport())

示例用法:报告

include 'HelpScout/ApiClient.php';

use HelpScout\ApiClient;

$scout = ApiClient::getInstance();
$scout->setKey('your-api-key-here');

$report = $scout->getConversationsReport([
	'start' => '2014-01-01T00:00:00Z',
	'end' => '2014-12-31T23:59:59Z'
]);

报告方法不是硬编码在ApiClient类中,而是通过服务描述来“描述”。服务描述是PHP配置数组,用于声明方法名称、调用API的位置和方式,以及任何可用和/或必需的参数。

URL配置参数通过单个配置数组参数发送到ApiClient方法。$scout->getDocsReport($config)

通过调用$scout->getServiceDescriptionMethods()可以获取可用报告方法的列表。

示例用法:Webhooks

include 'HelpScout/Webhook.php';

$webhook = new \HelpScout\Webhook('secret-key-here');
if ($webhook->isValid()) {
  $eventType = $webhook->getEventType();
  switch($eventType) {
    case 'convo.created':
        $conversation = $webhook->getConversation();
        // do something
        break;
    case 'convo.deleted':
        $obj = $webhook->getObject();
        if ($obj) {
          $convoId = $obj->id;
          // do something
        }
        break;
    case 'customer.created':
        $customer = $webhook->getCustomer();
        // do something
        break;
  }
}

示例用法:自定义字段

获取邮箱的自定义字段

include 'HelpScout/ApiClient.php';

use HelpScout\ApiClient;

$scout = ApiClient::getInstance();
$scout->setKey('your-api-key-here');

$mailbox = $scout->getMailbox(1234);
$customFields = $mailbox->getCustomFields();

获取对话的自定义字段及其回复

$conversation = $scout->getConversation(1234);
$customFields = $conversation->getCustomFields();

为尚未填写的内容填写值

如果对话还没有填写任何字段

$conversation = $scout->getConversation(1234);
$mailbox = $scout->getMailbox($conversation->getMailbox()->getId());

$conversationFields = [];

foreach ($mailbox->getCustomFields() as $customField) {
    if ($customField->getId() == 88) {
        $field = clone $customField;
        $field->setValue('Foo');
        $conversationFields[] = $field;
    }
}

$conversation->setCustomFields($conversationFields);

$scout->updateConversation($conversation);

更新对话字段值

$conversation = $scout->getConversation(1234);

foreach ($conversation->getCustomFields() as $customField) {
    if ($customField->getId() == 88) {
        $field->setValue('Bar');
    }
}

$scout->updateConversation($conversation);

自定义字段验证

日期字段(DateFieldRef

必须是有效的日期,格式为YYYY-MM-DD(年-月-日)。

下拉字段(DropdownFieldRef

值必须是可用下拉选项之一的有效ID。

多行字段(MultiLineFieldRef

多行值的最大字符串长度为15000个字符。

数字字段(NumberFieldRef

数字值必须是数值。整数和十进制(浮点数)是允许的(例如:100或12.34)。

单行字段 (SingleLineFieldRef)

单行值的最大字符串长度为255个字符。

调试

通过调用setDebug(true)方法启用调试。

setDebug方法接受两个参数:第一个是一个boolean,用于开启或关闭调试(true=开启,false=关闭)。第二个(可选)参数是要保存调试输出文件的目录。如果没有传递目录,则输出将回显而不是写入日志文件。

示例输出

[Apr 02 20:54:28] DEBUG: request = {"id":49424262,"firstName":"John","lastName":"Doe","photoUrl":null,"photoType":null,"gender":"unknown","age":null,"organization":null,"jobTitle":null,"location":"Dallas, TX","createdAt":"2015-04-01T18:08:10Z","modifiedAt":"2015-04-02T15:09:37Z","background":null,"address":{"id":5678,"lines":["123 Main Street"],"city":"Dallas","state":"","postalCode":74206,"country":"US","createdAt":null,"modifiedAt":null},"socialProfiles":[],"emails":[],"phones":[],"chats":[],"websites":[]}; context: {"method":"PUT"}
[Apr 02 20:54:28] DEBUG: response = {"code":400,"error":"Input could not be validated","validationErrors":[{"property":"address:state","value":null,"message":"Value is required"}]}; context: {"method":"PUT"}
[Apr 02 20:54:28] ERROR: Input could not be validated; context: {"method":"PUT","code":400,"errors":[{"property":"address:state","value":null,"message":"Value is required"}]}

调试行由四个部分组成:时间戳 [Apr 02 20:54:28]、级别 DEBUG、消息和上下文。

上述调试输出示例代表3行调试文本,都是在同一个API调用中发生的,是一个更新客户的PUT方法。第一行是请求JSON,第二行是响应JSON,第三行是API错误及其从服务器的响应。

捕获API错误/异常

服务器返回的4**和5**错误通过API客户端处理。在从API服务器收到响应后,客户端会进行检查以确保请求成功。如果检测到4**或5**错误,客户端将抛出HelpScout\ApiException。这允许您轻松地捕获来自服务器的错误,无论是验证错误还是服务器无法访问。这可以防止您的应用程序崩溃并终止请求,并允许您恢复。

当API服务器返回错误时(例如:验证失败),错误将添加到异常中,并通过getErrors()方法访问。

示例

try {
    $scout->createConversation($conversation);
} catch (\HelpScout\ApiException $e) {
    echo $e->getMessage();
    echo "\n";
    print_r($e->getErrors());
}

输出如下

Array
(
    [0] => Array
        (
            [property] => createdBy
            [value] => 1234
            [message] => The specified createdBy is not valid
        )

    [1] => Array
        (
            [property] => customer
            [value] => 5678
            [message] => The specified customer is not valid
        )

    [2] => Array
        (
            [property] => mailbox
            [value] => 012345
            [message] => The specified mailbox is not valid
        )

)