Blog
    Tutorial8 min read

    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

    Implementing Usage-Based Pricing with cred.diy

    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:

    1. Navigate to your dashboard
    2. Click "Create Project"
    3. Name your project and add a description
    4. 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

    1. Always check balance before deducting to provide good UX
    2. Use idempotency keys for critical operations
    3. Log all transactions with meaningful metadata
    4. Implement retry logic for API failures
    5. Cache balances where appropriate, but verify on deduction

    Testing Your Integration

    Use test API keys to validate your implementation:

    1. Create test users
    2. Issue test credits
    3. Simulate usage patterns
    4. Verify balance updates
    5. Test edge cases (zero balance, concurrent deductions)

    Next Steps

    Your usage-based pricing is now ready for production!

    Try it on a real project.