> ## Documentation Index
> Fetch the complete documentation index at: https://docs.getruba.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Grant Usage Before a Purchase

> Discover how to grant meter credits to customers before they make any purchase using the Ruba API.

export const RubaSocials = () => {
  if (typeof document === "undefined") {
    return null;
  }
  const inject = () => {
    const footer = document.getElementById("footer");
    if (!footer || document.getElementById("ruba-socials")) {
      return false;
    }
    const isDark = document.querySelector("html.dark") || document.querySelector('html[class*="dark"]');
    const lineColor = isDark ? "#383838" : "#e8e8ed";
    const iconColor = isDark ? "#8e8e93" : "#86868b";
    const markColor = isDark ? "#ffffff" : "#08080c";
    const hoverColor = "#0071e3";
    const div = document.createElement("div");
    div.id = "ruba-socials";
    div.style.cssText = `display:flex;align-items:center;gap:20px;padding-top:20px;margin-top:20px;border-top:1px solid ${lineColor};width:100%`;
    const logo = `<a href="https://getruba.com" style="display:inline-flex;height:24px;align-items:center;gap:8px;text-decoration:none;color:${markColor};line-height:1;"><svg width="24" height="24" viewBox="0 0 120 120" aria-hidden="true" style="display:block;flex:none;"><g transform="translate(2.5 0)"><path d="M19 25h59L65.43 47H19a4 4 0 0 1-4-4V29a4 4 0 0 1 4-4Z" fill="${markColor}"/><path d="M19 73h31.57L38 95H19a4 4 0 0 1-4-4V77a4 4 0 0 1 4-4Z" fill="${markColor}"/><path d="M85 25h25L70 95H45Z" fill="#007AFF"/></g></svg><span style="display:inline-flex;height:24px;align-items:center;font-weight:600;font-size:15px;color:${markColor};letter-spacing:-0.01em;line-height:1;">Ruba</span></a>`;
    const spacer = `<div style="flex:1"></div>`;
    const ig = `<a href="https://instagram.com/getruba" target="_blank" rel="noopener" aria-label="Instagram" style="display:flex;align-items:center;color:${iconColor};transition:color 0.15s ease;" onmouseover="this.style.color='${hoverColor}'" onmouseout="this.style.color='${iconColor}'"><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="2" width="20" height="20" rx="5" ry="5"/><path d="M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z"/><line x1="17.5" y1="6.5" x2="17.51" y2="6.5"/></svg></a>`;
    const li = `<a href="https://linkedin.com/company/getruba" target="_blank" rel="noopener" aria-label="LinkedIn" style="display:flex;align-items:center;color:${iconColor};transition:color 0.15s ease;" onmouseover="this.style.color='${hoverColor}'" onmouseout="this.style.color='${iconColor}'"><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M16 8a6 6 0 0 1 6 6v7h-4v-7a2 2 0 0 0-2-2 2 2 0 0 0-2 2v7h-4v-7a6 6 0 0 1 6-6z"/><rect x="2" y="9" width="4" height="12"/><circle cx="4" cy="4" r="2"/></svg></a>`;
    const x = `<a href="https://x.com/getruba" target="_blank" rel="noopener" aria-label="X" style="display:flex;align-items:center;color:${iconColor};transition:color 0.15s ease;" onmouseover="this.style.color='${hoverColor}'" onmouseout="this.style.color='${iconColor}'"><svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"/></svg></a>`;
    const github = `<a href="https://github.com/rubadot" target="_blank" rel="noopener" aria-label="GitHub" style="display:flex;align-items:center;color:${iconColor};transition:color 0.15s ease;" onmouseover="this.style.color='${hoverColor}'" onmouseout="this.style.color='${iconColor}'"><svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M12 .7a11.5 11.5 0 0 0-3.64 22.4c.58.1.79-.25.79-.56v-2.24c-3.22.7-3.9-1.37-3.9-1.37-.53-1.34-1.29-1.7-1.29-1.7-1.05-.72.08-.71.08-.71 1.16.08 1.78 1.2 1.78 1.2 1.04 1.77 2.72 1.26 3.38.96.1-.75.4-1.26.74-1.55-2.57-.3-5.27-1.29-5.27-5.69 0-1.26.45-2.29 1.19-3.09-.12-.29-.52-1.47.11-3.05 0 0 .97-.31 3.16 1.18A10.96 10.96 0 0 1 12 6.09c.98 0 1.94.13 2.86.39 2.2-1.49 3.16-1.18 3.16-1.18.63 1.58.23 2.76.11 3.05.74.8 1.19 1.83 1.19 3.09 0 4.42-2.7 5.39-5.28 5.68.42.36.79 1.06.79 2.14v3.28c0 .31.21.67.8.56A11.5 11.5 0 0 0 12 .7Z"/></svg></a>`;
    div.innerHTML = logo + spacer + ig + li + x + github;
    footer.appendChild(div);
    return true;
  };
  if (!document.documentElement.dataset.rubaSocialsObserver) {
    document.documentElement.dataset.rubaSocialsObserver = "true";
    const observer = new MutationObserver(() => {
      if (!document.getElementById("ruba-socials")) {
        inject();
      }
    });
    observer.observe(document.body, {
      childList: true,
      subtree: true
    });
  }
  setTimeout(() => {
    if (!inject()) {
      const interval = setInterval(() => {
        if (inject()) {
          clearInterval(interval);
        }
      }, 500);
      setTimeout(() => clearInterval(interval), 10000);
    }
  }, 300);
  return null;
};

<link rel="stylesheet" href="/style.css" />

<RubaSocials />

## The operating model

You may want to grant usage credits to customers even before they make a purchase. This is handy for:

* **Free trial credits** - Give new signups free credits to try your service
* **Promotional campaigns** - Grant credits as part of marketing initiatives
* **Testing and demos** - Provide credits for product demonstrations

This guide walks you through granting credits to customers who don't yet have an active subscription or purchase.

## System flow

To grant credits before a purchase, you need to:

1. Create a customer in Ruba (if they don't exist)
2. Create a meter with **Sum** aggregation to track usage
3. Ingest an event with a **negative value** to grant credits

<Info>
  **Why negative values?**

  When you ingest an event with a negative value (e.g., `-10`) into a meter using **Sum** aggregation, it grants the customer credits. A negative balance means available credits, which get reduced as they use your service.
</Info>

## Step 1: Create a Meter

First, create a meter to track your customers' usage.

<Steps>
  <Step title="Navigate to Meters">
    Open [**Products → Meters**](https://getruba.com/to/dashboard/products/meters) in the dashboard.
  </Step>

  <Step title="Create a new meter">
    Click **Create Meter** and configure:

    * **Name**: Give your meter a descriptive name (e.g., "API Calls" or "Storage Usage")
    * **Filter**: Add filters to match your usage events (e.g., name equals "api\_usage")
    * **Aggregation**: Select **Sum** and enter the property to sum (e.g., `units`)

    <Warning>
      The meter **must use Sum aggregation** for this approach to work.
    </Warning>
  </Step>

  <Step title="Save the meter">
    Save your meter and note the meter name, you'll need this when ingesting events.
  </Step>
</Steps>

Learn more about [creating meters](/features/usage-based-billing/meters).

## Step 2: Create a Customer

If your customer doesn't already exist in Ruba, create them first.

### Option A: Create via Dashboard

<Steps>
  <Step title="Navigate to Customers">
    Open [**Customers**](https://getruba.com/to/dashboard/customers) in the dashboard.
  </Step>

  <Step title="Add new customer">
    Click **Add Customer** and fill in:

    * **Email**: Customer's email address (required)
    * **Name**: Customer's full name (optional)
    * **External ID**: Your internal user ID for easy reference (optional but recommended)
  </Step>

  <Step title="Save customer">
    Click **Save** and note the Customer ID.
  </Step>
</Steps>

### Option B: Create via API

Use the Ruba SDK or API to create a customer programmatically:

```typescript icon="square-js" title="create-customer.ts" theme={"system"}
import { Ruba } from "@getruba/sdk";

const ruba = new Ruba({
  accessToken: process.env.RUBA_ACCESS_TOKEN,
});

// Create a new customer
await ruba.customers.create({
  email: "user@example.com",
  name: "John Doe",
  externalId: "user_123", // Your internal user ID (optional)
});
```

<Tip>
  Use the `externalId` field to link Ruba customers with your internal user system. This lets you reference customers without storing Ruba's internal ID.
</Tip>

### Using External ID

If you set an `externalId` when creating the customer, you can use it in event ingestion in place of the Ruba customer ID:

```typescript theme={"system"}
// Instead of using customerId, use externalCustomerId
await ruba.events.ingest({
  events: [{
    name: "api_usage",
    externalCustomerId: "user_123", // Your internal ID
    metadata: { units: -10 }
  }]
});
```

Learn more about [customer management](/features/customer-management).

## Step 3: Grant Credits by Ingesting a Negative Event

Now that you have a customer and a meter, grant credits by ingesting an event with a negative value.

### Using the Ruba SDK

```typescript icon="square-js" title="grant-credits.ts" theme={"system"}
import { Ruba } from "@getruba/sdk";

const ruba = new Ruba({
  accessToken: process.env.RUBA_ACCESS_TOKEN,
});

async function grantCredits(customerId: string, credits: number) {
  await ruba.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 customer
await grantCredits("cus_abc123", 10);
```

### Using External Customer ID

If you're using `externalId` for customer management:

```typescript icon="square-js" title="grant-credits-external.ts" theme={"system"}
import { Ruba } from "@getruba/sdk";

const ruba = new Ruba({
  accessToken: process.env.RUBA_ACCESS_TOKEN,
});

async function grantCreditsToExternalUser(externalUserId: string, credits: number) {
  await ruba.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 ID
await grantCreditsToExternalUser("user_123", 10);
```

## Step 4: Verify Credits Were Granted

Confirm that the credits were successfully granted to the customer.

### Using Customer Meters API

```typescript theme={"system"}
import { Ruba } from "@getruba/sdk";

const ruba = new Ruba({
  accessToken: process.env.RUBA_ACCESS_TOKEN,
});

// Check customer's meter balance
const meters = await ruba.customerMeters.list({
  customerId: "cus_abc123",
});

meters.items.filter((balance) => balance > 0).forEach((meter) => {
  console.log(`${Math.abs(meter.balance)} credits available for ${meter.meter_id}.`);
});
```

### Example Usage Flow

```typescript theme={"system"}
// Initial state: Customer created, 0 balance
// Grant 10 credits: balance = 10

// Customer uses 3 units
await ruba.events.ingest({
  events: [{
    name: "api_usage",
    customerId: "cus_abc123",
    metadata: { units: 3 } // Positive value for usage
  }]
});

// Balance is now 7 (7 credits remaining)

// Customer uses 8 more units
await ruba.events.ingest({
  events: [{
    name: "api_usage",
    customerId: "cus_abc123",
    metadata: { units: 8 }
  }]
});

// Balance is now -1 (used 1 unit beyond credits)
```
