EnergyAPIClientconst crypto = require('crypto');
const axios = require('axios');
class EnergyAPIClient {
constructor(apiKey, apiSecret, baseUrl = 'https://api.rolthe.com/v1') {
this.apiKey = apiKey;
this.apiSecret = apiSecret;
this.baseUrl = baseUrl;
}
// Keys must be sorted before signing — the server sorts too, and a different order breaks the signature
sortObject(obj) {
return Object.keys(obj).sort().reduce((sorted, key) => {
sorted[key] = typeof obj[key] === 'object' && obj[key] !== null
? this.sortObject(obj[key])
: obj[key];
return sorted;
}, {});
}
sign(timestamp, body = null) {
let message = `${this.apiKey}${timestamp}`;
if (body) message += JSON.stringify(this.sortObject(body));
return crypto.createHmac('sha256', this.apiSecret).update(message).digest('hex');
}
async request(method, endpoint, data = null) {
const timestamp = Math.floor(Date.now() / 1000);
const headers = {
'X-API-Key': this.apiKey,
'X-Timestamp': timestamp.toString(),
'X-Signature': this.sign(timestamp, data),
'Content-Type': 'application/json'
};
const url = `${this.baseUrl}${endpoint}`;
const response = method === 'GET'
? await axios.get(url, { headers })
: await axios.post(url, data, { headers });
return response.data;
}
}
const client = new EnergyAPIClient('your_api_key', 'your_api_secret');
client.request('GET', '/energy/account').then(console.log);
cURL example#!/bin/bash
API_KEY="TY_xxxxxxxx"
API_SECRET="sk_xxxxxxxx"
TIMESTAMP=$(date +%s)
# Signing a GET request (no body)
MESSAGE="${API_KEY}${TIMESTAMP}"
SIGNATURE=$(echo -n "$MESSAGE" | openssl dgst -sha256 -hmac "$API_SECRET" | cut -d' ' -f2)
curl -X GET "https://api.rolthe.com/v1/energy/account" \
-H "X-API-Key: ${API_KEY}" \
-H "X-Timestamp: ${TIMESTAMP}" \
-H "X-Signature: ${SIGNATURE}"