aivawins
v1.0.1
Published
Official TypeScript/JavaScript SDK for AIVA Platform API - subscription analytics, RFM segmentation, and marketing automation
Maintainers
Readme
AIVA Platform API Client
Official TypeScript/JavaScript SDK for the AIVA Platform API.
Build subscription analytics, customer segmentation, and marketing automation into your applications with AIVA's powerful API.
Features
- ✅ Complete TypeScript support - Full type definitions with autocomplete
- ✅ 35+ API methods - All AIVA Merchant API endpoints covered
- ✅ RFM Segmentation - Champions, Loyal, At Risk, Churned customers
- ✅ Real-time Analytics - MRR, churn rate, revenue trends
- ✅ Prize Draws - Blockchain-verified random draws
- ✅ Marketing Automation - Campaigns, webhooks, and triggers
- ✅ Affiliate Tracking - Commission management and sales attribution
- ✅ Flexible Auth - API keys or customer tokens
- ✅ Error Handling - Graceful error responses with details
Installation
npm install aivawinsOr with yarn:
yarn add aivawinsOr with pnpm:
pnpm add aivawinsQuick Start
import { createAivaClient } from 'aivawins';
const client = createAivaClient({
baseUrl: 'https://api.aivawins.ai',
apiKey: process.env.AIVA_API_KEY!,
merchantId: 'merch_xyz123'
});
// Get your business metrics
const metrics = await client.getDashboardMetrics();
console.log(`MRR: $${metrics.data.mrr}`);
console.log(`Active Subscriptions: ${metrics.data.activeSubscriptions}`);
// Get Champion customers for VIP campaign
const champions = await client.getCustomers({ segment: 'Champion' });
console.log(`Champions: ${champions.data.customers.length}`);Authentication
API Key (Recommended for Merchants)
import { createAivaClient } from 'aivawins';
const client = createAivaClient({
baseUrl: 'https://api.aivawins.ai',
apiKey: 'your_api_key_here',
merchantId: 'merch_xyz123'
});Get your API key:
- Login to AIVA Dashboard
- Navigate to Settings → API Keys
- Click "Generate New API Key"
Customer Token (For Customer-Facing Apps)
const client = createAivaClient({
baseUrl: 'https://api.aivawins.ai',
customerToken: 'customer_token_from_auth'
});API Reference
Merchant
Get and update merchant settings.
// Get merchant info
const merchant = await client.getMerchant();
console.log(merchant.data.companyName);
// Update merchant settings
await client.updateMerchant('merch_xyz', {
companyName: 'New Company Name',
currency: 'USD'
});Customers
Manage and segment customers using RFM analysis.
// Get all customers (paginated)
const customers = await client.getCustomers({
page: 1,
pageSize: 20
});
// Get customers by RFM segment
const champions = await client.getCustomers({
segment: 'Champion'
});
const atRisk = await client.getCustomers({
segment: 'At Risk'
});
// Search customers
const results = await client.getCustomers({
search: '[email protected]'
});
// Get single customer
const customer = await client.getCustomer('cust_abc123');
console.log(`LTV: $${customer.data.lifetimeValue}`);
console.log(`Segment: ${customer.data.rfmSegment}`);RFM Segments:
Champion- Best customers (high R, F, M)Loyal- Regular purchasersPotential Loyalist- Recent customers with potentialNew Customers- First-time buyersAt Risk- Used to buy frequently, but haven't recentlyChurned- Haven't purchased in a long time
Subscriptions
Manage customer subscriptions.
// Get all subscriptions
const subs = await client.getSubscriptions({
page: 1,
pageSize: 50
});
// Get customer's subscriptions
const customerSubs = await client.getCustomerSubscriptions('cust_abc123');
// Get subscription details
const sub = await client.getSubscription('sub_xyz789');
// Pause subscription
await client.pauseSubscription('sub_xyz789');
// Resume subscription
await client.resumeSubscription('sub_xyz789');
// Cancel subscription
await client.cancelSubscription('sub_xyz789', {
reason: 'Customer requested cancellation'
});Orders
Retrieve order history and details.
// Get all orders
const orders = await client.getOrders({
page: 1,
pageSize: 100
});
// Get customer's orders
const customerOrders = await client.getCustomerOrders('cust_abc123');
// Get order details
const order = await client.getOrder('ord_456def');
console.log(`Total: $${order.data.totalAmount}`);
console.log(`Items: ${order.data.items.length}`);Analytics
Get business intelligence and revenue metrics.
// Dashboard metrics (MRR, churn, LTV)
const metrics = await client.getDashboardMetrics();
console.log(`MRR: $${metrics.data.mrr}`);
console.log(`Churn Rate: ${metrics.data.churnRate}%`);
console.log(`Avg LTV: $${metrics.data.averageLTV}`);
// MRR trend over time
const trend = await client.getMRRTrend({ months: 12 });
trend.data.forEach(month => {
console.log(`${month.month}: $${month.mrr}`);
});
// RFM distribution
const rfm = await client.getRFMDistribution();
console.log(`Champions: ${rfm.data.segments.Champion}`);
console.log(`At Risk: ${rfm.data.segments['At Risk']}`);
// Revenue analytics
const revenue = await client.getRevenueAnalytics({
startDate: '2025-01-01',
endDate: '2025-11-24'
});
console.log(`Total Revenue: $${revenue.data.totalRevenue}`);Prize Draws
Create and manage blockchain-verified prize draws.
// Get active prize draws
const active = await client.getActivePrizeDraws();
// Get all prize draws
const draws = await client.getPrizeDraws({
page: 1,
pageSize: 20
});
// Get prize draw details
const draw = await client.getPrizeDraw('draw_202511');
console.log(`Prize Pool: $${draw.data.prizePool}`);
console.log(`Total Entries: ${draw.data.totalEntries}`);
// Create new prize draw
const newDraw = await client.createPrizeDraw({
name: 'November Grand Prize',
prizePool: 5000,
drawDate: '2025-11-30T20:00:00Z',
description: 'Monthly grand prize draw for all subscribers'
});
// Execute prize draw (on draw date)
const result = await client.executePrizeDraw('draw_202511');
console.log(`Winner: ${result.data.winnerId}`);
console.log(`Blockchain TX: ${result.data.blockchainTxHash}`);
// Get customer's prize entries
const entries = await client.getCustomerPrizeEntries('cust_abc123');
console.log(`Total Entries: ${entries.data.totalEntries}`);Affiliates
Manage affiliate program and track commissions.
// Get all affiliates
const affiliates = await client.getAffiliates({
page: 1,
pageSize: 50
});
// Get affiliate details
const affiliate = await client.getAffiliate('aff_jkl012');
console.log(`Total Commissions: $${affiliate.data.totalCommissions}`);
// Get affiliate sales
const sales = await client.getAffiliateSales('aff_jkl012', {
startDate: '2025-11-01',
endDate: '2025-11-30'
});
console.log(`Sales this month: ${sales.data.length}`);
// Create new affiliate
const newAffiliate = await client.createAffiliate({
email: '[email protected]',
firstName: 'John',
lastName: 'Doe',
commissionRate: 0.20 // 20%
});Marketing
Create targeted campaigns based on RFM segments.
// Get all campaigns
const campaigns = await client.getCampaigns({
page: 1,
pageSize: 20
});
// Create email campaign
const campaign = await client.createCampaign({
name: 'Win-back At Risk Customers',
targetSegment: 'At Risk',
channel: 'email',
subject: 'We miss you! Here\'s 20% off',
message: 'We noticed you haven\'t ordered recently...',
scheduleAt: '2025-11-25T09:00:00Z'
});
// Get campaign stats
const stats = await client.getCampaignStats('camp_mno345');
console.log(`Sent: ${stats.data.sentCount}`);
console.log(`Open Rate: ${stats.data.openRate}%`);
console.log(`Click Rate: ${stats.data.clickRate}%`);Webhooks
Set up real-time notifications for events.
// Get all webhooks
const webhooks = await client.getWebhooks();
// Create webhook
const webhook = await client.createWebhook({
event: 'customer.segment_changed',
url: 'https://yourdomain.com/webhooks/aiva',
filters: {
segment: 'At Risk'
}
});
// Delete webhook
await client.deleteWebhook('hook_pqr678');Available Events:
customer.createdcustomer.updatedcustomer.segment_changedsubscription.createdsubscription.pausedsubscription.resumedsubscription.cancelledorder.createdprize_draw.winner_selectedaffiliate.sale_created
TypeScript Support
Full TypeScript definitions included:
import {
createAivaClient,
AivaApiClient,
ApiClientConfig,
Customer,
Subscription,
Order,
PrizeDraw,
Campaign,
Affiliate,
DashboardMetrics
} from 'aivawins';
const client: AivaApiClient = createAivaClient({
baseUrl: 'https://api.aivawins.ai',
apiKey: process.env.AIVA_API_KEY!,
merchantId: 'merch_xyz'
});
// Full autocomplete and type checking
const customer: Customer = (await client.getCustomer('cust_123')).data;Error Handling
All methods return an ApiResponse<T> with success flag:
const result = await client.getCustomer('cust_abc123');
if (result.success) {
console.log('Customer:', result.data);
} else {
console.error('Error:', result.error.message);
console.error('Code:', result.error.code);
}Common Error Codes:
INVALID_API_KEY- API key is missing or invalidUNAUTHORIZED- API key doesn't have permissionNOT_FOUND- Resource doesn't existRATE_LIMIT_EXCEEDED- Too many requestsVALIDATION_ERROR- Invalid request data
Try/Catch Pattern:
try {
const customer = await client.getCustomer('cust_abc123');
if (!customer.success) {
throw new Error(customer.error.message);
}
console.log(customer.data);
} catch (error) {
console.error('Failed to fetch customer:', error);
}Framework Examples
Next.js App Router
// app/api/customers/route.ts
import { createAivaClient } from 'aivawins';
import { NextResponse } from 'next/server';
const client = createAivaClient({
baseUrl: process.env.AIVA_API_URL!,
apiKey: process.env.AIVA_API_KEY!,
merchantId: process.env.AIVA_MERCHANT_ID!
});
export async function GET(request: Request) {
const { searchParams } = new URL(request.url);
const segment = searchParams.get('segment');
const result = await client.getCustomers({
segment: segment || undefined,
page: 1,
pageSize: 20
});
if (!result.success) {
return NextResponse.json(
{ error: result.error.message },
{ status: 400 }
);
}
return NextResponse.json(result.data);
}React Hook (Client-Side)
⚠️ SECURITY WARNING: Never use your API key in client-side code! Use a backend API route to proxy requests.
// hooks/useAivaMetrics.ts
import { useState, useEffect } from 'react';
export function useAivaMetrics() {
const [metrics, setMetrics] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
async function loadMetrics() {
// Call YOUR backend API, which then calls AIVA API
const response = await fetch('/api/aiva/metrics');
const data = await response.json();
setMetrics(data);
setLoading(false);
}
loadMetrics();
}, []);
return { metrics, loading };
}Backend API route (server-side only):
// app/api/aiva/metrics/route.ts
import { createAivaClient } from 'aivawins';
import { NextResponse } from 'next/server';
// ✅ SECURE: API key only exists on server, never sent to client
const client = createAivaClient({
baseUrl: process.env.AIVA_API_URL!, // No NEXT_PUBLIC_ prefix!
apiKey: process.env.AIVA_API_KEY!, // Never exposed to browser
merchantId: process.env.AIVA_MERCHANT_ID!
});
export async function GET() {
const result = await client.getDashboardMetrics();
if (!result.success) {
return NextResponse.json(
{ error: result.error.message },
{ status: 400 }
);
}
return NextResponse.json(result.data);
}Express.js
// server.js
const express = require('express');
const { createAivaClient } = require('aivawins');
const app = express();
const client = createAivaClient({
baseUrl: process.env.AIVA_API_URL,
apiKey: process.env.AIVA_API_KEY,
merchantId: process.env.AIVA_MERCHANT_ID
});
app.get('/api/champions', async (req, res) => {
const result = await client.getCustomers({ segment: 'Champion' });
if (!result.success) {
return res.status(400).json({ error: result.error.message });
}
res.json(result.data);
});
app.listen(3000);Environment Variables
Create a .env file:
AIVA_API_URL=https://api.aivawins.ai
AIVA_API_KEY=your_api_key_here
AIVA_MERCHANT_ID=merch_xyz123Then use in your code:
import { createAivaClient } from 'aivawins';
const client = createAivaClient({
baseUrl: process.env.AIVA_API_URL!,
apiKey: process.env.AIVA_API_KEY!,
merchantId: process.env.AIVA_MERCHANT_ID!
});Common Use Cases
1. Win-back Campaign for At-Risk Customers
// Get at-risk customers
const atRisk = await client.getCustomers({ segment: 'At Risk' });
// Create targeted campaign
const campaign = await client.createCampaign({
name: 'Win-back At Risk',
targetSegment: 'At Risk',
channel: 'email',
subject: 'We miss you! 20% off your next order',
message: 'You haven\'t ordered recently. Come back with 20% off!',
scheduleAt: '2025-11-25T09:00:00Z'
});
console.log(`Campaign created: ${campaign.data.campaignId}`);
console.log(`Targeting: ${atRisk.data.totalCount} at-risk customers`);2. VIP Treatment for Champions
// Get Champions
const champions = await client.getCustomers({ segment: 'Champion' });
// Set up webhook to notify when someone becomes a Champion
const webhook = await client.createWebhook({
event: 'customer.segment_changed',
url: 'https://yourdomain.com/webhooks/new-champion',
filters: { segment: 'Champion' }
});
// Send VIP rewards
for (const customer of champions.data.customers) {
console.log(`VIP Customer: ${customer.email}`);
console.log(`LTV: $${customer.lifetimeValue}`);
// Send to your CRM, email marketing, etc.
}3. Business Intelligence Dashboard
// Get comprehensive metrics
const metrics = await client.getDashboardMetrics();
const trend = await client.getMRRTrend({ months: 12 });
const rfm = await client.getRFMDistribution();
// Build dashboard data
const dashboard = {
mrr: metrics.data.mrr,
churnRate: metrics.data.churnRate,
activeSubscriptions: metrics.data.activeSubscriptions,
mrrTrend: trend.data,
segmentDistribution: rfm.data.segments
};
console.log(dashboard);4. Automated Prize Draw
// Create monthly draw
const draw = await client.createPrizeDraw({
name: 'November Grand Prize',
prizePool: 5000,
drawDate: '2025-11-30T20:00:00Z',
description: 'All active subscribers automatically entered'
});
// On draw date (via cron job)
const result = await client.executePrizeDraw(draw.data.drawId);
console.log(`Winner: ${result.data.winnerId}`);
console.log(`Blockchain Proof: ${result.data.blockchainTxHash}`);
// Notify winner
const winner = await client.getCustomer(result.data.winnerId);
console.log(`Email: ${winner.data.email}`);Rate Limits
- Standard Plan: 1,000 requests/hour
- Pro Plan: 10,000 requests/hour
- Enterprise: Custom limits
Rate limit headers returned with every response:
X-RateLimit-Limit- Max requests per hourX-RateLimit-Remaining- Remaining requestsX-RateLimit-Reset- Timestamp when limit resets
Support
Documentation:
- API Docs: https://aivawins.ai/developers/
- Quick Start: https://aivawins.ai/quick-start/
- RFM Guide: https://aivawins.ai/rfm-guide/
Interactive API:
- Swagger UI: https://api.aivawins.ai/swagger
Support:
- Email: [email protected]
- GitHub Issues: https://github.com/aiva-platform/issues
Contributing
Contributions welcome! Please submit a pull request or open an issue.
License
MIT License - see LICENSE file for details
Changelog
1.0.0 (November 2025)
- Initial release
- 35+ API methods
- Full TypeScript support
- Complete AIVA Merchant API coverage
Built with ❤️ by the AIVA Platform Team
For more information, visit aivawins.ai
