How to get started with Trustpilot's Private API Authentication
Photo by Mohammad Rahmani on Unsplash
If you’re looking to trigger service or product review invitations via API, pull invitation data, add tags to reviews or create custom widgets, this technical blog explores the authentication process for using Trustpilot's private APIs. Learn how to obtain and refresh access tokens, as well as best practices for securing your API integrations. Whether you're a seasoned developer or just starting out, this guide provides a comprehensive overview of Trustpilot's authentication process. Read our authentication documentation here.
Prerequisites
To obtain an access token, you'll need the following:
- Trustpilot business account - create one here
- Trustpilot username and password (if using grant type password)
- Trustpilot Connect add-on Module/ Enterprise plan - get the module here or reach out to your Customer Success Manager to upgrade your plan
- Trustpilot API key and secret - support guide to creating one here
- API client - optional (we would recommend Postman)
What’s the difference between Public and Private API?
The Public API allows users to retrieve any information that is publicly available on Trustpilot.com, including review content and company profile information. On the other hand, our Private API is designed specifically for businesses to perform actions that are typically carried out within a B2B context, such as sending invitations, retrieving invitation data, replying to reviews, and filtering reviews by tags - features that are not accessible to the general public.
Accessing Private API
In order to access the Trustpilot API you will need to have the Trustpilot Connect Add-on module or an Enterprise plan that has this included. The module offers businesses a range of benefits, including using the API to customize how you collect and display Trustpilot reviews, embedded review forms to collect reviews directly from your webpage and build custom TrustBoxes. It's a valuable tool for building an online reputation and increasing customer engagement. Read more about our APIs in this introductory guide.
Generating an Access token and Refresh token using the API
Once you have access to the Trustpilot APIs, to use any private API endpoint, you need to authenticate using an access token. Trustpilot's access token obtained via OAuth2 Authentication is valid for 359999 seconds (around 4 days), while the refresh token, which is also returned in the response, is valid for around 90 days. You can find more information on authentication and the required steps in our API documentation.
We suggest you use an auth client to execute the OAuth2 authentication flow. You'll find auth clients in several languages here: oauth.net/2/#client-libraries
We support the following Grant Types in OAuth2 flow:
- Grant Type: Password
- Grant Type: Authorization Code
- Grant Type: Implicit
- Grant Type: Client Credentials
We recommend that you first request an access token using the grant_type client_credentials. This is because the client_credentials grant type allows a client application to obtain an access token directly from the authorization server, without any user involvement. Because your application's own credentials are being used, these credentials must be kept safe. Using the grant types password and auth code will allow you to obtain both an access token and refresh token whereas client credentials and implicit will not. For a video demo on how to do this with password, authorization code or implicit you can find it here oAuth2.0 Protocols by Jeremy Robinson.
Grant Type: Client Credentials
Note that when using this grant type the access token is not scoped to a user, therefore some endpoints will require the user's id to be provided in the form of a header (usually x-business-user-id) or in the request body. User's id can be obtained in the user's profile page.
Here are the steps you need to follow, I have also included Postman screenshots as we would advise testing the endpoints before testing it in your code:
1. Make a POST call to:
https://api.trustpilot.com/v1/oauth/oauth-business-users-for-applications/accesstoken
1a. With the following headers:
NOTE: The KEY AND SECRET need to be concatenated as follows KEY:SECRET and then base64 encoded.
Example of Postman Authorization:
1b. Include the following payload in the request body
Example of Postman Body:
2. Retrieve Access Token from the response
Example of Postman Response:
The response will contain the access token and the expiration time. You should use the "access_token" value, which is valid for 100 hours. When the access token expires, a HTTP error code 401 will be returned. We recommend setting up a loop to generate a new access token.
Grant Type: Password
This grant type is suitable for trusted applications that are owned and managed by the resource owner. It enables applications to directly access the user's credentials, which can be useful in certain scenarios but can also increase the risk of security breaches.The grant_type password can only be used from server-side to avoid exposing your API secret and credentials. Using this grant type allows you to obtain both an access token and refresh token. It involves the following steps:
1. Make a POST call to:
https://api.trustpilot.com/v1/oauth/oauth-business-users-for-applications/accesstoken
1a. With the following headers:
NOTE: The KEY AND SECRET need to be concatenated as follows KEY:SECRET and then base64 encoded.
Example of Postman Authorization:
1b. Include the following payload in the request body
2. Retrieve Access Tokens from the response
Example of Postman Response:
The response will contain the access token, refresh token, and the expiration time. You should use the "access_token" value, which is valid for 100 hours. When the access token expires, a HTTP error code 401 will be returned. You can use the refresh token or issue the same request to obtain a new access token and refresh token. See Refresh Token guide below.
Grant Type: Authorization Code
This grant type is suitable for server-side web applications that require long-lived access tokens. It is the most secure grant type because it requires a client secret and an authorization code to obtain an access token, which reduces the risk of token interception. The authorization code is a temporary code that the client will exchange for an access token and a refresh token. The code itself is obtained from the authorization server where the user gets a chance to see what information the client is requesting, and approve or deny the request. It involves the following steps:
1. Make a GET call to:
https://authenticate.trustpilot.com
1a. With the following parameters:
Example:
https://authenticate.trustpilot.com?client_id=APIKey&redirect_uri=https://www.clientsSite.com&response_type=code
Example of Postman Params:
2. Register your Redirect URI that corresponds with the API key and secret in your Trustpilot Business portal application
3. Visit your Trustpilot authorization page
4. Login to your Trustpilot Business account and retrieve your code.
5. Make a POST call to:
https://api.trustpilot.com/v1/oauth/oauth-business-users-for-applications/accesstoken
5a. With the following headers:
NOTE: The KEY AND SECRET need to be concatenated as follows KEY:SECRET and then base64 encoded.
Example of Postman Authorization:
5b. Include the following payload in the request body
Example of Postman Params:
6. Retrieve Access Tokens from the response
Example of Postman Authorization:
Unlike grant type client credentials, the response will contain the access token, refresh token, and the expiration time. You should use the "access_token" value, which is valid for 100 hours. When the access token expires, a HTTP error code 401 will be returned. See Refresh Token guide below.
Grant Type: Implicit
This grant type is suitable for client-side web applications that require short-lived access tokens. It is simpler than the authorization code grant because it does not require a client secret or an authorization code, but it is less secure because access tokens are returned directly to the client.
1. Make a GET call to:
https://authenticate.trustpilot.com
1a. With the following parameters:
Example:
https://authenticate.trustpilot.com?client_id=APIKey&redirect_uri=https://www.clientsSite.com&response_type=token
2. Navigate to your Trustpilot authorization page
3. Login to your Trustpilot Business account and retrieve your access token.
Refresh Token
All grant types will include an access token and expiration time in the response, only grant types password and authorization code will contain both the access token, refresh token. You should use the "access_token" value, which is valid for 100 hours. When the access token expires, a HTTP error code 401 will be returned. You can use the refresh token or issue the same request to obtain a new access token or new access and refresh token.
We recommend setting up a loop using the refresh token to generate a new access token. You can use the grant_type refresh_token and your refresh token as the value for the key "refresh_token" as a query parameter within the following step.
1. Make a POST call to:
https://api.trustpilot.com/v1/oauth/oauth-business-users-for-applications/refresh
1a. With the following params:
Example of Postman params:
1b. Include the following headers in the request:
NOTE: The KEY AND SECRET need to be concatenated as follows KEY:SECRET and then base64 encoded.
Example of Postman authorization:
1c. Include the following payload in the request body
Example of Postman body:
Depending on your internal security, you should set up this loop every 48-72 hours to ensure that you always create a new access token using the refresh token before the previous one expires.
You should always use the most up-to-date access token to populate the Bearer Token when using the private API endpoints to ensure that it's valid. Note that the old token will no longer be active once a new one is generated.
Finally, we recommend that you only authenticate when needed and reuse the valid access token when requesting private Trustpilot APIs. Too frequent authentication requests will be rejected with HTTP error code 429.
Generating an Access token and Refresh token with Node.js:
Here is an example of how you could retrieve your access token with Node.js:
var API_KEY = 'your_api_key'
var API_SECRET = 'your_api_secret'
var myHeaders = new Headers();
myHeaders.append("Authorization", "Basic [BASE64_ENCODED(API_KEY:API_SECRET)]");
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
var urlencoded = new URLSearchParams();
urlencoded.append("grant_type", "client_credentials");
urlencoded.append("client_id", {API_KEY});
urlencoded.append("client_secret", {API_SECRET});
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: urlencoded,
redirect: 'follow'
};
fetch("https://api.trustpilot.com/v1/oauth/oauth-business-users-for-applications/accesstoken", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
Here is an example of how you would retrieve a refresh token every 72 hours with your API credentials and access token using Node.js:
// Define the Trustpilot API credentials
let refreshToken = 'your_refresh_token';
const clientId = 'your_api_key';
const clientSecret = 'your_api_secret';
// Function to refresh the access token
async function refreshAccessToken() {
try {
const response = await fetch(
'https://api.trustpilot.com/v1/oauth/oauth-business-users-for-applications/refresh',
{
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: `grant_type=refresh_token&refresh_token=${refreshToken}&client_id=${clientId}&client_secret=${clientSecret}`
}
);
const json = await response.json();
if (response.ok) {
const accessToken = json.access_token;
refreshToken = json.refresh_token;
console.log('Access token refreshed:', accessToken);
return accessToken;
} else {
console.error('Failed to refresh access token:', json);
throw new Error('Failed to refresh access token');
}
} catch (error) {
console.error('Error refreshing access token:', error);
throw error;
}
}
// Function to refresh the access token every X seconds
async function loopRefreshAccessToken(intervalInSeconds) {
while (true) {
try {
const accessToken = await refreshAccessToken();
// Wait for the interval before refreshing again
await new Promise(resolve => setTimeout(resolve, intervalInSeconds * 1000));
} catch (error) {
console.error('Error refreshing access token:', error);
break;
}
}
}
// Start the loop with an interval of 1 hour (3600 seconds)
loopRefreshAccessToken(3600);
Conclusion:
In conclusion, Trustpilot's private APIs provide a wealth of opportunities for developers to integrate their data and resources into custom applications. However, as with any API integration, proper authentication protocols are crucial to ensure the security and reliability of your system. By following the steps outlined in this technical blog, you can obtain and refresh access tokens, as well as implement best practices to ensure that your API integrations are secure and performant. Whether you are looking to trigger review invitations or expanding the capabilities of your application, understanding Trustpilot's authentication process is essential for success. So, dive in and start building powerful, secure integrations with Trustpilot's private APIs today! For more detailed information, please refer to our documentation.
1 comentario
Sort by Fecha Votosmi heng
Hi, Linda L. Nice to meet you!
I'm having some problems with the authorization code mode, so I can help to check the problem
I'm using the authorization code mode for authorization, and on the Trustpilot login page, when I use my google account to login for authorization, its callback address will lose the `state` parameter
Looking forward to your reply!