Skip to main content
If you’ve developed an API especially one that’s compute-intensive, such as for code execution, inference, or data processing - it’s time to consider how you’ll monetize it. But not just any monetization model will do. Traditional options like subscriptions, postpaid billing, or prepaid credits often fall short for APIs with unpredictable usage patterns, variable costs, and strict performance requirements. This guide introduces a pay-as-you-go model powered by real-time payments, designed for modern API services. With this setup, your users pay exactly for what they consume, and payments are processed instantly. There’s no need to manage user balances manually, chase down unpaid invoices, or limit usage through rate limiting. Throughout this guide, we’ll use a code execution API as our example — think of a service inspired by the popular open-source platform Judge0, where users can submit code in various programming languages (Python, JavaScript, Rust, etc.) and receive execution results. We’ll charge users a fixed fee per code submission.

Merchant Onboarding & Product Setup

1

Create a Paygentic account

Go to platform.paygentic.io and sign up. Choose Merchant during registration.
2

Create a Product

Open your merchant dashboard and create a new product.
3

Define Billable Metrics

This is what you’ll charge for — e.g., number of code submissions or execution timeFor different API tiers, you can create separate metrics:
  • Basic Submissions: Simple languages like Python, JavaScript
  • Premium Submissions: Complex languages like Rust, Haskell
  • Execution Time: Actual processing time in seconds
4

Create Plan and Price

  • Create a usage plan
  • Set a price for your metric (e.g., $0.001 per submission)

Customer Onboarding

Now that your product is configured, you need to programmatically create customers and subscriptions when users sign up for your API service.
1

Create a Customer

When a new user signs up for your API, create them as a managed customer in Paygentic:
// Create a managed customer when user signs up
const customer = await fetch('https://api.paygentic.io/v0/customers', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${process.env.PAYGENTIC_API_KEY}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    merchantId: process.env.PAYGENTIC_MERCHANT_ID,
    consumer: {
      name: userProfile.name,
      email: userProfile.email,
      phone: userProfile.phone,
      address: {
        line1: userProfile.addressLine1,
        city: userProfile.city,
        state: userProfile.state,
        country: userProfile.country,
        zipCode: userProfile.zipCode
      }
    }
  })
});

const customerData = await customer.json();
const customerId = customerData.customerId; // Store this in your database!
The API is idempotent - if a customer already exists for this email/merchant combination, it returns the existing customer ID instead of creating a duplicate.
2

Create a Subscription

Once you have a customer ID, create a subscription to your plan. This establishes the billing relationship:
// Subscribe customer to your usage plan
const subscription = await fetch('https://api.paygentic.io/v0/subscriptions', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${process.env.PAYGENTIC_API_KEY}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    customerId: customerId,
    planId: process.env.PAYGENTIC_PLAN_ID, // From your product's plan
    name: 'Code Execution API Access',
    startedAt: new Date().toISOString(),
    prefundAmount: "10" // Optional: Initial account funding
  })
});

const subscriptionData = await subscription.json();
If your plan has upfront fees or if you specified a prefundAmount, the response will include a payment.checkoutUrl that the customer must visit to complete payment before they can start using the API.
3

Handle Payment (if required)

If the subscription requires initial payment, direct the user to complete it:
if (subscriptionData.payment?.checkoutUrl) {
  // Redirect user to payment page or embed in iframe
  window.location.href = subscriptionData.payment.checkoutUrl;

  // Or send them the link via email
  await sendPaymentEmail(userProfile.email, subscriptionData.payment.checkoutUrl);
}
For a seamless experience, you can embed the payment checkout in an iframe within your application. See the Customer Lifecycle guide for implementation details.

Tracking Usage

Once customers are onboarded and have active subscriptions, track their usage in real-time. This involves optional entitlement creation for payment pre-authorization and mandatory usage event reporting.
1

Report Usage Events

When a customer uses your API, report the usage immediately to trigger real-time billing:
// Report usage after successful code execution
const usageEvent = await fetch('https://api.paygentic.io/v0/usage', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${process.env.PAYGENTIC_API_KEY}`
  },
  body: JSON.stringify({
    customerId: customerId,
    merchantId: process.env.PAYGENTIC_MERCHANT_ID,
    idempotencyKey: `report_${timestamp}_${submissionId}`,
    properties: [
      {
        billableMetricId: process.env.PAYGENTIC_BILLABLE_METRIC_ID,
        quantity: 3
      }
    ],
    entitlementId: entitlementId,
    timestamp: new Date().toISOString()
  })
});

if (usageEvent.id) {
  console.log('✅ Usage reported and customer charged');
} else {
  console.error('❌ Failed to report usage:', await usageEvent.text());
}
While the entitlementId is optional when reporting usage, it is considered best practice to include it. Creating and consuming from a pre-authorized entitlement helps guarantee that you will be paid for the reported usage in full.
2

Provide Customer Portal Access

Give your API users visibility into their usage and billing through the customer portal:
// Generate a portal link for customer self-service
async function getPortalLink(subscriptionId) {
  const response = await fetch(
    `https://api.paygentic.io/v0/subscriptions/${subscriptionId}/portal`,
    {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${process.env.PAYGENTIC_API_KEY}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({})
    }
  );

  const data = await response.json();
  return data.url; // Single-use portal URL
}

// Add to your API dashboard
app.get('/billing-portal', async (req, res) => {
  const subscriptionId = req.user.subscriptionId;
  const portalUrl = await getPortalLink(subscriptionId);
  res.redirect(portalUrl);
});
The portal allows customers to:
  • View real-time usage metrics
  • Download invoices
  • Manage payment methods
  • Track spending

Complete Integration Example

Here’s how all the pieces fit together in your API service:
class CodeExecutionService {
  constructor() {
    this.merchantId = process.env.PAYGENTIC_MERCHANT_ID;
    this.apiKey = process.env.PAYGENTIC_API_KEY;
    this.planId = process.env.PAYGENTIC_PLAN_ID;
    this.metricId = process.env.PAYGENTIC_BILLABLE_METRIC_ID;
  }

  // Called when user signs up
  async onboardUser(userProfile) {
    // 1. Create customer
    const customer = await this.createCustomer(userProfile);

    // 2. Create subscription
    const subscription = await this.createSubscription(customer.customerId);

    // 3. Handle payment if needed
    if (subscription.payment?.checkoutUrl) {
      return {
        requiresPayment: true,
        paymentUrl: subscription.payment.checkoutUrl
      };
    }

    // 4. Store in your database
    await this.saveUserBilling(userProfile.id, {
      customerId: customer.customerId,
      subscriptionId: subscription.id
    });

    return {
      requiresPayment: false,
      customerId: customer.customerId
    };
  }

  // Called for each API request
  async handleCodeExecution(userId, code, language) {
    const billing = await this.getUserBilling(userId);

    try {
      // 1. Pre-authorize payment (optional but recommended)
      const entitlement = await this.createEntitlement(billing.customerId, 1);

      // 2. Execute code
      const result = await this.executeCode(code, language);

      // 3. Report usage
      await this.reportUsage(
        billing.customerId,
        result.executionId,
        entitlement.id
      );

      return result;
    } catch (error) {
      console.error('Execution failed:', error);
      throw error;
    }
  }

  async createCustomer(userProfile) {
    const response = await fetch('https://api.paygentic.io/v0/customers', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${this.apiKey}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        merchantId: this.merchantId,
        consumer: {
          name: userProfile.name,
          email: userProfile.email,
          phone: userProfile.phone,
          address: userProfile.address
        }
      })
    });

    return response.json();
  }

  async createSubscription(customerId) {
    const response = await fetch('https://api.paygentic.io/v0/subscriptions', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${this.apiKey}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        customerId: customerId,
        planId: this.planId,
        name: 'Code Execution API Access',
        startedAt: new Date().toISOString(),
        prefundAmount: "10"
      })
    });

    return response.json();
  }

  async createEntitlement(customerId, quantity) {
    const response = await fetch('https://edge-api.paygentic.io/v0/entitlements', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${this.apiKey}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        merchantId: this.merchantId,
        customerId: customerId,
        entitlementData: [{
          billableMetricId: this.metricId,
          quantity: quantity
        }]
      })
    });

    return response.json();
  }

  async reportUsage(customerId, executionId, entitlementId) {
    const response = await fetch('https://edge-api.paygentic.io/v0/usage', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${this.apiKey}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        idempotencyKey: `${executionId}_${Date.now()}`,
        entitlementId: entitlementId,
        customerId: customerId,
        merchantId: this.merchantId,
        timestamp: new Date().toISOString(),
        properties: [{
          billableMetricId: this.metricId,
          quantity: 1
        }],
        metadata: {
          executionId: executionId
        }
      })
    });

    if (!response.ok) {
      throw new Error(`Usage reporting failed: ${await response.text()}`);
    }

    return response.json();
  }
}

Next Steps

You’ve successfully integrated pay-as-you-go monetization! Your API now benefits from:
  • Instant Revenue: Get paid immediately when customers use your API
  • Zero Risk: No unpaid usage or bad debt from customers
  • Transparent Pricing: Customers see exactly what they pay for each request
  • Scalable Architecture: Handles high-volume APIs with edge infrastructure

Additional Resources