Intercom PHP Library

repository·master·Indexed 43 days ago

https://github.com/intercom/intercom-php

A high-level, type-safe PHP SDK for interacting with Intercom's APIs. Built for PHP 8.1+, it provides interfaces for managing admins, articles, help centers, and AI content import sources, as well as tools for reporting data exports and handling paginated results.

Tokens
49.5K
Snippets
235
Records
244
Agent score
54%

What's inside Intercom

  1. Iterate through paginated results

    master

    List endpoints return a Pager<T> object. You can iterate over this object directly to automatically fetch all items across all pages, or you can iterate page-by-page using getPages().

    // Automatic iteration over all items
    $items = $client->articles->list(['limit' => 10]);
    foreach ($items as $item) {
        var_dump($item);
    }
    
    // Manual page-by-page iteration
    foreach ($items->getPages() as $page) {
        foreach ($page->getItems() as $pageItem) {
            var_dump($pageItem);
        }
    }
  2. Manage Custom Object Instances

    master

    The customObjectInstances unstable API allows you to perform CRUD operations on custom object instances. All methods require a customObjectTypeIdentifier (the unique identifier of the custom object type).

    Fetching Instances

    • By External ID: Use getCustomObjectInstancesByExternalId with a GetCustomObjectInstancesByExternalIdRequest.
    • By Intercom ID: Use getCustomObjectInstancesById with a GetCustomObjectInstancesByIdRequest.

    Creating and Updating

    • Create or Update: Use createCustomObjectInstances with a CreateOrUpdateCustomObjectInstanceRequest. You can provide an externalId, externalCreatedAt, externalUpdatedAt, and an array of customAttributes.

    Deleting

    • By External ID: Use deleteCustomObjectInstancesById with a DeleteCustomObjectInstancesByIdRequest.
    • By Intercom ID: Use deleteCustomObjectInstancesByExternalId with a DeleteCustomObjectInstancesByExternalIdRequest.
    // Example: Create or update a custom object instance
    $client->customObjectInstances->createCustomObjectInstances(
        new CreateOrUpdateCustomObjectInstanceRequest([
            'customObjectTypeIdentifier' => 'Order',
            'externalId' => '123',
            'externalCreatedAt' => 1392036272,
            'externalUpdatedAt' => 1392036272,
            'customAttributes' => [
                'order_number' => 'ORDER-12345',
                'total_amount' => 'custom_attributes',
            ],
        ]),
    );
  3. Basic usage of IntercomClient

    master

    To use the SDK, instantiate Intercom\IntercomClient with your access token. You can then access various API resources through properties on the client instance.

    <?php
    
    namespace Example;
    
    use Intercom\IntercomClient;
    use Intercom\AiContent\Requests\CreateContentImportSourceRequest;
    
    $client = new IntercomClient(
        token: '<token>',
    );
    $client->aiContent->createContentImportSource(
        new CreateContentImportSourceRequest([
            'syncBehavior' => 'api',
            'url' => 'https://www.example.com',
        ]),
    );
  4. Migrate from the Legacy SDK

    master

    The new SDK exports the legacy SDK under the Intercom\Legacy\ namespace to facilitate migration.

    Recommended migration steps:

    1. Upgrade the package to ^5.1.0.
    2. Search and replace all imports from Intercom\... to Intercom\Legacy\....
    3. Gradually replace Intercom\Legacy\... imports with the new Intercom\... imports.
    use Intercom\IntercomClient;
    use Intercom\Legacy\IntercomClient as LegacyIntercomClient;
    
    $intercom = new IntercomClient();
    $legacyClient = new LegacyIntercomClient();
  5. Handle API exceptions

    master

    The SDK throws exceptions when the API returns a non-success status code (4xx or 5xx). You should catch Intercom\Exceptions\IntercomApiException to access specific error details like the status code and response body.

    use Intercom\Exceptions\IntercomApiException;
    use Intercom\Exceptions\IntercomException;
    
    try {
        $response = $client->aiContent->createContentImportSource(...);
    } catch (IntercomApiException $e) {
        echo 'API Exception occurred: ' . $e->getMessage() . "\n";
        echo 'Status Code: ' . $e->getCode() . "\n";
        echo 'Response Body: ' . $e->getBody() . "\n";
    }
  6. Initialize the legacy IntercomClient

    master

    The Intercom\Legacy\IntercomClient is a backward-compatibility version of the Intercom client. It can be authenticated using either an App ID with an API Key (Basic Auth) or a Bearer Token.

    To use it, instantiate the class with your credentials. You can also provide an optional array of extra request headers that will be sent with every API request.

    use Intercom\Legacy\IntercomClient;
    
    // Using App ID and API Key (Basic Auth)
    $client = new IntercomClient('YOUR_APP_ID', 'YOUR_API_KEY');
    
    // Using a Bearer Token
    $client = new IntercomClient('YOUR_BEARER_TOKEN');
    
    // With extra headers
    $client = new IntercomClient('YOUR_TOKEN', null, ['X-Custom-Header' => 'value']);
  7. Initialize the IntercomClient

    master

    To interact with the Intercom API, instantiate the Intercom\IntercomClient class. You must provide an authentication token either by passing it to the constructor or by setting the INTERCOM_API_KEY environment variable.

    You can also provide an optional $options array to configure the client's behavior, such as custom headers, timeouts, or a custom Guzzle HTTP client.

    use Intercom\IntercomClient;
    
    // Option 1: Pass token directly
    $client = new IntercomClient('YOUR_ACCESS_TOKEN');
    
    // Option 2: Use environment variable INTERCOM_API_KEY
    // putenv('INTERCOM_API_KEY=your_token_here');
    // $client = new IntercomClient();
    
    // Option 3: With custom options
    $client = new IntercomClient('YOUR_ACCESS_TOKEN', [
        'timeout' => 5.0,
        'headers' => ['X-Custom-Header' => 'value'],
    ]);
  8. Create a new Ticket Type

    master

    Create a new ticket type using the unstable ticketTypes endpoint.

    Note: Every ticket type is automatically created with two default attributes: _default_title_ and _default_description_. For the icon property, it is recommended to use an emoji from the Twemoji Cheatsheet.

    $client->unstable->ticketTypes->createTicketType(
        [
            'key' => "value",
        ],
    );
  9. Set an Admin as away for the Inbox

    master

    Use $client->admins->away() to update an admin's away status. This requires a ConfigureAwayAdminRequest object.

    Parameters for ConfigureAwayAdminRequest:

    • adminId (int): The unique identifier of the admin.
    • awayModeEnabled (bool): Set to true to change the status to away.
    • awayModeReassign (bool): Set to true to assign new conversation replies to your default inbox.
    • awayStatusReasonId (?int): The unique identifier for the away status reason.
    $client->admins->away(
        new ConfigureAwayAdminRequest([
            'adminId' => 1,
            'awayModeEnabled' => true,
            'awayModeReassign' => true,
            'awayStatusReasonId' => 12345,
        ]),
    );
  10. Iterate over all companies using the Scroll API

    master

    For large datasets exceeding 10,000 companies, use scroll instead of standard pagination to avoid performance issues and errors.

    Usage Rules:

    • Only one scroll can be open per app at a time.
    • Scrolls expire after 1 minute of inactivity.
    • To start, send a request to the scroll endpoint without a parameter. For subsequent requests, use the scrollParam returned in the previous response.

    Error Handling:

    • If you encounter a HTTP 500 error with the message "Request failed due to an internal network error. Please restart the scroll operation.", you must restart the entire scroll operation from the beginning; you cannot resume from a specific point.
    $client->companies->scroll(
        new ScrollCompaniesRequest([
            'scrollParam' => 'scroll_param',
        ]),
    );