Credit Grants


Credit Grant objects are used to issue credits to your customers, which can then be applied to future invoices, particularly in usage-based or credit-based billing models. Each grant tracks the total amount, the remaining balance, its status, and any specific applicability rules.

For a broader understanding of how to implement a complete credit-based system, refer to our guide on Credit-Based Billing.

The Credit Grant Object#

A CreditGrant object contains all the details about a specific issuance of credits to a customer.

The Credit Grant Object

{
  "id": "crdg_1B2c3D4e5F6g7H8i9J0k1L2m",
  "object": "credit_grant",
  "amount": "5000",
  "currency_id": "curr_usd",
  "customer_id": "cus_a1b2c3d4e5f6g7h8",
  "name": "Promotional Onboarding Credit",
  "category": "promotional",
  "priority": 50,
  "status": "granted",
  "effective_at": 1672531200,
  "expires_at": 1704067199,
  "granted_at": 1672531200,
  "remaining_amount": "3500",
  "applicability_config": {
    "scope": {
      "price_type": "metered"
    }
  },
  "metadata": {
    "campaign_id": "promo_q1_2024"
  },
  "livemode": true,
  "created_at": "2023-01-01T00:00:00.000Z",
  "updated_at": "2023-01-15T10:30:00.000Z",

See all 13 lines

Create a Credit Grant#

Issues a new credit grant to a customer. If the specified customer does not exist, a new customer will be created automatically based on the provided customer_id (DID).

Create a Credit Grant

import payment from '@blocklet/payment-js';

async function createCreditGrant() {
  try {
    const creditGrant = await payment.creditGrants.create({
      amount: '100.00',
      currency_id: 'curr_usd', // Replace with a valid currency ID
      customer_id: 'cus_a1b2c3d4e5f6g7h8', // or a user DID
      name: 'Initial sign-up bonus',
      category: 'promotional',
      priority: 50,
      expires_at: Math.floor(new Date('2024-12-31').getTime() / 1000),
      metadata: {
        source: 'marketing_campaign_fall_2024'
      }
    });
    console.log('Credit grant created:', creditGrant);
  } catch (error) {
    console.error('Error creating credit grant:', error.message);
  }
}

createCreditGrant();

Parameters

Name

Type

Description

amount

string

Required. The amount of credit to grant, as a string representation of a number.

currency_id

string

Required. The ID of the currency for this grant.

customer_id

string

Required. The ID or DID of the customer to receive the credit.

name

string

An optional name for the credit grant for internal reference.

category

'paid' | 'promotional'

Required. The category of the grant. paid grants are typically purchased by the customer, while promotional grants are given away.

priority

number

Optional. A number between 0 and 100 used to determine the order of application. Lower numbers are applied first. Defaults to 50.

effective_at

number

Optional. A Unix timestamp indicating when the grant becomes active. If not provided, it becomes effective immediately.

expires_at

number

Optional. A Unix timestamp indicating when the grant expires.

applicability_config

object

Optional. Defines rules for where this credit can be applied. See details below. If not set, it defaults to all metered prices.

metadata

object

Optional. A set of key-value pairs that you can attach to the object. Useful for storing additional information.

applicability_config Object Properties

Name

Type

Description

scope

object

Defines the scope of prices the credit grant applies to.

scope Object Properties

Name

Type

Description

prices

string[]

An array of Price IDs. If specified, the credit grant will only apply to these prices.

price_type

string

Can be set to 'metered'. If specified, the credit grant will apply to all prices of this type.

Returns

A TCreditGrantExpanded object if the call is successful.

Retrieve a Credit Grant#

Retrieves the details of an existing credit grant by its unique identifier.

Retrieve a Credit Grant

import payment from '@blocklet/payment-js';

async function getCreditGrant(grantId) {
  try {
    const creditGrant = await payment.creditGrants.retrieve(grantId);
    console.log('Retrieved credit grant:', creditGrant);
  } catch (error) {
    console.error(`Error retrieving credit grant ${grantId}:`, error.message);
  }
}

getCreditGrant('crdg_1B2c3D4e5F6g7H8i9J0k1L2m'); // Replace with a valid credit grant ID

Parameters

Name

Type

Description

id

string

Required. The unique identifier of the credit grant to retrieve.

Returns

A TCreditGrantExpanded object with an additional items property containing an array of expanded Price objects if applicability_config.scope.prices is set.

Update a Credit Grant#

Updates the specified credit grant by setting or unsetting the metadata property. Other properties cannot be updated.

Update a Credit Grant

import payment from '@blocklet/payment-js';

async function updateCreditGrantMetadata(grantId) {
  try {
    const result = await payment.creditGrants.update(grantId, {
      metadata: {
        source: 'marketing_campaign_fall_2024',
        updated_by: 'admin_user_xyz'
      }
    });
    console.log('Update successful:', result.success);
  } catch (error) {
    console.error(`Error updating credit grant ${grantId}:`, error.message);
  }
}

updateCreditGrantMetadata('crdg_1B2c3D4e5F6g7H8i9J0k1L2m'); // Replace with a valid credit grant ID

Parameters

Name

Type

Description

id

string

Required. The ID of the credit grant to update.

metadata

object

A set of key-value pairs to store on the object. To remove a key, set its value to null.

Returns

An object containing a success boolean.

Response

{
  "success": true
}

List Credit Grants#

Returns a paginated list of credit grants. You can filter the list based on various parameters.

List Credit Grants

import payment from '@blocklet/payment-js';

async function listCustomerCreditGrants() {
  try {
    const grants = await payment.creditGrants.list({
      customer_id: 'cus_a1b2c3d4e5f6g7h8', // Replace with a valid customer ID
      status: 'granted,pending',
      pageSize: 10
    });
    console.log(`Found ${grants.count} grants.`);
    grants.list.forEach(grant => {
      console.log(`- ${grant.id} (${grant.status})`);
    });
  } catch (error) {
    console.error('Error listing credit grants:', error.message);
  }
}

listCustomerCreditGrants();

Parameters

Name

Type

Description

customer_id

string

Optional. Filter grants by a specific customer ID or DID.

currency_id

string

Optional. Filter grants by currency ID.

status

string

Optional. A comma-separated string of statuses to filter by (e.g., 'granted,pending,depleted').

livemode

boolean

Optional. Filter by live mode.

q

string

Optional. A general search query string.

page

number

Optional. The page number for pagination. Defaults to 1.

pageSize

number

Optional. The number of items per page. Defaults to 20.

Returns

A paginated object containing a list of TCreditGrantExpanded objects and a count of the total number of records.

Get Credit Summary#

Retrieves a summary of a customer's effective credit balances, grouped by currency. This is useful for displaying a customer's total available credit.

Get Credit Summary

import payment from '@blocklet/payment-js';

async function getCustomerCreditSummary(customerId) {
  try {
    const summary = await payment.creditGrants.summary({ customer_id: customerId });
    console.log('Customer Credit Summary:', summary);
  } catch (error) {
    console.error(`Error fetching credit summary for ${customerId}:`, error.message);
  }
}

getCustomerCreditSummary('cus_a1b2c3d4e5f6g7h8'); // Replace with a valid customer ID

Parameters

Name

Type

Description

customer_id

string

Required. The ID or DID of the customer whose credit summary you want to retrieve.

subscription_id

string

Optional. If provided, the summary will only include credits applicable to the prices in this specific subscription.

Returns

Returns a CreditSummary object. This is a map where each key is a currency ID. The value is an object containing the total and remaining credit amounts for that currency, along with a count of active grants.

Response

{
  "curr_usd": {
    "paymentCurrency": {
      "id": "curr_usd",
      "name": "United States Dollar",
      "symbol": "$",
      "decimal": 2
    },
    "totalAmount": "15000",
    "remainingAmount": "8500",
    "grantCount": 2
  },
  "curr_eur": {
    "paymentCurrency": {
      "id": "curr_eur",
      "name": "Euro",
      "symbol": "€",
      "decimal": 2
    },
    "totalAmount": "2000",
    "remainingAmount": "2000",
    "grantCount": 1
  }
}

Next, you can explore how credit consumption is recorded by viewing the Credit Transactions API.