Implementing Usage-Based Pricing with cred.diy
A step-by-step guide to integrating credit-based pricing into your application using our REST API and webhooks.
By cred.diy Team

This tutorial walks you through implementing a complete usage-based pricing system using cred.diy. By the end, you'll have a working credit system that issues, tracks, and bills for usage.
Prerequisites
- A cred.diy account with API access
- Basic knowledge of REST APIs
- Your application backend (Node.js, Python, etc.)
Step 1: Set Up Your Project
First, create a new project in the cred.diy dashboard:
- Navigate to your dashboard
- Click "Create Project"
- Name your project and add a description
- Copy your API key from the API Keys section
Step 2: Define Your Credit Type
Create a credit type that represents your usage unit:
// Example: Create a credit type for API calls
const creditType = {
name: "API Credits",
symbol: "API",
description: "Credits for API usage",
exchange_rate: 1.0 // 1 credit = $0.01
};
Step 3: Create Pricing Tiers
Set up packages users can purchase:
const tiers = [
{ name: "Starter", credits: 1000, price: 9.99 },
{ name: "Growth", credits: 5000, price: 39.99 },
{ name: "Scale", credits: 25000, price: 149.99 }
];
Step 4: Issue Credits on Purchase
When a user completes a purchase, issue their credits:
const issueCredits = async (userId, amount) => {
const response = await fetch(
'https://eutdgemlrpvnxfkkpvlu.supabase.co/functions/v1/credits-api/issue',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': process.env.CRED_API_KEY
},
body: JSON.stringify({
user_id: userId,
credit_type_id: 'your_credit_type_id',
amount: amount,
reason: 'Purchase'
})
}
);
return response.json();
};
Step 5: Deduct Credits on Usage
Before performing billable actions, check and deduct credits:
const processApiCall = async (userId) => {
// First, check balance
const balance = await getBalance(userId);
if (balance < 1) {
throw new Error('Insufficient credits');
}
// Deduct the credit
await deductCredits(userId, 1, 'API call');
// Process the actual API call
return performApiOperation();
};
Step 6: Set Up Webhooks
Listen for credit events to keep your system in sync:
app.post('/webhooks/cred', (req, res) => {
const event = req.body;
switch (req.headers['x-cred-event']) {
case 'credits.low':
notifyUser(event.user_id, 'Low balance!');
break;
case 'purchase.completed':
sendReceipt(event.user_id, event.amount);
break;
}
res.status(200).send('OK');
});
Step 7: Add Checkout Integration
Enable users to purchase more credits:
const createCheckout = async (userId, tierId) => {
const response = await fetch(
'https://eutdgemlrpvnxfkkpvlu.supabase.co/functions/v1/hosted-checkout',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': process.env.CRED_API_KEY
},
body: JSON.stringify({
user_id: userId,
pricing_tier_id: tierId,
success_url: 'https://yourapp.com/success',
cancel_url: 'https://yourapp.com/cancel'
})
}
);
const { url } = await response.json();
return url; // Redirect user to this URL
};
Best Practices
- Always check balance before deducting to provide good UX
- Use idempotency keys for critical operations
- Log all transactions with meaningful metadata
- Implement retry logic for API failures
- Cache balances where appropriate, but verify on deduction
Testing Your Integration
Use test API keys to validate your implementation:
- Create test users
- Issue test credits
- Simulate usage patterns
- Verify balance updates
- Test edge cases (zero balance, concurrent deductions)
Next Steps
- Set up webhooks for real-time notifications
- Implement referral programs to drive growth
- Add analytics to track usage patterns
Your usage-based pricing is now ready for production!

Building AI-Powered Apps with Credit Metering
How to implement per-request credit billing for AI features like image generation, chat completions, and embeddings.

Using Webhooks for Real-Time Credit Updates
How to leverage webhooks to keep your application in sync with credit transactions and purchases.