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 Polar SDK or API to create a customer programmatically:
create-customer.ts
Copy
Ask AI
import { Polar } from "@polar-sh/sdk";const polar = new Polar({ accessToken: process.env.POLAR_ACCESS_TOKEN,});// Create a new customerawait polar.customers.create({ email: "[email protected]", name: "John Doe", externalId: "user_123", // Your internal user ID (optional)});
Use the externalId field to link Polar customers with your internal user system. This allows you to reference customers without storing Polar’s internal ID.
If you set an externalId when creating the customer, you can use it in event ingestion instead of the Polar customer ID:
Copy
Ask AI
// Instead of using customerId, use externalCustomerIdawait polar.events.ingest({ events: [{ name: "api_usage", externalCustomerId: "user_123", // Your internal ID metadata: { units: -10 } }]});
import { Polar } from "@polar-sh/sdk";const polar = new Polar({ accessToken: process.env.POLAR_ACCESS_TOKEN,});async function grantCredits(customerId: string, credits: number) { await polar.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
Ask AI
import { Polar } from "@polar-sh/sdk";const polar = new Polar({ accessToken: process.env.POLAR_ACCESS_TOKEN,});async function grantCreditsToExternalUser(externalUserId: string, credits: number) { await polar.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);