Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Intercom Php Laravel Package

intercom/intercom-php

Intercom PHP SDK for PHP 8.1+ that makes it easy to call Intercom APIs. Instantiate IntercomClient with your token, use typed request objects, handle IntercomApiException for 4xx/5xx errors, and iterate list endpoints with automatic pagination via Pager.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require intercom/intercom-php
    

    Requires PHP 8.1+.

  2. First Use Case: Initialize the client with your Intercom API token and call an endpoint (e.g., create a contact):

    use Intercom\IntercomClient;
    use Intercom\Contacts\Requests\CreateContactRequest;
    
    $client = new IntercomClient(token: 'YOUR_INTERCOM_TOKEN');
    $response = $client->contacts->create(
        new CreateContactRequest([
            'email' => 'user@example.com',
            'name' => 'John Doe',
        ])
    );
    
  3. Where to Look First:

    • README.md: Covers installation, basic usage, and advanced features.
    • IntercomClient class: Entry point for all API interactions.
    • Requests/ namespace: Predefined request classes for each endpoint (e.g., CreateContactRequest).

Implementation Patterns

Core Workflows

  1. CRUD Operations: Use request classes (e.g., CreateContactRequest, UpdateCompanyRequest) for type safety and validation:

    // Create
    $client->contacts->create(new CreateContactRequest($data));
    
    // Read (single)
    $contact = $client->contacts->get('123');
    
    // Read (paginated)
    foreach ($client->contacts->list(['limit' => 50]) as $contact) {
        // Process each contact
    }
    
    // Update
    $client->contacts->update('123', new UpdateContactRequest($data));
    
    // Delete (soft/hard)
    $client->contacts->archive('123'); // Soft delete
    $client->contacts->delete('123');  // Hard delete (v3.2.0+)
    
  2. Pagination: Leverage the Pager interface for automatic pagination:

    $pager = $client->companies->list(['limit' => 100]);
    foreach ($pager as $company) {
        // Process each company
    }
    // Or iterate pages manually:
    foreach ($pager->getPages() as $page) {
        foreach ($page->getItems() as $item) {
            // Handle items
        }
    }
    
  3. Error Handling: Catch IntercomApiException for API errors and IntercomException for SDK issues:

    try {
        $client->contacts->create(...);
    } catch (IntercomApiException $e) {
        logError($e->getMessage(), $e->getCode(), $e->getBody());
    }
    
  4. Legacy Migration: Use the Legacy namespace alongside the new SDK during transition:

    use Intercom\Legacy\IntercomClient as LegacyClient;
    $legacyClient = new LegacyClient('token');
    

Integration Tips

  1. Dependency Injection (Laravel): Bind the client in AppServiceProvider:

    public function register()
    {
        $this->app->singleton(IntercomClient::class, function ($app) {
            return new IntercomClient(token: config('services.intercom.token'));
        });
    }
    

    Inject via constructor:

    public function __construct(private IntercomClient $intercom) {}
    
  2. Custom HTTP Client: Override Guzzle defaults (e.g., timeouts, middleware):

    $client = new IntercomClient(options: [
        'client' => new \GuzzleHttp\Client([
            'timeout'  => 10.0,
            'headers'  => ['User-Agent' => 'MyApp/1.0'],
        ]),
    ]);
    
  3. Rate Limiting: Check headers for limits:

    $response = $client->contacts->list([]);
    $rateLimit = $response->getRateLimit(); // Returns RateLimit object
    
  4. API Versioning: Use baseUrl option for non-default endpoints (e.g., unstable APIs):

    $client = new IntercomClient(token: 'token', options: [
        'baseUrl' => 'https://api.intercom.io/unstable',
    ]);
    

Gotchas and Tips

Pitfalls

  1. Token Security:

    • Never hardcode tokens in version control. Use Laravel’s .env or a secrets manager.
    • Avoid logging tokens in error messages (sanitize with str_replace).
  2. Pagination Edge Cases:

    • Empty pages may trigger OutOfBoundsException. Validate $pager->isEmpty() before iteration.
    • Large datasets: Use limit to avoid hitting API rate limits.
  3. Legacy Breaking Changes:

    • v4.0.0+ uses HTTPPlug (not Guzzle directly). Ensure your project includes a compatible adapter (e.g., php-http/guzzle7-adapter).
    • v5.0.0+ is auto-generated. Avoid manual edits to the SDK (they’ll be overwritten).
  4. Timeouts and Retries:

    • Default timeout: 30 seconds. Override per-request:
      $client->contacts->create(..., options: ['timeout' => 5.0]);
      
    • Retries: Default 2 attempts for 429/5xx errors. Disable with maxRetries: 0.
  5. Soft vs. Hard Deletes:

    • archive() (soft delete) is reversible via API. delete() (hard delete) is permanent (v3.2.0+).

Debugging Tips

  1. Enable Guzzle Debugging: Add middleware to log requests/responses:

    $handlerStack = \GuzzleHttp\HandlerStack::create();
    $handlerStack->push(\GuzzleHttp\Middleware::tap(function ($request, $options) {
        \Log::debug('Intercom Request:', [
            'url' => (string) $request->getUri(),
            'method' => $request->getMethod(),
            'headers' => $request->getHeaders(),
        ]);
    }));
    $client = new IntercomClient(options: ['client' => new \GuzzleHttp\Client(['handler' => $handlerStack])]);
    
  2. Common HTTP Errors:

    • 401 Unauthorized: Invalid token or permissions.
    • 404 Not Found: Check endpoint URLs (e.g., contacts/{id} vs. companies/{id}).
    • 429 Too Many Requests: Implement exponential backoff or increase rate limits.
  3. Type Safety:

    • Use IDE autocompletion for request classes (e.g., CreateContactRequest fields).
    • Validate request data with Request::validate() if extending the SDK.

Extension Points

  1. Custom Requests: Extend the SDK by creating new request classes (e.g., for undocumented endpoints):

    namespace App\Intercom\Requests;
    use Intercom\Requests\Request;
    
    class CustomRequest extends Request {
        public function __construct(array $data) {
            parent::__construct('POST', '/custom-endpoint', $data);
        }
    }
    

    Register in IntercomClient via setRequestFactory.

  2. Middleware: Add request/response processing:

    $handlerStack = \GuzzleHttp\HandlerStack::create();
    $handlerStack->push(\GuzzleHttp\Middleware::mapRequest(function ($request) {
        $request = $request->withHeader('X-Custom-Header', 'value');
        return $request;
    }));
    
  3. Testing: Mock the client for unit tests:

    $mockClient = $this->createMock(\Psr\Http\Client\ClientInterface);
    $client = new IntercomClient(options: ['client' => $mockClient]);
    

Laravel-Specific Quirks

  1. Queue Jobs: Offload Intercom API calls to queues to avoid timeouts:

    use Illuminate\Bus\Queueable;
    use Intercom\IntercomClient;
    
    class SyncContactJob implements Queueable {
        public function handle(IntercomClient $intercom) {
            $intercom->contacts->create(...);
        }
    }
    
  2. Service Container: Override defaults in config/services.php:

    'intercom' => [
        'token' => env('INTERCOM_TOKEN'),
        'timeout' => env('INTERCOM_TIMEOUT', 30),
    ],
    

    Then inject via constructor with type-hinting.

  3. Events: Trigger Laravel events after Intercom operations:

    event(new ContactSynced($contactData));
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky