Hubspot API Integration with Wordpress CMS(Resolving CORS issue effectively using various techniques)

sibu stephen
5 min readSep 29, 2023

--

“There is a saying if we need to do a thing right, do it right rather than having things to do in way which works now but breaks later :) “

Well as per saying, imagine if we are travelling in a forest and we come across a situation where we see there are 2different ways to reach your destination and we might think well if we go by either of them we will reach our destination easily, but what we not know is which way is effective for us and according to our situation, let’s say

First way A — Has more stones on the way which is not idle if we are having a car with less ground clearance while if we are walking the way to the destination or have a car with Good car clearance then way A is idle.

Second way B — Has water on it’s way then it’s not idle for someone having a car with less car clearance or more car clearance but someone with swimming experience can get through.

Like the above example if we try to relate it with our technology terms we do have idle ways but it depends on what technology stack or what requirement what you are serving.

Well after this physiological talk let’s deep dive into hanshaking Hubspot CMS with our Wordpress CMS. Though there is no module yet developed in order to sync any blog or content from our Hubspot CMS directly into our Wordpress CMS, but our Hubspot community has provided us with different ways which we can achieve using API.

  1. Node Js standalone server.
  2. Axios on client side.
  3. Creating a hubspot modules which acts as a server proxy.

Let’s talk in detail on each of them.

Node JS standalone Server.

This technique involves creating a new repo and initalising your Node Js Proxy server which would handle your API requests from the Hubspot API and in return it would fetch the data for you when you call the app. This approach is specially useful when you are not able to set up the headers despite of setting the attributes to true.

For detailed info into code do visit -

https://community.hubspot.com/t5/APIs-Integrations/How-can-I-set-up-a-proxy-API-to-get-around-the-CORS-error/m-p/281436

https://travishorn.com/creating-a-node-js-proxy-to-secure-your-third-party-api-key-e305f2c951da

Axios on client side.

This is the standard method recommended in the hubspot documentation where we need to call the Axios API and call it in your javascript file to fetch the data for you.

axios.get('https://api.hubapi.com/crm/v3/objects/contacts',
{
headers: {
'Authorization': `Bearer ${YOUR_TOKEN}`,
'Content-Type': 'application/json'
}
},
(err, data) => {
// Handle the API response
}
);

In the above code line we are fetching the date via request and providing proper token and parameters.

This would work for most of the applications unless you come across CORS issue which essentially means your aplication is not allowing to make request. Well this can be mitigated by adding

``Access-Control-Allow-Origin: *`` in yout HTML headers of config file but at times the application still doesn’t gives you enough permissions to make a API call.

Creating a hubspot modules which acts as a server proxy.

This is a technique which can be implemented across any PHP based CMS and applications where it requires you to create a module which would act as a proxy server who makes requests for you and then you can use it to fetch in your php code ot Javascript code to make it presentable for the users. Let’s make a quick module (In wordpress) and see how ti works.

At first you need to create a module let’s give it a name as `HubspotAPICall`

<?php
/*
Plugin Name: HubSpot API Call
Description: Plugin for Hubspot API call
*/

// Add a custom endpoint for the proxy
add_action('rest_api_init', 'hubspot_api_proxy_endpoint');

function hubspot_api_proxy_endpoint() {
register_rest_route('hubspot-api-proxy/v1', 'call', array(
'methods' => 'GET',
'callback' => 'hubspot_api_proxy_callback',
));
}

function hubspot_api_proxy_callback($request) {
// Get the URL to proxy (HubSpot CMS API URL)
$api_url = $request->get_param('url');

// Get any additional query parameters if needed
$query_params = $request->get_params();

// Make the proxy request to HubSpot CMS
$response = wp_safe_remote_get($api_url, array(
'timeout' => 30,
'httpversion' => '1.1',
'blocking' => true,
'redirection' => 5,
'headers' => array(
"Access-Control-Allow-Origin: *"
// Add any other required headers here
),
'body' => $query_params,
));

if (is_wp_error($response)) {
return new WP_Error('api_error', 'Error fetching data from HubSpot CMS', array('status' => 500));
}

// Return the HubSpot CMS API response
return json_decode(wp_remote_retrieve_body($response));
}

?>

So what the above functions are doing is setting up a safe proxy passage which uses function `wp_safe_remote_get` which takes in parameters of the url passed and makes the request.

<?php
// Define your HubSpot CMS API URL
$hubspot_api_url = 'https://api.hubapi.com/cms/v3/blogs/posts?sort=-created&limit=3&state=PUBLISHED';

// Define your Bearer Token
$bearer_token = 'YOUR_BEARER_TOKEN_HERE';

// Make the request to the custom WordPress REST API endpoint with the bearer token in the header
$response = wp_safe_remote_get(
rest_url('hubspot-api-proxy/v1/call?url=' . urlencode($hubspot_api_url)),
array(
'headers' => array(
'Authorization' => 'Bearer ' . $bearer_token
)
)
);

if (is_wp_error($response)) {
// Handle error
echo 'Error: ' . $response->get_error_message();
} else {
// Process the response data
$data = json_decode(wp_remote_retrieve_body($response));
// Handle the API response data
}
?>

In the above code you are using the function wp_safe_remote_get we are passing our hubspot API alosn with the bearer token, to effectively disply the json data in php alternatively you can use axios, fetch or ajax function in javascript to display the data.

Alternatively in php there is another way by using curl_setopt to make a curl requests something like the below code.

    <?php
// Function to make a request to the HubSpot API
function fetchData($apiEndpoint, $accessToken) {
$ch = curl_init($apiEndpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer ' . $accessToken
));

$response = curl_exec($ch);

if (curl_errno($ch)) {
return false; // Handle the error
}

curl_close($ch);

return $response; // Return the API response
}
// Define the API endpoint and access token
$api = 'https://api.hubapi.com/cms/v3/blogs/posts?state=PUBLISHED';
$Token = 'YOU_BEARER_TOKEN';
// Call the function from your file to fetch data
$hubSpotData = fetchHubSpotData($api, $Token);
// Convert the JSON response into a PHP object.
$hubSpotDataArray = json_decode($hubSpotData, true); // Set the second parameter to true for an associative array
?>
// To pass via javascript.
<script>
var hubSpotData = <?php echo json_encode($hubSpotData); ?>;
</script>

Well these techniques could effectively help you find out ways to tackle. the CORS issues in any php based CMS/Applications.

BONUS TIP

If you want to try out a API call on local without using any other method you can simply use — https://cors-anywhere.herokuapp.com/ whic would allow you to make aPI request from anywhere into any application but is only restricted to your local development environment this is helpful for a quick POC or any other local based approcah but not useful on any other environment.

Hope this blog helped you tackle the CORS issues and think of best approach for your application based on your application type :)

For more reference and other approaches apart from the mentioned above refer —

https://developers.hubspot.com/docs/api/private-apps#make-api-calls-with-your-app-s-access-token
https://legacydocs.hubspot.com/docs/methods/oauth2/initiate-oauth-integration
https://developers.hubspot.com/docs/cms/developer-reference/reverse-proxy-support

--

--

sibu stephen

Basically not viewed as a popular one, but I count myself as one for existence.