DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Contract-First Integration: Building Scalable Systems With Flyway, OpenAPI, and Kafka
  • The "Zombie API" Attack: Why Your Old Integrations Are Your Biggest Security Risk
  • 6 Integration Patterns That Look Good on Paper and What Happens When They Hit Production
  • The Future of AI Integration: Why Model Context Protocol Is the New API

Trending

  • Build Self-Managing Data Pipelines With an LLM Agent
  • Integrating AI-Driven Decision-Making in Agile Frameworks: A Deep Dive into Real-World Applications and Challenges
  • A Scalable Framework for Enterprise Salesforce Optimization: Turning Outcomes Into an Operating System
  • Architecting an Embedded Efficiency Layer: A Platform Deep Dive into Day-Two Operational Tuning
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. Hubspot API Integration With WordPress CMS

Hubspot API Integration With WordPress CMS

This article presents a discussion of various approaches that one can use to integrate Hubspot CMS using WordPress. Read more!

By 
Sibu Stephen user avatar
Sibu Stephen
·
Nov. 07, 23 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
2.5K Views

Join the DZone community and get the full member experience.

Join For Free

“There is a saying if we need to do a thing right, we need to do it right the first time, rather than doing things in a way that works now but breaks later :)."

Well, as per this saying, imagine if we are traveling in a forest and we come across a situation where we see there are two different 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: If it has water on its 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 you are serving.

Well, after this physiological talk, let’s deep dive into handshaking 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, our Hubspot community has provided us with different ways in which we can achieve this using API.

  1. Node Js standalone server.
  2. Axios on the client side.
  3. Creating a Hubspot module that acts as a server proxy.

Let’s talk in detail about each of them.

Node.js Standalone Server

This technique involves creating a new repo and initializing 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 especially useful when you are not able to set up the headers despite setting the attributes to true.

For detailed info into code, do visit:

Hubspot Community

Travis Horn

Axios on the 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.

JavaScript
 
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 data via request and providing the proper token and parameters.

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

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

Creating a Hubspot Module That Acts as a Server Proxy

This is a technique that can be implemented across any PHP-based CMS and applications where it requires you to create a module that would act as a proxy server that makes requests for you, and then you can use it to fetch in your PHP code or JavaScript code to make it presentable for the users. Let’s make a quick module (in WordPress) and see how it works.

First, you need to create a module. Let’s give it a name such as `HubspotAPICall`

PHP
 
<?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 the function `wp_safe_remote_get` which takes in the parameters of the URL passed and makes the request.

PHP
 
<?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 along with the bearer token to display the JSON data in PHP effectively; alternatively, you can use Axios, fetch, or Ajax functions in JavaScript to display the data.

Alternatively, in PHP, there is another way by using curl_setopt to make a curl request, something like the below code.

PHP
 
  <?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 ways to tackle the CORS issues in any PHP-based CMS/Applications.

Bonus Tip

Visit here if you want to try out an API call locally without using any other method, which would allow you to make API requests from anywhere into any application but is only restricted to your local development environment. This is helpful for a quick POC or any other locally-based approach but not useful in any other environment.

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

Further References

HubSpot Docs
LegacyDocs
Developer Reference

API Content management system WordPress Integration

Published at DZone with permission of Sibu Stephen. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Contract-First Integration: Building Scalable Systems With Flyway, OpenAPI, and Kafka
  • The "Zombie API" Attack: Why Your Old Integrations Are Your Biggest Security Risk
  • 6 Integration Patterns That Look Good on Paper and What Happens When They Hit Production
  • The Future of AI Integration: Why Model Context Protocol Is the New API

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook