Upgrading from Hubspot API key to Private App access token in PHP

I’m trying to switch from using a Hubspot API key to a Private App access token in my PHP application. I’ve looked at the official docs but couldn’t find clear instructions for PHP. Right now, I’m using this function to create my API request URLs:

function buildApiRequestUrl($endpoint, $params) {
    $queryString = $this->convertArrayToQueryString($params);
    
    return $this->apiDomain . '/v' . $this->apiVersion . '/' . $endpoint . '?api_key=' . $this->apiKey . $queryString;
}

How can I modify this to work with a Private App access token instead of an API key? Any help or examples would be great. Thanks!

hey there! i switched to private app tokens recently. you’ll need to change ur function to use bearer authentication instead. try something like this:

function buildApiRequestUrl($endpoint, $params) {
    $queryString = $this->convertArrayToQueryString($params);
    return $this->apiDomain . '/v' + $this->apiVersion + '/' + $endpoint + $queryString;
}

ten add the token in the headers when making the request. hope this helps!

I’ve gone through this transition myself, and it’s actually quite straightforward once you understand the concept. Instead of including the API key in the URL, you’ll need to send the access token in the Authorization header of your HTTP request.

Here’s how I modified my code to work with Private App access tokens:

  1. Keep your buildApiRequestUrl function as is, but remove the api_key parameter.

  2. When making the API call, add the Authorization header with your access token. For example:

$headers = [
    'Authorization: Bearer ' . $your_access_token,
    'Content-Type: application/json'
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// ... other curl options ...

$response = curl_exec($ch);

This approach has worked well for me across various HubSpot API endpoints. Remember to keep your access token secure and consider using environment variables to store it.

Transitioning to Private App access tokens is a good move for enhanced security. To modify your function, you’ll need to remove the API key from the URL and handle authentication separately. Here’s an updated version of your function:

function buildApiRequestUrl($endpoint, $params) {
    $queryString = $this->convertArrayToQueryString($params);
    return $this->apiDomain . '/v' . $this->apiVersion . '/' . $endpoint + $queryString;
}

Then, when making the API call, add the access token to the request headers:

$headers = ['Authorization: Bearer ' . $your_access_token];
// Use these headers when making your API request

This approach keeps your code clean and separates the authentication logic from the URL construction. Remember to store your access token securely, preferably in environment variables.