HubSpot PHP SDK

repository·master·Indexed 42 days ago

https://github.com/hubspot/hubspot-api-php

A PHP client for the HubSpot API v3 that provides a structured, object-oriented interface for interacting with HubSpot services including CRM (contacts, objects) and Files. Requires PHP >= 8.1.

Tokens
1.9K
Snippets
6
Records
7
Agent score
4%

What's inside HubSpot

  1. Configure Retry Middleware for API failures

    master

    The SDK provides retry middleware to handle three failure scenarios: rate limiting (429), internal server errors (500–503, 520–599), and connection errors. By default, it retries up to 5 times (\HubSpot\RetryMiddlewareFactory::DEFAULT_MAX_RETRIES).

    Delay Helpers

    If no delay function is provided, Guzzle uses exponential backoff. You can provide custom delay logic using:

    • \HubSpot\Delay::getConstantDelayFunction(int $secondsDelay = 10): Fixed delay.
    • \HubSpot\Delay::getLinearDelayFunction(): Delay grows linearly with retry count.

    Implementation Example

    To use middleware, push them onto a Guzzle HandlerStack and pass that stack to a custom Guzzle client:

    $handlerStack = \GuzzleHttp\HandlerStack::create();
    
    // Retry on 429 with a constant 10-second delay
    $handlerStack->push(
        \HubSpot\RetryMiddlewareFactory::createRateLimitMiddleware(
            \HubSpot\Delay::getConstantDelayFunction()
        )
    );
    
    // Retry on 5xx errors (exponential backoff by default)
    $handlerStack->push(
        \HubSpot\RetryMiddlewareFactory::createInternalErrorsMiddleware()
    );
    
    // Retry on connection errors (cURL codes 52, 55, 56)
    $handlerStack->push(
        \HubSpot\RetryMiddlewareFactory::createConnectionErrorsMiddleware()
    );
    
    $client = new \GuzzleHttp\Client(['handler' => $handlerStack]);
    $hubspot = \HubSpot\Factory::createWithAccessToken('your-access-token', $client);
    $handlerStack = \GuzzleHttp\HandlerStack::create();
    
    $handlerStack->push(
        \HubSpot\RetryMiddlewareFactory::createRateLimitMiddleware(
            \HubSpot\Delay::getConstantDelayFunction()
        )
    );
    
    $handlerStack->push(
        \HubSpot\RetryMiddlewareFactory::createInternalErrorsMiddleware()
    );
    
    $handlerStack->push(
        \HubSpot\RetryMiddlewareFactory::createConnectionErrorsMiddleware()
    );
    
    $client = new \GuzzleHttp\Client(['handler' => $handlerStack]);
    $hubspot = \HubSpot\Factory::createWithAccessToken('your-access-token', $client);
  2. Instantiate the API Client using Factory

    master

    The \HubSpot\Factory class is the primary way to create an API client instance. You can authenticate using an access token (from a Private App or OAuth2) or a developer API key.

    Using an Access Token

    $hubspot = \HubSpot\Factory::createWithAccessToken('your-access-token');

    Using a Developer API Key

    $hubspot = \HubSpot\Factory::createWithDeveloperApiKey('your-developer-apikey');

    Using a Custom Guzzle Client

    If you need to provide a custom Guzzle client (e.g., for specific configuration or middleware):

    $client = new \GuzzleHttp\Client([...]);
    $hubspot = \HubSpot\Factory::createWithAccessToken('your-access-token', $client);

    Customizing Base Path and Auth via Config

    You can pass a custom configuration object to the create method:

    $config = new \GuzzleHttp\Client();
    $config->setBasePath('*');
    $config->setAccessToken('*');
    $config->setDeveloperApiKey('*');
    
    $hubspot = \HubSpot\Factory::create(null, $config);
  3. Upload files to HubSpot

    master

    Use the files() namespace to upload files. You can pass an SplFileObject and a JSON-encoded configuration for file properties like access level and TTL.

    $file = new \SplFileObject('file path');
    $response = $hubspot->files()->filesApi()->upload($file, null, '/', null, null, json_encode([
        'access' => 'PRIVATE',
        'ttl' => 'P2W',
        'overwrite' => false,
        'duplicateValidationStrategy' => 'NONE',
        'duplicateValidationScope' => 'EXACT_FOLDER'
    ]));
    $file = new \SplFileObject('file path');
    $response = $hubspot->files()->filesApi()->upload($file, null, '/', null, null, json_encode([
        'access' => 'PRIVATE',
        'ttl' => 'P2W',
        'overwrite' => false,
        'duplicateValidationStrategy' => 'NONE',
        'duplicateValidationScope' => 'EXACT_FOLDER'
    ]) );
  4. Use apiRequest for unmapped endpoints

    master

    If the SDK does not yet have a wrapped implementation for a specific HubSpot endpoint, you can use the apiRequest method to call it directly. This method benefits from all configured client parameters (auth, base URL, etc.).

    apiRequest options

    An options array can include:

    • method (string): HTTP method (e.g., GET, POST). Default: GET.
    • path (string): URL path (e.g., /crm/v3/objects/contacts).
    • headers (array): HTTP headers.
    • body (mixed): Request body. If defaultJson is true, this is transformed to a JSON string.
    • authType (enum): none, accessToken, hapikey, or developerApiKey. Defaults to the configured auth type.
    • baseUrl (string): Base URL. Default: https://api.hubapi.com.
    • qs (array): Query parameters.
    • defaultJson (bool): If true, adds Content-Type: application/json and Accept: application/json, */*;q=0.8 headers and transforms the body to JSON. Default: true.

    Examples

    Direct PUT request:

    $response = $hubspot->apiRequest([
        'method' => 'PUT',
        'path' => '/some/api/not/wrapped/yet',
        'body' => ['key' => 'value'],
    ]);

    GET request via path:

    $response = $hubspot->apiRequest([
        'path' => '/crm/v3/objects/contacts',
    ]);
  5. Manage CRM Contacts

    master

    Use the crm()->contacts() namespace to perform CRUD operations on contacts.

    Get a page of contacts

    $response = $hubspot->crm()->contacts()->basicApi()->getPage();

    Get a contact by email

    $contact = $hubSpot->crm()->contacts()->basicApi()->getById('example@example.com', null, null, null, false, 'email');

    Search for contacts

    To search, construct a PublicObjectSearchRequest with Filter and FilterGroup objects:

    $filter = new \HubSpot\Client\Crm\Contacts\Model\Filter();
    $filter
        ->setOperator('EQ')
        ->setPropertyName('email')
        ->setValue($search);
    
    $filterGroup = new \HubSpot\Client\Crm\Contacts\Model\FilterGroup();
    $filterGroup->setFilters([$filter]);
    
    $searchRequest = new \HubSpot\Client\Crm\Contacts\Model\PublicObjectSearchRequest();
    $searchRequest->setFilterGroups([$filterGroup]);
    $searchRequest->setProperties(['firstname', 'lastname', 'date_of_birth', 'email']);
    
    $contactsPage = $hubspot->crm()->contacts()->searchApi()->doSearch($searchRequest);

    Create, Update, and Archive contacts

    Create:

    $contactInput = new \HubSpot\Client\Crm\Contacts\Model\SimplePublicObjectInput();
    $contactInput->setProperties(['email' => 'example@example.com']);
    $contact = $hubspot->crm()->contacts()->basicApi()->create($contactInput);

    Update:

    $newProperties = new \HubSpot\Client\Crm\Contacts\Model\SimplePublicObjectInput();
    $newProperties->setProperties(['email' => 'updatedExample@example.com']);
    $hubspot->crm()->contacts()->basicApi()->update($contactId, $newProperties);

    Archive:

    $hubspot->crm()->contacts()->basicApi()->archive($contactId);