trustlabs-sdk
Version:
Easy-to-use SDK for displaying trust verification badges on websites. Supports React, Vue, vanilla JS, and CDN usage.
402 lines (311 loc) • 11.1 kB
Markdown
# TrustLabs SDK - Server Setup Guide
This guide shows how to set up the server-side proxy for the TrustLabs SDK across different platforms.
## Why a Server Proxy?
The TrustLabs SDK requires a server proxy to keep your API key secure. Never expose your API key in client-side code.
## Next.js (App Router)
Create `app/api/trust-status/route.ts`:
```typescript
import { NextResponse } from 'next/server';
export async function POST(req: Request) {
try {
const { emails } = await req.json();
// Validate input
if (!Array.isArray(emails) || emails.length === 0) {
return NextResponse.json(
{ error: 'Invalid emails array' },
{ status: 400 }
);
}
if (emails.length > 100) {
return NextResponse.json(
{ error: 'Too many emails (max 100)' },
{ status: 400 }
);
}
const apiKey = process.env.TRUSTLABS_API_KEY;
if (!apiKey) {
console.error('TRUSTLABS_API_KEY environment variable not set');
return NextResponse.json(
{ error: 'Service configuration error' },
{ status: 500 }
);
}
// Call TrustLabs API
const params = emails.map(encodeURIComponent).join(',');
const url = `https://api.trustlabs.pro/api/public/trust-status?emails=${params}`;
const response = await fetch(url, {
headers: {
'X-API-Key': apiKey,
'Content-Type': 'application/json',
},
// Add timeout
signal: AbortSignal.timeout(10000)
});
if (!response.ok) {
console.error('TrustLabs API error:', {
status: response.status,
statusText: response.statusText,
url: url
});
return NextResponse.json(
{ error: 'Failed to fetch trust status' },
{ status: 502 }
);
}
const data = await response.json();
return NextResponse.json(data.results);
} catch (error) {
console.error('Trust status API error:', error);
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
);
}
}
```
Add to your `.env.local`:
```bash
TRUSTLABS_API_KEY=your_api_key_here
```
## Express.js
```javascript
const express = require('express');
const app = express();
app.use(express.json());
app.post('/api/trust-status', async (req, res) => {
try {
const { emails } = req.body;
// Validate input
if (!Array.isArray(emails) || emails.length === 0) {
return res.status(400).json({ error: 'Invalid emails array' });
}
if (emails.length > 100) {
return res.status(400).json({ error: 'Too many emails (max 100)' });
}
const apiKey = process.env.TRUSTLABS_API_KEY;
if (!apiKey) {
console.error('TRUSTLABS_API_KEY environment variable not set');
return res.status(500).json({ error: 'Service configuration error' });
}
// Call TrustLabs API
const params = emails.map(encodeURIComponent).join(',');
const url = `https://api.trustlabs.pro/api/public/trust-status?emails=${params}`;
const response = await fetch(url, {
headers: {
'X-API-Key': apiKey,
'Content-Type': 'application/json',
}
});
if (!response.ok) {
console.error('TrustLabs API error:', response.status, response.statusText);
return res.status(502).json({ error: 'Failed to fetch trust status' });
}
const data = await response.json();
res.json(data.results);
} catch (error) {
console.error('Trust status API error:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
```
## Laravel (PHP)
Create a controller:
```php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
class TrustStatusController extends Controller
{
public function getTrustStatus(Request $request)
{
// Validate input
$request->validate([
'emails' => 'required|array|min:1|max:100',
'emails.*' => 'email'
]);
$emails = $request->input('emails');
$apiKey = env('TRUSTLABS_API_KEY');
if (!$apiKey) {
Log::error('TRUSTLABS_API_KEY environment variable not set');
return response()->json(['error' => 'Service configuration error'], 500);
}
try {
$params = implode(',', array_map('urlencode', $emails));
$url = "https://api.trustlabs.pro/api/public/trust-status?emails={$params}";
$response = Http::withHeaders([
'X-API-Key' => $apiKey,
'Content-Type' => 'application/json',
])->timeout(10)->get($url);
if (!$response->successful()) {
Log::error('TrustLabs API error', [
'status' => $response->status(),
'body' => $response->body()
]);
return response()->json(['error' => 'Failed to fetch trust status'], 502);
}
$data = $response->json();
return response()->json($data['results'] ?? []);
} catch (\Exception $e) {
Log::error('Trust status API error', ['error' => $e->getMessage()]);
return response()->json(['error' => 'Internal server error'], 500);
}
}
}
```
Add to your routes (`web.php` or `api.php`):
```php
Route::post('/api/trust-status', [TrustStatusController::class, 'getTrustStatus']);
```
Add to your `.env`:
```bash
TRUSTLABS_API_KEY=your_api_key_here
```
## Django (Python)
Create a view in `views.py`:
```python
import json
import os
import requests
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
import logging
logger = logging.getLogger(__name__)
@csrf_exempt
@require_http_methods(["POST"])
def trust_status(request):
try:
data = json.loads(request.body)
emails = data.get('emails', [])
# Validate input
if not isinstance(emails, list) or len(emails) == 0:
return JsonResponse({'error': 'Invalid emails array'}, status=400)
if len(emails) > 100:
return JsonResponse({'error': 'Too many emails (max 100)'}, status=400)
api_key = os.environ.get('TRUSTLABS_API_KEY')
if not api_key:
logger.error('TRUSTLABS_API_KEY environment variable not set')
return JsonResponse({'error': 'Service configuration error'}, status=500)
# Call TrustLabs API
params = ','.join([requests.utils.quote(email) for email in emails])
url = f'https://api.trustlabs.pro/api/public/trust-status?emails={params}'
response = requests.get(url, headers={
'X-API-Key': api_key,
'Content-Type': 'application/json',
}, timeout=10)
if not response.ok:
logger.error(f'TrustLabs API error: {response.status_code} {response.text}')
return JsonResponse({'error': 'Failed to fetch trust status'}, status=502)
data = response.json()
return JsonResponse(data.get('results', []), safe=False)
except json.JSONDecodeError:
return JsonResponse({'error': 'Invalid JSON'}, status=400)
except Exception as e:
logger.error(f'Trust status API error: {str(e)}')
return JsonResponse({'error': 'Internal server error'}, status=500)
```
Add to your `urls.py`:
```python
from django.urls import path
from . import views
urlpatterns = [
path('api/trust-status/', views.trust_status, name='trust_status'),
]
```
## Ruby on Rails
Create a controller:
```ruby
class Api::TrustStatusController < ApplicationController
before_action :validate_emails
def create
api_key = ENV['TRUSTLABS_API_KEY']
if api_key.blank?
Rails.logger.error 'TRUSTLABS_API_KEY environment variable not set'
return render json: { error: 'Service configuration error' }, status: 500
end
begin
params_string = emails.map { |email| CGI.escape(email) }.join(',')
url = "https://api.trustlabs.pro/api/public/trust-status?emails=#{params_string}"
response = HTTParty.get(url, {
headers: {
'X-API-Key' => api_key,
'Content-Type' => 'application/json'
},
timeout: 10
})
if response.success?
render json: response.parsed_response['results'] || []
else
Rails.logger.error "TrustLabs API error: #{response.code} #{response.message}"
render json: { error: 'Failed to fetch trust status' }, status: 502
end
rescue => e
Rails.logger.error "Trust status API error: #{e.message}"
render json: { error: 'Internal server error' }, status: 500
end
end
private
def emails
@emails ||= params[:emails] || []
end
def validate_emails
unless emails.is_a?(Array) && emails.any?
return render json: { error: 'Invalid emails array' }, status: 400
end
if emails.length > 100
return render json: { error: 'Too many emails (max 100)' }, status: 400
end
end
end
```
Add to your routes:
```ruby
Rails.application.routes.draw do
namespace :api do
post 'trust-status', to: 'trust_status#create'
end
end
```
## Environment Variables
All implementations require setting the `TRUSTLABS_API_KEY` environment variable:
### Development
Create a `.env` file (add to `.gitignore`):
```bash
TRUSTLABS_API_KEY=your_api_key_here
```
### Production
Set the environment variable in your hosting platform:
- **Vercel**: Dashboard → Settings → Environment Variables
- **Netlify**: Site settings → Environment variables
- **Heroku**: `heroku config:set TRUSTLABS_API_KEY=your_key`
- **AWS**: Lambda environment variables or Systems Manager
- **Docker**: `docker run -e TRUSTLABS_API_KEY=your_key`
## Error Handling Best Practices
1. **Always validate input** - Check email format and array limits
2. **Use timeouts** - Prevent hanging requests
3. **Log errors** - Help with debugging in production
4. **Return appropriate HTTP status codes**
5. **Don't expose sensitive information** in error messages
6. **Implement rate limiting** if needed
## Testing Your Setup
Use this test script to verify your server endpoint:
```bash
curl -X POST http://localhost:3000/api/trust-status \
-H "Content-Type: application/json" \
-d '{"emails":["test@example.com"]}'
```
Expected response:
```json
[
{
"email": "test@example.com",
"verified": false,
"completed_at": null
}
]
```