Hey there, fellow developer! Ready to supercharge your app with some social proof? Let's dive into integrating the Trustpilot API using JavaScript. We'll be using the nifty trustpilot
package to make our lives easier. Buckle up, and let's get started!
Before we jump in, make sure you've got:
Alright, let's get our hands dirty:
mkdir trustpilot-integration cd trustpilot-integration npm init -y npm install trustpilot
Easy peasy, right? We're off to a great start!
Now, let's set up our Trustpilot client:
const Trustpilot = require('trustpilot'); const client = new Trustpilot({ apiKey: 'YOUR_API_KEY', secret: 'YOUR_SECRET', username: 'YOUR_USERNAME', password: 'YOUR_PASSWORD' });
Replace those placeholder values with your actual credentials, and you're good to go!
Time to grab some reviews:
async function getLatestReviews() { try { const reviews = await client.reviews.list({ businessUnitId: 'YOUR_BUSINESS_UNIT_ID', page: 1, perPage: 20 }); console.log(reviews); } catch (error) { console.error('Error fetching reviews:', error); } } getLatestReviews();
Pro tip: Implement pagination to fetch more reviews as needed!
Let's invite some customers to leave reviews:
async function sendInvitation(email) { try { const invitation = await client.invitations.create({ businessUnitId: 'YOUR_BUSINESS_UNIT_ID', recipientEmail: email, referenceId: 'ORDER_123', // Replace with your order ID templateId: 'YOUR_TEMPLATE_ID' }); console.log('Invitation sent:', invitation); } catch (error) { console.error('Error sending invitation:', error); } } sendInvitation('[email protected]');
Set up an endpoint to receive Trustpilot webhooks:
const express = require('express'); const app = express(); app.post('/trustpilot-webhook', express.json(), (req, res) => { const webhookData = req.body; // Process the webhook data console.log('Received webhook:', webhookData); res.sendStatus(200); }); app.listen(3000, () => console.log('Webhook server running on port 3000'));
Always wrap your API calls in try-catch blocks, and respect Trustpilot's rate limits. Your future self will thank you!
Don't forget to write tests! Here's a quick example using Jest:
const Trustpilot = require('trustpilot'); jest.mock('trustpilot'); test('fetches reviews successfully', async () => { const mockReviews = [{ id: '1', content: 'Great service!' }]; Trustpilot.prototype.reviews.list.mockResolvedValue(mockReviews); const client = new Trustpilot({ /* mock credentials */ }); const reviews = await client.reviews.list({ /* params */ }); expect(reviews).toEqual(mockReviews); });
And there you have it! You've just built a solid Trustpilot API integration. Remember, this is just the beginning – there's so much more you can do with the Trustpilot API. Why not try fetching business info or responding to reviews next?
Now go forth and build something awesome! 🚀