Code Examples
Ready-to-use code for integrating with the Loyalteez API.
Node.js / JavaScript
Complete Integration Module
// loyalteez.js
const crypto = require('crypto');
const fetch = require('node-fetch');
class Loyalteez {
constructor(brandId, securityKey) {
this.brandId = brandId;
this.securityKey = securityKey;
this.baseUrl = 'https://api.loyalteez.app';
}
sign(timestamp, body) {
const signingString = `${timestamp}:${this.brandId}:${body}`;
return crypto
.createHmac('sha256', this.securityKey)
.update(signingString)
.digest('hex');
}
async trackEvent(eventType, userEmail, metadata = {}) {
const timestamp = Date.now();
const body = JSON.stringify({
brandId: this.brandId,
eventType,
userEmail,
metadata
});
const signature = this.sign(timestamp, body);
const response = await fetch(`${this.baseUrl}/loyalteez-api/manual-event`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Loyalteez-Brand-Id': this.brandId,
'X-Loyalteez-Signature': signature,
'X-Loyalteez-Timestamp': timestamp.toString()
},
body
});
const result = await response.json();
if (!response.ok) {
throw new Error(result.error || 'Request failed');
}
return result;
}
getUserEmail(platform, userId) {
return `${platform}_${String(userId).toLowerCase()}@loyalteez.app`;
}
}
module.exports = Loyalteez;
Usage
const Loyalteez = require('./loyalteez');
const ltz = new Loyalteez(
process.env.LOYALTEEZ_BRAND_ID,
process.env.LOYALTEEZ_SECURITY_KEY
);
// Track a game event
async function onQuestComplete(playerId, questName) {
const userEmail = ltz.getUserEmail('mygame', playerId);
const result = await ltz.trackEvent('quest_completed', userEmail, {
quest_name: questName,
completed_at: new Date().toISOString()
});
console.log(`Rewarded ${result.rewardAmount} LTZ to player ${playerId}`);
}
// Track a purchase
async function onPurchase(userId, orderId, amount) {
const userEmail = ltz.getUserEmail('myapp', userId);
const result = await ltz.trackEvent('purchase', userEmail, {
order_id: orderId,
amount: amount
});
return result;
}
Python
Complete Integration Module
# loyalteez.py
import hmac
import hashlib
import time
import json
import requests
from typing import Optional, Dict, Any
class Loyalteez:
def __init__(self, brand_id: str, security_key: str):
self.brand_id = brand_id
self.security_key = security_key
self.base_url = 'https://api.loyalteez.app'
def _sign(self, timestamp: str, body: str) -> str:
signing_string = f"{timestamp}:{self.brand_id}:{body}"
return hmac.new(
self.security_key.encode(),
signing_string.encode(),
hashlib.sha256
).hexdigest()
def track_event(
self,
event_type: str,
user_email: str,
metadata: Optional[Dict[str, Any]] = None
) -> Dict[str, Any]:
timestamp = str(int(time.time() * 1000))
body = json.dumps({
'brandId': self.brand_id,
'eventType': event_type,
'userEmail': user_email,
'metadata': metadata or {}
}, separators=(',', ':'))
signature = self._sign(timestamp, body)
response = requests.post(
f'{self.base_url}/loyalteez-api/manual-event',
headers={
'Content-Type': 'application/json',
'X-Loyalteez-Brand-Id': self.brand_id,
'X-Loyalteez-Signature': signature,
'X-Loyalteez-Timestamp': timestamp
},
data=body
)
result = response.json()
if not response.ok:
raise Exception(result.get('error', 'Request failed'))
return result
def get_user_email(self, platform: str, user_id: str) -> str:
return f"{platform}_{str(user_id).lower()}@loyalteez.app"
Usage
import os
from loyalteez import Loyalteez
ltz = Loyalteez(
os.environ['LOYALTEEZ_BRAND_ID'],
os.environ['LOYALTEEZ_SECURITY_KEY']
)
# Track a game event
def on_quest_complete(player_id: str, quest_name: str):
user_email = ltz.get_user_email('mygame', player_id)
result = ltz.track_event('quest_completed', user_email, {
'quest_name': quest_name
})
print(f"Rewarded {result['rewardAmount']} LTZ to player {player_id}")
# Track a signup
def on_signup(user_id: str, referrer_id: str = None):
user_email = ltz.get_user_email('myapp', user_id)
metadata = {'signup_source': 'web'}
if referrer_id:
metadata['referrer_id'] = referrer_id
return ltz.track_event('account_creation', user_email, metadata)
Go
Complete Integration Module
// loyalteez.go
package loyalteez
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
)
type Client struct {
BrandID string
SecurityKey string
BaseURL string
}
type EventRequest struct {
BrandID string `json:"brandId"`
EventType string `json:"eventType"`
UserEmail string `json:"userEmail"`
Metadata map[string]interface{} `json:"metadata"`
}
type EventResponse struct {
Success bool `json:"success"`
RewardAmount float64 `json:"rewardAmount"`
TxHash string `json:"txHash"`
Error string `json:"error,omitempty"`
}
func NewClient(brandID, securityKey string) *Client {
return &Client{
BrandID: brandID,
SecurityKey: securityKey,
BaseURL: "https://api.loyalteez.app",
}
}
func (c *Client) sign(timestamp, body string) string {
signingString := fmt.Sprintf("%s:%s:%s", timestamp, c.BrandID, body)
h := hmac.New(sha256.New, []byte(c.SecurityKey))
h.Write([]byte(signingString))
return hex.EncodeToString(h.Sum(nil))
}
func (c *Client) TrackEvent(eventType, userEmail string, metadata map[string]interface{}) (*EventResponse, error) {
timestamp := strconv.FormatInt(time.Now().UnixMilli(), 10)
reqBody := EventRequest{
BrandID: c.BrandID,
EventType: eventType,
UserEmail: userEmail,
Metadata: metadata,
}
bodyJSON, _ := json.Marshal(reqBody)
signature := c.sign(timestamp, string(bodyJSON))
req, _ := http.NewRequest("POST",
c.BaseURL+"/loyalteez-api/manual-event",
strings.NewReader(string(bodyJSON)))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Loyalteez-Brand-Id", c.BrandID)
req.Header.Set("X-Loyalteez-Signature", signature)
req.Header.Set("X-Loyalteez-Timestamp", timestamp)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var result EventResponse
json.Unmarshal(body, &result)
if !result.Success && result.Error != "" {
return nil, fmt.Errorf(result.Error)
}
return &result, nil
}
func (c *Client) GetUserEmail(platform, userID string) string {
return fmt.Sprintf("%s_%[email protected]", platform, strings.ToLower(userID))
}
Usage
package main
import (
"fmt"
"os"
"your-project/loyalteez"
)
func main() {
client := loyalteez.NewClient(
os.Getenv("LOYALTEEZ_BRAND_ID"),
os.Getenv("LOYALTEEZ_SECURITY_KEY"),
)
// Track event
userEmail := client.GetUserEmail("mygame", "player_123")
result, err := client.TrackEvent("quest_completed", userEmail, map[string]interface{}{
"quest_name": "First Blood",
})
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("Rewarded %.2f LTZ\n", result.RewardAmount)
}
cURL Examples
Track Event
# Variables
BRAND_ID="0xYourBrandId"
SECURITY_KEY="your_security_key"
TIMESTAMP=$(date +%s000)
BODY='{"brandId":"'$BRAND_ID'","eventType":"quest_completed","userEmail":"[email protected]","metadata":{"quest":"First Blood"}}'
# Generate signature (requires openssl)
SIGNING_STRING="$TIMESTAMP:$BRAND_ID:$BODY"
SIGNATURE=$(echo -n "$SIGNING_STRING" | openssl dgst -sha256 -hmac "$SECURITY_KEY" | cut -d' ' -f2)
# Make request
curl -X POST https://api.loyalteez.app/loyalteez-api/manual-event \
-H "Content-Type: application/json" \
-H "X-Loyalteez-Brand-Id: $BRAND_ID" \
-H "X-Loyalteez-Signature: $SIGNATURE" \
-H "X-Loyalteez-Timestamp: $TIMESTAMP" \
-d "$BODY"
Error Handling
All examples should handle these common errors:
try {
const result = await ltz.trackEvent('quest_completed', userEmail, metadata);
} catch (error) {
if (error.message.includes('cooldown')) {
// User already claimed this event recently
console.log('User is on cooldown');
} else if (error.message.includes('signature')) {
// Authentication issue
console.error('Check security key');
} else if (error.message.includes('not found')) {
// Event type doesn't exist
console.error('Create event in Partner Portal first');
} else {
console.error('Unexpected error:', error);
}
}