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 |
|---|---|---|
| string | Required. The amount of credit to grant, as a string representation of a number. |
| string | Required. The ID of the currency for this grant. |
| string | Required. The ID or DID of the customer to receive the credit. |
| string | An optional name for the credit grant for internal reference. |
| 'paid' | 'promotional' | Required. The category of the grant. |
| number | Optional. A number between 0 and 100 used to determine the order of application. Lower numbers are applied first. Defaults to |
| number | Optional. A Unix timestamp indicating when the grant becomes active. If not provided, it becomes effective immediately. |
| number | Optional. A Unix timestamp indicating when the grant expires. |
| object | Optional. Defines rules for where this credit can be applied. See details below. If not set, it defaults to all metered prices. |
| 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 |
|---|---|---|
| object | Defines the scope of prices the credit grant applies to. |
scope Object Properties
Name | Type | Description |
|---|---|---|
| string[] | An array of Price IDs. If specified, the credit grant will only apply to these prices. |
| string | Can be set to |
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 IDParameters
Name | Type | Description |
|---|---|---|
| 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 IDParameters
Name | Type | Description |
|---|---|---|
| string | Required. The ID of the credit grant to update. |
| object | A set of key-value pairs to store on the object. To remove a key, set its value to |
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 |
|---|---|---|
| string | Optional. Filter grants by a specific customer ID or DID. |
| string | Optional. Filter grants by currency ID. |
| string | Optional. A comma-separated string of statuses to filter by (e.g., |
| boolean | Optional. Filter by live mode. |
| string | Optional. A general search query string. |
| number | Optional. The page number for pagination. Defaults to |
| number | Optional. The number of items per page. Defaults to |
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 IDParameters
Name | Type | Description |
|---|---|---|
| string | Required. The ID or DID of the customer whose credit summary you want to retrieve. |
| 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.