Back

How to build a public Trustpilot integration: Building the Auth Flow

Aug 2, 20247 minute read

Hey there, fellow JavaScript enthusiast! Ready to dive into the world of Trustpilot integrations? Today, we're going to focus on the most crucial part of building a public Trustpilot integration: the authorization flow. Buckle up, because we're about to make your app Trustpilot-powered in no time!

Prerequisites

Before we jump in, make sure you've got:

  • A Trustpilot Business account (if you don't have one, go grab it!)
  • An application registered in Trustpilot's Developer Portal
  • A Node.js environment set up and ready to roll

Got all that? Great! Let's get started.

Understanding Trustpilot's OAuth 2.0 Flow

Trustpilot uses OAuth 2.0 for authorization, specifically the authorization code grant type. Don't worry, it's not as complicated as it sounds! You'll need three key things:

  1. Client ID
  2. Client Secret
  3. Redirect URI

These are like the keys to your Trustpilot kingdom, so keep them safe!

Setting Up the Server

First things first, let's set up a basic Express.js server. Fire up your terminal and run:

npm init -y npm install express axios dotenv

Now, create an index.js file and let's get coding:

require('dotenv').config(); const express = require('express'); const axios = require('axios'); const app = express(); const port = 3000; app.listen(port, () => console.log(`Server running on port ${port}`));

Implementing the Authorization Request

Time to create that authorization URL and send your users on a magical journey to Trustpilot's authorization page:

app.get('/auth', (req, res) => { const authUrl = `https://api.trustpilot.com/v1/oauth/authorize?client_id=${process.env.CLIENT_ID}&redirect_uri=${encodeURIComponent(process.env.REDIRECT_URI)}&response_type=code`; res.redirect(authUrl); });

Handling the Callback

When the user grants permission, Trustpilot will redirect them back to your app with an authorization code. Let's catch that:

app.get('/callback', async (req, res) => { const { code } = req.query; // We'll use this code in the next step res.send('Authorization successful! Check your console.'); });

Exchanging the Code for Access Token

Now for the fun part - let's trade that code for an access token:

async function getAccessToken(code) { try { const response = await axios.post('https://api.trustpilot.com/v1/oauth/oauth-business-users-for-applications/accesstoken', { grant_type: 'authorization_code', code, client_id: process.env.CLIENT_ID, client_secret: process.env.CLIENT_SECRET, redirect_uri: process.env.REDIRECT_URI }); return response.data; } catch (error) { console.error('Error getting access token:', error.response.data); } } app.get('/callback', async (req, res) => { const { code } = req.query; const tokenData = await getAccessToken(code); console.log('Access Token:', tokenData.access_token); res.send('Authorization successful! Check your console.'); });

Refreshing the Access Token

Tokens don't last forever, so let's add a refresh function:

async function refreshAccessToken(refreshToken) { try { const response = await axios.post('https://api.trustpilot.com/v1/oauth/oauth-business-users-for-applications/refresh', { grant_type: 'refresh_token', refresh_token: refreshToken, client_id: process.env.CLIENT_ID, client_secret: process.env.CLIENT_SECRET }); return response.data; } catch (error) { console.error('Error refreshing token:', error.response.data); } }

Making Authenticated Requests

Now that you've got your access token, you can start making authenticated requests to Trustpilot's API:

async function getBusinessUnits(accessToken) { try { const response = await axios.get('https://api.trustpilot.com/v1/business-units', { headers: { Authorization: `Bearer ${accessToken}` } }); return response.data; } catch (error) { if (error.response.status === 401) { // Time to refresh that token! const newTokenData = await refreshAccessToken(/* your refresh token */); // Retry the request with the new token } console.error('Error fetching business units:', error.response.data); } }

Security Considerations

Remember, with great power comes great responsibility:

  • Keep your client secret... well, secret! Use environment variables.
  • Always use HTTPS in production.
  • Consider implementing PKCE (Proof Key for Code Exchange) for added security.

Wrapping Up

And there you have it! You've just built the authorization flow for a Trustpilot integration. Pretty cool, right? From here, you can start building out the rest of your integration, fetching reviews, posting invitations, and more.

Additional Resources

Want to dive deeper? Check out these resources:

Now go forth and build amazing things with Trustpilot! Remember, the reviews are out there - you just need to integrate them. Happy coding!