hubspot-php icon indicating copy to clipboard operation
hubspot-php copied to clipboard

Example of how to use OAuth2

Open mikeamcbrien opened this issue 8 years ago • 25 comments

Can you provide example code on how to use the library to authorize an app and refresh tokens using Oauth2?

Thanks.

mikeamcbrien avatar May 10 '18 14:05 mikeamcbrien

$clientId = "YOUR_APP_CLIENT_ID";
$clientSecret = "YOUR_APP_CLIENT_SECRET";
$redirectURI = "https://www.yourHubSpotApp.com/check_code";
$scopesArray = array('content', 'social');

// Get the user to click the $authorizeLink in your app
$authorizeLink = $hubspot->getAuthUrl($clientId, $redirectURI, $scopesArray);

echo "<a href='$authorizeLink'>Click to Authorize</a><BR>";

// Get the tokens to access the user data by using the one time code returned
if(isset($_GET['code']))
{
	$tokenCode = $_GET['code'];
	$accessTokens = $hubspot->getTokensByCode($clientId, $clientSecret, $redirectURI, $tokenCode);
	echo "SUCCESS | <pre>",print_r($accessTokens),"</pre>";
}

More info here: https://developers.hubspot.com/docs/methods/oauth2/oauth2-overview https://developers.hubspot.com/docs/methods/oauth2/get-access-and-refresh-tokens

Cheers!

siremi avatar Jun 05 '18 16:06 siremi

@siremi - Can you give me a FULL example of this? I am running into the following error...

Fatal error: Uncaught Error: Class 'SevenShores\Hubspot\Resources\GetAuthUrl' not found in /Users/mike/www/sites/s2ksync/public/vendor/ryanwinchester/hubspot-php/src/Factory.php:92 Stack trace: #0 /Users/mike/www/sites/s2ksync/public/index.php(98): SevenShores\Hubspot\Factory->__call('getAuthUrl', Array) #1 /Users/mike/.composer/vendor/weprovide/valet-plus/server.php(117): require('/Users/mike/www...') #2 {main} thrown in /Users/mike/www/sites/s2ksync/public/vendor/ryanwinchester/hubspot-php/src/Factory.php on line 92

I'm not sure if there is typo or if I am doing something incorrectly. Thanks.

mikeamcbrien avatar Jun 07 '18 20:06 mikeamcbrien

Sorry, try loading these:

require_once "src/Http/Client.php";
require_once "src/Resources/OAuth2.php";

use SevenShores\Hubspot\Http\Client;
use SevenShores\Hubspot\Resources\OAuth2;

siremi avatar Jun 07 '18 20:06 siremi

Still, a no go... here is my "full" file...

require 'vendor/autoload.php';

use SevenShores\Hubspot\Http\Client;
use SevenShores\Hubspot\Resources\OAuth2;
use SevenShores\Hubspot\Resources\Contacts;

$hubspot = SevenShores\Hubspot\Factory::create('xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxx');

//Oauth2 Validation
$clientId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxx";
$clientSecret = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx";
$redirectURI = "https://s2ksync.dev/";
$scopesArray = array('contacts','content','timeline','forms','files','automation');

// Get the user to click the $authorizeLink in your app
$authorizeLink = $hubspot->getAuthUrl($clientId, $redirectURI, $scopesArray);

echo "<a href='$authorizeLink'>Click to Authorize</a><BR>";

// Get the tokens to access the user data by using the one time code returned
if(isset($_GET['code']))
{
    $tokenCode = $_GET['code'];
    $accessTokens = $hubspot->getTokensByCode($clientId, $clientSecret, $redirectURI, $tokenCode);
    echo "SUCCESS | <pre>",print_r($accessTokens),"</pre>";
}

and the error message still remains....

Fatal error: Uncaught Error: Class 'SevenShores\Hubspot\Resources\GetAuthUrl' not found in /Users/mike/www/sites/s2ksync/public/vendor/ryanwinchester/hubspot-php/src/Factory.php:92 Stack trace: #0 /Users/mike/www/sites/s2ksync/public/index.php(27): SevenShores\Hubspot\Factory->__call('getAuthUrl', Array) #1 /Users/mike/.composer/vendor/weprovide/valet-plus/server.php(117): require('/Users/mike/www...') #2 {main} thrown in /Users/mike/www/sites/s2ksync/public/vendor/ryanwinchester/hubspot-php/src/Factory.php on line 92

mikeamcbrien avatar Jun 08 '18 18:06 mikeamcbrien

Try to add this after the auto load:

require 'vendor/autoload.php';
require_once "src/Resources/OAuth2.php";

# If it works, you'll probably want to add Contacts too...

siremi avatar Jun 08 '18 18:06 siremi

I did try that as well to no avail. Same exact error.

mikeamcbrien avatar Jun 08 '18 18:06 mikeamcbrien

Oh, I think you found a bug... This method is not included in the Factory

/**
 * Class Factory
 *
 * @method \SevenShores\Hubspot\Resources\BlogAuthors blogAuthors()
 * @method \SevenShores\Hubspot\Resources\Blogs blogs()
 * @method \SevenShores\Hubspot\Resources\BlogPosts blogPosts()
 * @method \SevenShores\Hubspot\Resources\BlogTopics blogTopics()
 * @method \SevenShores\Hubspot\Resources\Companies companies()
 * @method \SevenShores\Hubspot\Resources\CompanyProperties companyProperties()
 * @method \SevenShores\Hubspot\Resources\ContactLists contactLists()
 * @method \SevenShores\Hubspot\Resources\ContactProperties contactProperties()
 * @method \SevenShores\Hubspot\Resources\Contacts contacts()
 * @method \SevenShores\Hubspot\Resources\Email email()
 * @method \SevenShores\Hubspot\Resources\EmailEvents emailEvents()
 * @method \SevenShores\Hubspot\Resources\Engagements engagements()
 * @method \SevenShores\Hubspot\Resources\Files files()
 * @method \SevenShores\Hubspot\Resources\Forms forms()
 * @method \SevenShores\Hubspot\Resources\Keywords keywords()
 * @method \SevenShores\Hubspot\Resources\Pages pages()
 * @method \SevenShores\Hubspot\Resources\SocialMedia socialMedia()
 * @method \SevenShores\Hubspot\Resources\Timeline timeline()
 * @method \SevenShores\Hubspot\Resources\Workflows workflows()
 * @method \SevenShores\Hubspot\Resources\Events events()
 * @method \SevenShores\Hubspot\Resources\DealPipelines dealPipelines()
 * @method \SevenShores\Hubspot\Resources\DealProperties dealProperties()
 * @method \SevenShores\Hubspot\Resources\Deals deals()
 * @method \SevenShores\Hubspot\Resources\Owners owners()
 * @method \SevenShores\Hubspot\Resources\SingleEmail singleEmail()
 */

Adding this line should work:

  • @method \SevenShores\Hubspot\Resources\OAuth2 oauth2()

Or, maybe use the Client instead...

siremi avatar Jun 08 '18 18:06 siremi

Adding that to the Factory.php did not resolve the issue. Thanks for looking into it so far.

mikeamcbrien avatar Jun 08 '18 18:06 mikeamcbrien

@ryanwinchester Can you give any insight on this? What am I doing wrong?

mikeamcbrien avatar Jun 29 '18 17:06 mikeamcbrien

Same problem here, does anyone have a clue on how to get this working? Thanks!

markhorsman avatar Jul 12 '18 15:07 markhorsman

@mikeamcbrien

I think you must call the resource first and call the method next. Like for another resources

$authorizeLink = $hubspot->oAuth2->getAuthUrl($clientId, $redirectURI, $scopesArray);

laupiFrpar avatar Aug 29 '18 16:08 laupiFrpar

to create $hubspot, need HAPIKey?

I see this: $hubspot = SevenShores\Hubspot\Factory::create('xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxx');

Why need HAPIKey to call OAuth2 functions?

itulga avatar Nov 09 '18 11:11 itulga

Thanks to @mikeamcbrien @siremi and @laupiFrpar

I got it to work with:

$authorizeLink = $hubspot->oauth2()->getAuthUrl($clientId, $redirectURI, $scopesArray);

(note the capitalisation of oauth2 and the parenthesis).

Hope this helps Mike

Webalite avatar Jan 09 '19 00:01 Webalite

Yes, of course. You would need to call the method exactly as named after adding it to the Factory:

@method \SevenShores\Hubspot\Resources\OAuth2 oauth2() Then it should be $hubspot->oauth2()

@method \SevenShores\Hubspot\Resources\OAuth2 OAuth2() Then it should be $hubspot->OAuth2()

@gtulga You don't need the HAPIKey if you have an access token. If you don't have it, then you can still use the API with the HAPIKey, but it will only work for YOUR account, that is you wouldn't be able to connect to customer / consumer account. However, HAPIKey is great if you want to do some API calls real quick / develop your app faster / skip OAuth2 connection step.

siremi avatar Jan 09 '19 01:01 siremi

Here's another example with the HTTP client:

$this->httpClient = new Client(
			array(
				'oauth2' => true, // true if you have an accessToken | false if you're using the HAPIKey
				'key' => $HAPIKeyOrAccessToken
			),
			null,
			array('verify' => false) // SSL verification
		);
		
$hubspot =  new OAuth2($this->httpClient);
		
$hubspot->getAuthUrl($this->appClientId, $redirectURI, $scopesArray);

siremi avatar Jan 09 '19 01:01 siremi

Here's a working example I made combining some of the given code examples in this thread and in the readme file. I added @method \SevenShores\Hubspot\Resources\OAuth2 oauth2() to Factory as mentioned above. What it lacks now is some logic to handle the fact that the token expires every 6th hour, and you thus need to get a new one using the refreshtoken (like the token it's in the $accesTokens->data object), and update the factory's client->key with the new token.

<?php
    require_once __DIR__.'/vendor/autoload.php';

    use SevenShores\Hubspot\Http\Client;
    use SevenShores\Hubspot\Resources\OAuth2;

    define("CALLBACK_URL", "https://yourappurl.com/somescript.php");
    define("CLIENT_ID", "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx");
    define("CLIENT_SECRET", "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx");

    // Scope. Use what you need here check:
    // https://developers.hubspot.com/docs/methods/oauth2/initiate-oauth-integration#scopes
    $scope = ['contacts','actions','files'];

    $my_client = new Client(['key' => CLIENT_SECRET]);
    $my_oauth2 = new OAuth2($my_client);

    if (!isset($_GET['code'])) {
        // Get the user to click the $authorizeLink in your app
        $authorizeLink = $my_oauth2->getAuthUrl(CLIENT_ID, CALLBACK_URL, $scope);
        echo "<a href='$authorizeLink'>Click to Authorize</a><BR>";
        exit;
    }
    // Get the tokens to access the user data by using the one time code returned
    if(isset($_GET['code']))
    {
        // sanitize GET 
        $safeGet = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);
        $tokenCode = $safeGet['code'];

        // get access tokens
        $accessTokens = $my_oauth2->getTokensByCode(CLIENT_ID, CLIENT_SECRET, CALLBACK_URL, $tokenCode);
        echo "SUCCESS | <pre>",print_r($accessTokens),"</pre>";

        // Create a factory using Oauth2 with our aquired tokens and test if it works
        if(isset($accessTokens->data))
        {
            // update my_client to use oauth2
            $my_client->key = $accessTokens->data->access_token;
            $my_client->oauth2 = TRUE;

            // create Factory using createWithToken and my_client as client
            $hubspot = SevenShores\Hubspot\Factory::createWithToken($accessTokens->data->access_token, $my_client);

            // test Factory
            $response = $hubspot->contacts()->all([
                'count'     => 10,
                'property'  => ['firstname', 'lastname'],
            ]);
            foreach ($response->contacts as $contact) {
                echo sprintf(
                    "Contact name is %s %s." . PHP_EOL,
                    $contact->properties->firstname->value,
                    $contact->properties->lastname->value
                );
            }
        }
        else
        {
            echo "Oups!? Something went wrong...";
        }
    }

?>

andersiversen avatar Jan 24 '19 10:01 andersiversen

Here you go. This should automatically refresh any expired tokens or about to expire in 1 minute. You can increase the error margin, if you expect the API call to take longer.

You need to have some sort of storage like a DB to save your access / refresh tokens.

if(time()+60>=$accessTokenDataArray['expiresTime']) // 'expiresTime' => time()+$data['expires_in']
{
	// token has expired or is very close to expiry | try to refresh using the refresh token
	$refreshToken = $dataArray['refreshToken'];
	
	if(is_null($this->hubspot))
		$this->hubspot = new HubSpot_Client();
	
	$responseArray = json_decode($this->hubspot->getTokensByRefresh(
		$refreshToken
	), true);
	
	if($responseArray['status']!=Api_StatusCode::OK)
		$this->failResponse("Could not refresh access! Please re-connect."); // http_code => 400 means the user disconnected from HS platform | all refresh tokens will be revoked | You will still have access until the access token expires.
	
	$accessToken = $responseArray['data']['access_token'];
	
	$accessCodeId = $this->saveAccessTokens($accessToken, $responseArray['data']['expires_in'], $responseArray['data']['refresh_token']);
	
	if(!isset($accessCodeId) or !$accessCodeId)
		$this->failResponse("Warning! Could not save access tokens.");
	
} // end if need to refresh
else
	$accessToken = $accessTokenDataArray['accessToken'];

// All good | Call the API actions using the `$accessToken`

siremi avatar Jan 24 '19 22:01 siremi

Does anybody can tell me how to handle auth2 with Ajax, I want to get token after filling the form by ajax, but I'm not getting, how to handle with Auth2, previous it was working with API Key.

umeshnevase avatar Apr 16 '19 07:04 umeshnevase

I have tried to use the example without Factory but I have reached a paradox:

To be able to use OAuth 2, I need to generate an Auth URL so that I can authenticate the app on my Hubspot environment and get and Access Token in return.

To get the URL I need an OAuth2 object which extends Resource. Resource needs a Client Object. And the Client object needs either an API key (which I am not using) or... an Access Token?

So, in other words, to be able to generate an access token, I need an access token which is in itself impossible.

See #166

Pryrios avatar Jun 06 '19 07:06 Pryrios

The Auth URL is just a hard-coded value. This will redirect the customer to HubSpot so he can connect your App.

You should be able to initialize the Client with a null value or 'n/a' The access toke should be optional to use getAuthUrl()...

The Auth URL looks like this: https://app.hubspot.com/oauth/authorize?client_id={$clientId}&scope={$scopeString}&redirect_uri=".urlencode($redirectURI)

siremi avatar Jun 06 '19 16:06 siremi