GithubHelp home page GithubHelp logo

hubspot / hubspot-php Goto Github PK

View Code? Open in Web Editor NEW
347.0 35.0 192.0 1.56 MB

HubSpot PHP API Client

License: Other

PHP 99.89% Shell 0.02% Dockerfile 0.09%
hubspot php api-wrapper api-rest api api-client

hubspot-php's Introduction

HubSpot PHP API client

Version Total Downloads Build Status License

Hubspot is a marketing, sales, and service software that helps your business grow without compromise. Because “good for the business” should also mean “good for the customer.”

This library supports only legacy API

Please consider switching to the latest API.

Setup

Composer:

composer require "hubspot/hubspot-php"

Sample apps

Link

Quickstart

Examples Using Factory

All following examples assume this step.

$hubspot = SevenShores\Hubspot\Factory::create('api-key');

// OR create with access token (OAuth2 or Private App)

$hubspot = SevenShores\Hubspot\Factory::createWithAccessToken('access-token');

// OR instantiate by passing a configuration array.
// The only required value is the 'key'
// Please note: as of November 30, 2022, HubSpot API Keys are being deprecated and are no longer supported.

$hubspot = new SevenShores\Hubspot\Factory([
    'key'      => 'demo',
    'oauth2'   => false, // default
]);

// Then you can call a resource
// When referencing endpoints, use camelCase

$hubspot->contactlists

You can find more information about oauth2 access tokens here and about private app access token here.

Note: You can prevent any error handling provided by this package by passing following options into client creation routine: (applies also to Factory::create() and Factory::createWithAccessToken())

$hubspot = new SevenShores\Hubspot\Factory(
    [
        'key' => 'demo',
    ],
    null,
    [
        'http_errors' => false // pass any Guzzle related option to any request, e.g. throw no exceptions
    ],
    false // return Guzzle Response object for any ->request(*) call
);

By setting http_errors to false, you will not receive any exceptions at all, but pure responses. For possible options, see http://docs.guzzlephp.org/en/latest/request-options.html.

API Client comes with Middleware for implementation of Rate and Concurrent Limiting

It provides an ability to turn on retry for failed requests with statuses 429 or 500. You can read more about working within the HubSpot API rate limits here.

$handlerStack = \GuzzleHttp\HandlerStack::create();
$handlerStack->push(
    \SevenShores\Hubspot\RetryMiddlewareFactory::createRateLimitMiddleware(
        \SevenShores\Hubspot\Delay::getConstantDelayFunction()
    )
);

$handlerStack->push(
    \SevenShores\Hubspot\RetryMiddlewareFactory::createInternalErrorsMiddleware(
        \SevenShores\Hubspot\Delay::getExponentialDelayFunction(2)
    )
);

$guzzleClient = new \GuzzleHttp\Client(['handler' => $handlerStack]);

$config = [
    'key' => 'access token',
    'oauth2' => true,
];

$hubspot = new \SevenShores\Hubspot\Factory($config, new \SevenShores\Hubspot\Http\Client($config, $guzzleClient));

Get a single contact

$contact = $hubspot->contacts()->getByEmail("[email protected]");

echo $contact->properties->email->value;

Paginate through all contacts

// Get an array of 10 contacts
// getting only the firstname and lastname properties
// and set the offset to 123456
$response = $hubspot->contacts()->all([
    'count'     => 10,
    'property'  => ['firstname', 'lastname'],
    'vidOffset' => 123456,
]);

Working with the data is easy!

foreach ($response->contacts as $contact) {
    echo sprintf(
        "Contact name is %s %s." . PHP_EOL,
        $contact->properties->firstname->value,
        $contact->properties->lastname->value
    );
}

// Info for pagination
echo $response->{'has-more'};
echo $response->{'vid-offset'};

or if you prefer to use array access?

foreach ($response['contacts'] as $contact) {
    echo sprintf(
        "Contact name is %s %s." . PHP_EOL,
        $contact['properties']['firstname']['value'],
        $contact['properties']['lastname']['value']
    );
}

// Info for pagination
echo $response['has-more'];
echo $response['vid-offset'];

Now with response methods implementing PSR-7 ResponseInterface

$response->getStatusCode()   // 200;
$response->getReasonPhrase() // 'OK';
// etc...

Example Without Factory

<?php

require 'vendor/autoload.php';

use SevenShores\Hubspot\Http\Client;
use SevenShores\Hubspot\Endpoints\Contacts;

$client = new Client(['key' => 'access token', 'oauth2' => true,]);

$contacts = new Contacts($client);

$response = $contacts->all();

foreach ($response->contacts as $contact) {
    //
}

Example of using built in utils

<?php

require 'vendor/autoload.php';

use SevenShores\Hubspot\Utils\OAuth2;

$authUrl = OAuth2::getAuthUrl(
    'clientId',
    'http://localhost/callaback.php',
    'contacts'
);

or using Factory:

<?php

require 'vendor/autoload.php';

use SevenShores\Hubspot\Utils;

$authUrl = Utils::getFactory()->oAuth2()->getAuthUrl(
    'clientId',
    'http://localhost/callaback.php',
    'contacts'
);

Status

If you see something not planned, that you want, make an issue and there's a good chance I will add it.

  • Analytics API
  • Calendar API :updated:
  • Companies API :updated:
  • Company Properties API :updated:
  • Contacts API :updated:
  • Contact Lists API :updated:
  • Contact Properties API :updated:
  • Conversations Live Chat Widget API (Front End)
  • CMS Blog API (Blogs) :updated:
  • CMS Blog Authors API (BlogAuthors) :updated:
  • CMS Blog Comments API (BlogComments)
  • CMS Blog Post API (BlogPosts)
  • CMS Blog Topics API (BlogTopics)
  • CMS Domains API
  • CMS Files API (Files)
  • CMS HubDB API (HubDB) :updated:
  • CMS Layouts API
  • CMS Page Publishing API (Pages)
  • CMS Site Maps
  • CMS Site Search API
  • CMS Templates API
  • CMS URL Mappings API
  • CRM Associations API
  • CRM Extensions API
  • CRM Object Properties API (ObjectProperties) 🆕
  • CRM Pipelines API (CrmPipelines)
  • Deals API
  • Deal Pipelines API :deprecated:
  • Deal Properties API :updated:
  • Ecommerce Bridge API :updated:
  • Email Subscription API :updated:
  • Email Events API :updated:
  • Engagements API
  • Events API
  • Forms API :updated:
  • Line Items API 🆕
  • Marketing Email API
  • Owners API :updated:
  • Products API 🆕
  • Social Media API
  • Tickets API
  • Timeline API :updated:
  • Tracking Code API
  • Transactional Email API
  • Workflows API :updated:
  • Webhooks API

hubspot-php's People

Contributors

atanasiuk-hubspot avatar atymic avatar carcus88 avatar cincauhangus avatar denniskorbginski avatar domagoj03 avatar erikrorstrom avatar felixmaier1989 avatar ffauvel avatar geekdevs avatar graymouser avatar iillexial avatar jamesgraham avatar joesantos418 avatar johncongdon avatar ksvirkou-hubspot avatar lordthorzonus avatar lukevers avatar maddy2101 avatar massimilianobraglia avatar morrislaptop avatar nediam avatar nicobraintly avatar pixelao avatar ryanwinchester avatar siremi avatar stvsimons avatar thunder87 avatar wilsonpinto avatar yfaktor avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

hubspot-php's Issues

OAuth2 support

Recently, HubSpot rolled out their new authentication which is OAuth2. OAuth1 is still currently supported, and will be for quite some time since they're just now making the transition (I sent an email asking someone about that and got that confirmation), so both forms of OAuth should be supported.

http://developers.hubspot.com/docs/methods/oauth2/oauth2-overview

As mentioned in #50, I don't think this library should have anything to do with generating the access tokens or refreshing them, but just another way to sign the request. The difference here is that instead of signing requests ?access_token=token we now sign them with an Authorization header:

Authorization: Bearer {token}

I'm opening this ticket in case anyone stumbles upon this library in the time that I open this ticket and the time that I submit a pull request.

Case Sensitive File Names

In the file HubSpotService.php there is a function

 protected function getApiClassName($name)
 {
        return 'Fungku\\HubSpot\\Api\\' . ucfirst($name);
 }

This incorrectly returns the filename; for example contactproperties returns as Contactproperties where it should return as ContactProperties or the Api/ContactProperties.php needs to be changed to Api/Contactproperties.php

Any ideas on how to resolve this issue?

v2 API

Are you planning on updating the endpoints to the v2 API?

Tasks: Add more endpoints

API endpoints:

  • Endpoints
    • Blog (COS)
    • Blog Authors (COS)
    • Blog Posts (COS)
    • Blog Topics (COS)
    • Contacts
    • Contact Lists
    • Contact Properties
    • Email
    • Email Events
    • Engagements
    • Events
    • Files (COS)
    • Forms
    • Keywords
    • Page Publishing (COS)
    • Social Media
    • Workflows
    • Companies
    • Companies Properties
    • Deals
    • Templates (COS)

Create, Read, Update Company Fields with PHP 5.3

Hi,

We want to use Add, read, edit Company properties with HubSpot. We have PHP Version 5.3.
But I guess to modify company properties we need to use HubSpot V2 API, which is only supported on PHP Version >= 5.5.

Is there any way we can use HubSpot V1 API for updating company properties with PHP 5.3?
We do not want to update to PHP 5.5 as of now.

Please advice. Also suggest alternatives.

Thanks,
Prashant

Refreshing OAuth token

Hey everybody,
First thanks for creating this awesome package.

Is there a function to refresh the OAuth token? I can get the whole thing set up but I will need to refresh the OAuth token for further use.

Thanks

Namespace is not correct

File:
Factory.php

function __call($name, $arguments = null)
{
$resource = 'SevenShores\Hubspot\Resource' . ucfirst($name);
return new $resource($this->client);
}

'SevenShores\\Hubspot\\Resource\\' . ucfirst($name);

Resource

Folder???

Resources

Files API results in HTTP 504 Gateway Timeout

Just doing a simple request get metadata for files results in get a 504 timeout. When I make this request manually using curl it works fine. Here's some example code:


$hubspot = SevenShores\Hubspot\Factory::create('my-api-key');
$files = $hubspot->files()->all();

Release at the horizon?

Hi, thanks for merging my PR. Now of course the next question would be, what blocks a stable release? Can I help?

Kind regards
Anja

Contact

Ryan, keen to speak to you about some additional development work on this API - or at least get your thoughts. Would it be possible we can talk please?
[email protected]
Thanks
Matt

New Tag

Hey,

Could we get a new tag/release whenever you have time? Sorry for all the pushiness lately 😉.

Similar to #66, I'd rather use a tag than dev-master in production.

Documentation need updating?

Hi,

Now that the response is implementing PSR-7 ResponseInterface, does the README need to be updated? Or am I retrieving the results incorrectly?

This seems to be the only way to access the data:

        $response = $hubspot->blogs()->all();
        $blogs = $response->getData();
        foreach ($blogs->objects as $blog) {
            echo($blog->name);
        }

Thank you,
Gary Wong

Library leaks API key when an error occurs

Whenever there is an HTTP or validation error at Hubspot, the library will throw a GuzzleHttp\Exception\ClientException with a message:

Uncaught exception 'GuzzleHttp\Exception\ClientException' with message 'Client error: POST https://api.hubapi.com/contacts/v1/contact/createOrUpdate/email/[email protected]?hapikey=<redacted> resulted in a 400 Bad Request response: <redacted>

This then gets picked up by our logging systems spreading the API key everywhere.

I don't think the HTTP 4xx should result in a GuzzleHttp\Exception\ClientException, but a nice exception from this library which interprets the results from Hubspot and gives the domain exception message.

addContact should be post method in ContactList.php

public function addContact($list_id, $contact_ids)
{
    $endpoint = "/contacts/v1/lists/{$list_id}/add";
    $options['json'] = ['vids' => $contact_ids];

// here should be post not get
return $this->request('get', $endpoint, $options);
}

Mistake in README

$hubspot = new SevenShores\Hubspot\Factory([
  'key'      => 'demo',
  'oauth'    => false, // default
  'base_url' => 'https://api.hubapi.com' // default
],
[
  'http_errors' = true // pass any Guzzle related option to any request, e.g. throw no exceptions
],
false // return Guzzle Response object for any ->request(*) call
);

should be:

$hubspot = new SevenShores\Hubspot\Factory([
  'key'      => 'demo',
  'oauth'    => false, // default
  'base_url' => 'https://api.hubapi.com' // default
],
null, // <== Added null here
[
// => instead of =
  'http_errors' => true // pass any Guzzle related option to any request, e.g. throw no exceptions
],
false // return Guzzle Response object for any ->request(*) call
);

Create company - Bad Request

Hi,

I'm using version 0.9.0

With the following code

$hubspot = \Fungku\HubSpot\HubSpotService::make('**KEY**');
$company = $hubspot->companies()->create(
array(
    array(
        'property' => 'name',
        'value' => 'Hello'
    ),
    array(
        'property' => 'description',
        'value' => 'World'
    )
));

I get the following error

object(Fungku\HubSpot\Http\Response)#119 (2) {
  ["response":protected]=>
  object(GuzzleHttp\Psr7\Response)#123 (6) {
    ["reasonPhrase":"GuzzleHttp\Psr7\Response":private]=>
    string(11) "Bad Request"
    ["statusCode":"GuzzleHttp\Psr7\Response":private]=>
    int(400)
    ["headers":"GuzzleHttp\Psr7\Response":private]=>
    array(5) {
      ["access-control-allow-credentials"]=>
      array(1) {
        [0]=>
        string(5) "false"
      }
      ["content-type"]=>
      array(1) {
        [0]=>
        string(31) "application/json; charset=UTF-8"
      }
      ["content-length"]=>
      array(1) {
        [0]=>
        string(3) "291"
      }
      ["date"]=>
      array(1) {
        [0]=>
        string(29) "Fri, 27 May 2016 13:11:26 GMT"
      }
      ["connection"]=>
      array(1) {
        [0]=>
        string(5) "close"
      }
    }
    ["headerLines":"GuzzleHttp\Psr7\Response":private]=>
    array(5) {
      ["Access-Control-Allow-Credentials"]=>
      array(1) {
        [0]=>
        string(5) "false"
      }
      ["Content-Type"]=>
      array(1) {
        [0]=>
        string(31) "application/json; charset=UTF-8"
      }
      ["Content-Length"]=>
      array(1) {
        [0]=>
        string(3) "291"
      }
      ["Date"]=>
      array(1) {
        [0]=>
        string(29) "Fri, 27 May 2016 13:11:26 GMT"
      }
      ["Connection"]=>
      array(1) {
        [0]=>
        string(5) "close"
      }
    }
    ["protocol":"GuzzleHttp\Psr7\Response":private]=>
    string(3) "1.1"
    ["stream":"GuzzleHttp\Psr7\Response":private]=>
    object(GuzzleHttp\Psr7\Stream)#125 (7) {
      ["stream":"GuzzleHttp\Psr7\Stream":private]=>
      resource(13) of type (stream)
      ["size":"GuzzleHttp\Psr7\Stream":private]=>
      int(291)
      ["seekable":"GuzzleHttp\Psr7\Stream":private]=>
      bool(true)
      ["readable":"GuzzleHttp\Psr7\Stream":private]=>
      bool(true)
      ["writable":"GuzzleHttp\Psr7\Stream":private]=>
      bool(true)
      ["uri":"GuzzleHttp\Psr7\Stream":private]=>
      string(10) "php://temp"
      ["customMetadata":"GuzzleHttp\Psr7\Stream":private]=>
      array(0) {
      }
    }
  }
  ["data":protected]=>
  object(stdClass)#124 (5) {
    ["status"]=>
    string(5) "error"
    ["message"]=>
    string(30) "Property values were not valid"
    ["correlationId"]=>
    string(36) "4bd79dc4-90b1-4f15-ba3a-f794dac68de3"
    ["validationResults"]=>
    array(1) {
      [0]=>
      object(stdClass)#121 (4) {
        ["isValid"]=>
        bool(false)
        ["message"]=>
        string(24) "duplicate property value"
        ["error"]=>
        string(26) "DUPLICATE_PROPERTY_TO_SAVE"
        ["name"]=>
        string(0) ""
      }
    }
    ["requestId"]=>
    string(36) "2af2576e-f903-414a-a8ab-021a93468a7a"
  }
}

.env.example file

Hi, thank you for this nice collection, it is almost all I could wish for (except for the already mentioned OAuth2 token refresh ;) ).
I have a hopefully only small request, that would be to provide a .env.example file in order to list all parameters that are currently handled through dotenv.

Kind regards
Anja

Transactional Email API - having trouble sending custom properties

I've asked this on Stack Overflow as well. I hope you don't mind that I cross-post it here to give you a heads-up. http://stackoverflow.com/questions/42519131/sevenshores-hubspot-php-api-passing-customer-properties-into-singeemail-send

In short, can someone supply me with a code sample for sending custom properties to $hubspot-SingleEmail()->send? Here's what I have, and Hubspot doesn't seem to like it:

	$custom_properties = [
		[
			"name" => "item_1",
			"value" => "foloopy fosure"
		];
	];

	$message = [
		"to" => "[email protected]",
		"subject" => "testing signature request email"
	];

	$hubspot->SingleEmail()->send(
		$transaction_email_content_id,
		$message,
		$contact_properties,
		$custom_properties
	);

Thanks!

Error on GuzzleHttp/psr7 "Response could not be converted to int"

Hi there,
We're on Laravel 5.2 and we just updated from v1.0.0-rc.4 to v1.0.0 / 93df25e . Now when we try to update our hubspot contacts we're presented with this error below. We've had to revert back to v1.0.0-rc.4 / c29461f . Didn't see anything about this issue so making one for it.

The version of guzzlehttp/psr7 is ~1.3.1. Using method Contacts->createOrUpdate

[2017-01-25 15:52:25] local.ERROR: ErrorException: Object of class GuzzleHttp\Psr7\Response could not be converted to int in /var/www/api/vendor/guzzlehttp/psr7/src/Response.php:95 Stack trace: #0 /var/www/api/vendor/guzzlehttp/psr7/src/Response.php(95): Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(8, 'Object of class...', '/var/www/api/ve...', 95, Array) #1 /var/www/api/vendor/ryanwinchester/hubspot-php/src/Http/Client.php(101): GuzzleHttp\Psr7\Response->__construct(Object(GuzzleHttp\Psr7\Response)) #2 /var/www/api/vendor/ryanwinchester/hubspot-php/src/Resources/Contacts.php(46): SevenShores\Hubspot\Http\Client->request('post', 'https://api.hub...', Array)

Can't update contacts by email

Hello,

I saw #84 and #85.

However, I cannot update contacts by email and wondering if you can help. Here is my code. I'm getting 204 back which should be success. But nothing is happening.

Also, just to be sure, I'm using dev-master version. So #84 and #85 should be included in my dependency.

            # Instantiate new hubspot factory using the FD api key
            $hubspot = \SevenShores\Hubspot\Factory::create('1112222333');

            # URL decode the orignal email
            $update_email = $orig_email;

            # Get the contact from the original form submit
            $contact = $hubspot->contacts()->getByEmail($update_email);

            # Instantiate the current time
            $now = Carbon::now();

            # Now use their vid to update the contact with the proper name, phone and email
            $props["properties"] = [
                array("property" => "email", "value" => $email),
                array("property" => "firstname", "value" => $name),
                array("property" => "phone", "value" => $phone),
                array("property" => "fd_account_create_date", "value" => $now->timestamp * 1000),
            ];

            # Last, update the contact.
            $update_contact = $hubspot->contacts()->update($contact->vid, json_encode($props));

            if($update_contact->getStatusCode() == 204) {
                Slack::to('#dev-notifications')->send("New demo account created: " . $email);
            }

Am I doing anything wrong?

Call fails when contact does not exists

e.g.
$contact = $hubspot->contacts()->getByEmail("[email protected]");
returns an error
PHP Fatal error: Uncaught GuzzleHttp\Exception\ClientException: Client error: GET https://api.hubapi.com/contacts/v1/contact/email/[email protected]/profile?hapikey=APIKEYNOTSHOWNHERE resulted in a 404 Not Found response:

Digging a bit in the source of my trouble and I think that having the ability to turn off 'http_errors' on $hubspot->contacts()->getByEmail would solve my problem but I don;t know if it is doable or an option

Iterate over results

I am now upgrading from version v0.9.7 and I think something has broken on the lib regarding iterating over the results.

Currently, if I run code like this it would give me 0 results.

        $count = 0;
        $resp = $hubSpotService->contacts()->all();
        foreach ($resp as $row) {
            ++$count;
        }

        echo $count; //outputs `0`

The only workaround for this I see is following (which looks ugly).

        $count = 0;
        $resp = $hubSpotService->contacts()->all()->toArray();
        foreach ($resp as $row) {
            ++$count;
        }

        echo $count; //outputs `3`

Is this an "official" way to iterate over results now? Previously (on v.0.9.7) both approaches would give me the same output.

RequestException causes catchable fatal error

RequestExceptions that are thrown by Guzzle are catched in Client.php on line 38. A response should be returned, however the given parameter to the Response constructor is a string instead of a ResponseInterface. This causes the following error:

Catchable fatal error: Argument 1 passed to Fungku\HubSpot\Http\Response::__construct() must implement interface Psr\Http\Message\ResponseInterface, null given, called in /.../vendor/fungku/hubspot-php/src/Http/Client.php on line 39 and defined in /.../vendor/fungku/hubspot-php/src/Http/Response.php on line 24

Timeline API

Any plans to implement the Timeline API in the near future?

Add example file

Would it be possible to add a working example file. I am kind of new to PHP name spaces, and not quite sure how to start this off. It seems like if I try including the HubSpotService file then it isn't auto-including any other referenced files (e.g. BlogPosts). I am sure I'm just making a namespace noob mistake.

Get blogpost by pURL in addition to ID

Currently using this lib to interface with our HubSpot account and I'm building the blog integration. With the blogPost resource you can only pull a single post by ID. I'd like to create a method to pull by pURL for friendly URLs on my end, and also when returning a post or multiple posts add a pURL field which is just absolute_url with the domain/dir stripped off.

If this is a one off and should be written on my end I'll pass but if you think it'd be a good addition I'll write it and submit a PR.

Triggered events include API Key

When an event is triggered, the API Key is added to the event ID in HubSpot

$hubspotFactory = new Factory(['key' => '1234567890']);
$hubspotFactory->events()->trigger('1234', 'test event', '[email protected]');

When the contact record for [email protected] is viewed in HubSpot, the triggered event appears as:

Contact triggered event test event?hapikey=1234567890

I believe this is perhaps because, according to the docs, the API key does not need to be a part of the request.

Thanks for any help!

Problem uploading file - request option issues?

Hello!

Sorry if this is obvious. I'm somewhat new to this. My call to upload a file...

$files->upload('/var/www/html/signed_documents/documents.zip');

Is resulting the following error:

PHP Fatal error: Uncaught exception 'InvalidArgumentException' with message 'Passing in the "body" request option as an array to send a POST request has been deprecated. Please use the "form_params" request option to send a application/x-www-form-urlencoded request, or a the "multipart" request option to send a multipart/form-data request.' in /var/www/html/public/myproject/vendor/guzzlehttp/guzzle/src/Client.php:402

Any suggestions?

Ability to pass your own client instance to the service

I would like the ability to add my own instance of Client to the service which get's passed to all created API classes.

I would like to set up a events on the client to handle refreshing the OAuth token without having to handle each response separately.

Ideally I would like to be able to do the folloing:

    /**
     * @param string|null $apiKey
     * @param bool $oauth
     * @param HttpClient $client
     * @throws HubSpotException
     */
    protected function __construct($apiKey = null, $oauth = false, HttpClient $client = null)
    {
        $this->oauth = $oauth;
        $this->apiKey = $apiKey ?: getenv('HUBSPOT_API_KEY');
        if (empty($this->apiKey)) {
            throw new HubSpotException("You must provide a HubSpot api key.");
        }
        $this->client = $client;
    }

    /**
     * @param string $access_token HubSpot oauth access token
     * @param HttpClient $client An Http Client
     * @return static
     */
    public static function makeWithToken($access_token, HttpClient $client = null)
    {
        return new static($access_token, true, $client);
    }

    /**
     * @param string $name
     * @param null $arguments
     * @return mixed
     * @throws HubSpotException
     */
    public function __call($name, $arguments = null)
    {
        $apiClass = $this->getApiClassName($name);
        if (! (new \ReflectionClass($apiClass))->isInstantiable()) {
            throw new HubSpotException("Target [$apiClass] is not instantiable.");
        }
        $client = ($this->client) ?: new Client;
        return new $apiClass($this->apiKey, $client, $this->oauth);
    }

What are your thoughts? I'll happily create a pull request if you think this would be useful

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.