Create a meter with Sum aggregation to track usage
Ingest an event with a negative value to grant credits
Why negative values?When you ingest an event with a negative value (e.g., -10) to a meter using Sum aggregation, it grants the customer credits. A negative balance means available credits, which get reduced as they use your service.
Use the Spaire SDK or API to create a customer programmatically:
create-customer.ts
Copy
import { Spaire } from "@spaire/sdk";const spaire = new Spaire({ accessToken: process.env.SPAIRE_ACCESS_TOKEN,});// Create a new customerawait spaire.customers.create({ email: "[email protected]", name: "John Doe", externalId: "user_123", // Your internal user ID (optional)});
Use the externalId field to link Spaire customers with your internal user system. This allows you to reference customers without storing Spaire’s internal ID.
If you set an externalId when creating the customer, you can use it in event ingestion instead of the Spaire customer ID:
Copy
// Instead of using customerId, use externalCustomerIdawait spaire.events.ingest({ events: [{ name: "api_usage", externalCustomerId: "user_123", // Your internal ID metadata: { units: -10 } }]});
import { Spaire } from "@spaire/sdk";const spaire = new Spaire({ accessToken: process.env.SPAIRE_ACCESS_TOKEN,});async function grantCredits(customerId: string, credits: number) { await spaire.events.ingest({ events: [ { customerId, name: "api_usage", // Must match your meter's filter name metadata: { units: -credits, // Negative value grants credits }, }, ], }); console.log(`Granted ${credits} credits to customer ${customerId}`);}// Grant 10 credits to a customerawait grantCredits("cus_abc123", 10);
If you’re using externalId for customer management:
grant-credits-external.ts
Copy
import { Spaire } from "@spaire/sdk";const spaire = new Spaire({ accessToken: process.env.SPAIRE_ACCESS_TOKEN,});async function grantCreditsToExternalUser(externalUserId: string, credits: number) { await spaire.events.ingest({ events: [ { name: "api_usage", // Must match your meter's filter name externalCustomerId: externalUserId, // Use your internal ID metadata: { units: -credits, // Negative value grants credits }, }, ], }); console.log(`Granted ${credits} credits to user ${externalUserId}`);}// Grant 10 credits using your internal user IDawait grantCreditsToExternalUser("user_123", 10);