Subscriptions
Subscription objects allow you to charge a customer on a recurring basis. A subscription ties a customer to a particular plan or set of prices. This section covers all the API methods available for managing subscriptions.
For more information on managing the individual line items of a subscription, see the Subscription Items documentation. To manage customers, refer to the Customers documentation.
Retrieve a Subscription#
Retrieves the details of an existing subscription. You need only provide the unique subscription identifier.
Parameters
Name | Type | Description |
---|---|---|
|
| The unique identifier of the subscription to retrieve. |
Returns
Returns a TSubscriptionExpanded
object if a valid identifier was provided. The object includes expanded details on the customer, payment method, payment currency, and subscription items.
Example
import payment from '@blocklet/payment-js';
async function getSubscription(subscriptionId) {
try {
const subscription = await payment.subscriptions.retrieve(subscriptionId);
console.log('Retrieved subscription:', subscription.id, 'Status:', subscription.status);
} catch (error) {
console.error(`Error retrieving subscription ${subscriptionId}:`, error.message);
}
}
// Replace with a valid subscription ID
getSubscription('sub_xxxxxxxxxxxxxx');
Example Response
{
"id": "sub_xxxxxxxxxxxxxx",
"status": "active",
"customer_id": "cus_xxxxxxxxxxxxxx",
"current_period_start": 1672531200,
"current_period_end": 1675209600,
"items": [
{
"id": "si_xxxxxxxxxxxxxx",
"price_id": "price_xxxxxxxxxxxxxx",
"quantity": 1
}
],
"customer": {
"id": "cus_xxxxxxxxxxxxxx",
"did": "did:abt:z123..."
}
}
This example shows how to fetch and log the details of a specific subscription.
Update a Subscription#
Updates an existing subscription by setting the values of the parameters passed. Any parameters not provided will be left unchanged.
Parameters
Name | Type | Description |
---|---|---|
|
| The identifier of the subscription to be updated. |
|
| An object containing the fields to update. See details below. |
data
Object Properties
Name | Type | Description |
---|---|---|
|
| An optional description for the subscription. |
|
| A set of key-value pairs that you can attach to an object. |
|
| Determines how to handle failures when collecting payment. Can be |
|
| Determines how to handle prorations when the billing cycle changes. Can be |
|
| Resets the billing cycle anchor. Can be |
|
| A Unix timestamp indicating the end of the trial period. Can also be set to |
|
| A list of subscription items to update. See the table below for details. |
|
| A list of service actions associated with the subscription. |
items
Object Properties
Name | Type | Description |
---|---|---|
|
| The ID of the subscription item to update or delete. Required for updates and deletions. |
|
| The ID of the price to add. Required for adding a new item. |
|
| The quantity of the subscription item. |
|
| Set to |
|
| For metered billing, set to |
Returns
Returns the updated TSubscription
object.
Example
import payment from '@blocklet/payment-js';
async function updateSubscriptionMetadata(subscriptionId) {
try {
const subscription = await payment.subscriptions.update(subscriptionId, {
metadata: {
order_id: 'new-order-id-123'
}
});
console.log('Subscription updated:', subscription.id);
console.log('New metadata:', subscription.metadata);
} catch (error) {
console.error(`Error updating subscription ${subscriptionId}:`, error.message);
}
}
// Replace with a valid subscription ID
updateSubscriptionMetadata('sub_xxxxxxxxxxxxxx');
Example Response
{
"id": "sub_xxxxxxxxxxxxxx",
"status": "active",
"metadata": {
"order_id": "new-order-id-123"
},
"items": []
}
List Subscriptions#
Returns a list of your subscriptions. The subscriptions are returned sorted by creation date, with the most recent subscriptions appearing first.
Parameters
Name | Type | Description |
---|---|---|
|
| Filter subscriptions by status. Comma-separated for multiple values (e.g., |
|
| Filter subscriptions by a specific customer ID. |
|
| Filter subscriptions by a specific customer DID. |
|
| Filter by custom metadata fields. |
|
| Sort order (e.g., |
|
| If |
|
| The page number for pagination. Defaults to |
|
| The number of items per page. Defaults to |
Returns
Returns a paginated list of TSubscriptionExpanded
objects.
Example
import payment from '@blocklet/payment-js';
async function listActiveSubscriptions() {
try {
const subscriptions = await payment.subscriptions.list({
status: 'active',
pageSize: 10
});
console.log(`Found ${subscriptions.count} active subscriptions.`);
subscriptions.list.forEach(sub => {
console.log(`- ID: ${sub.id}, Customer: ${sub.customer_id}`);
});
} catch (error) {
console.error('Error listing subscriptions:', error.message);
}
}
listActiveSubscriptions();
Example Response
{
"count": 5,
"list": [
{
"id": "sub_xxxxxxxxxxxxxx",
"status": "active",
"customer_id": "cus_xxxxxxxxxxxxxx"
}
],
"paging": {
"page": 1,
"pageSize": 10
}
}
Search Subscriptions#
Searches for subscriptions that match a given query.
Parameters
Name | Type | Description |
---|---|---|
|
| The search query string. |
|
| The page number for pagination. Defaults to |
|
| The number of items per page. Defaults to |
Returns
Returns a paginated list of TSubscriptionExpanded
objects that match the search query.
Example
import payment from '@blocklet/payment-js';
async function searchForSubscription(query) {
try {
const results = await payment.subscriptions.search({ query });
console.log(`Found ${results.count} results for '${query}'.`);
results.list.forEach(sub => console.log(`- ${sub.id}`));
} catch (error) {
console.error('Error searching subscriptions:', error.message);
}
}
searchForSubscription('cus_xxxxxxxxxxxxxx');
Cancel a Subscription#
Cancels a customer’s subscription. The subscription status will be marked as canceled
.
Parameters
Name | Type | Description |
---|---|---|
|
| The identifier of the subscription to cancel. |
|
| An object containing cancellation details. See below. |
data
Object Properties
Name | Type | Description |
---|---|---|
|
| When to cancel the subscription. Options: |
|
| Required if |
|
| Specifies if a refund should be issued. Options: |
|
| Customer feedback for the cancellation. |
|
| Internal comment about the cancellation. |
|
| The reason for cancellation (e.g., |
|
| For stake-based subscriptions, how to handle the stake. Options: |
|
| Required if |
Returns
Returns the canceled TSubscription
object.
Example
import payment from '@blocklet/payment-js';
async function cancelSubscriptionAtPeriodEnd(subscriptionId) {
try {
const subscription = await payment.subscriptions.cancel(subscriptionId, {
at: 'current_period_end',
reason: 'cancellation_requested'
});
console.log(`Subscription ${subscription.id} scheduled for cancellation.`);
} catch (error) {
console.error(`Error canceling subscription ${subscriptionId}:`, error.message);
}
}
// Replace with a valid subscription ID
cancelSubscriptionAtPeriodEnd('sub_xxxxxxxxxxxxxx');
Recover a Subscription#
Reactivates a canceled subscription that was set to cancel at the end of the current billing period (cancel_at_period_end
was true
).
Parameters
Name | Type | Description |
---|---|---|
|
| The identifier of the subscription to recover. |
Returns
Returns the recovered TSubscription
object with cancel_at_period_end
set to false
.
Example
import payment from '@blocklet/payment-js';
async function recoverSubscription(subscriptionId) {
try {
const subscription = await payment.subscriptions.recover(subscriptionId);
console.log(`Subscription ${subscription.id} has been recovered.`);
} catch (error) {
console.error(`Error recovering subscription ${subscriptionId}:`, error.message);
}
}
// Replace with a valid subscription ID
recoverSubscription('sub_xxxxxxxxxxxxxx');
Pause a Subscription#
Pauses payment collection for a subscription.
Parameters
Name | Type | Description |
---|---|---|
|
| The identifier of the subscription to pause. |
|
| An object containing pause details. See below. |
data
Object Properties
Name | Type | Description |
---|---|---|
|
| Specifies when the subscription should resume. Use |
|
| Required if |
|
| Determines the behavior of invoices created while paused. Can be |
Returns
Returns the paused TSubscription
object.
Example
import payment from '@blocklet/payment-js';
async function pauseSubscription(subscriptionId) {
try {
const subscription = await payment.subscriptions.pause(subscriptionId, {});
console.log(`Subscription ${subscription.id} is now paused indefinitely.`);
} catch (error) {
console.error(`Error pausing subscription ${subscriptionId}:`, error.message);
}
}
// Replace with a valid subscription ID
pauseSubscription('sub_xxxxxxxxxxxxxx');
Resume a Subscription#
Resumes a paused subscription.
Parameters
Name | Type | Description |
---|---|---|
|
| The identifier of the subscription to resume. |
Returns
Returns the resumed TSubscription
object.
Example
import payment from '@blocklet/payment-js';
async function resumeSubscription(subscriptionId) {
try {
const subscription = await payment.subscriptions.resume(subscriptionId);
console.log(`Subscription ${subscription.id} has been resumed.`);
} catch (error) {
console.error(`Error resuming subscription ${subscriptionId}:`, error.message);
}
}
// Replace with a valid subscription ID
resumeSubscription('sub_xxxxxxxxxxxxxx');
Delete a Subscription#
Permanently deletes a subscription and all associated data. This action cannot be undone and is not available in production environments.
Parameters
Name | Type | Description |
---|---|---|
|
| The identifier of the subscription to delete. |
Returns
Returns the deleted TSubscription
object.
Example
import payment from '@blocklet/payment-js';
async function deleteSubscription(subscriptionId) {
try {
const subscription = await payment.subscriptions.del(subscriptionId);
console.log(`Subscription ${subscription.id} has been deleted.`);
} catch (error) {
console.error(`Error deleting subscription ${subscriptionId}:`, error.message);
}
}
// Replace with a valid subscription ID
deleteSubscription('sub_xxxxxxxxxxxxxx');
Get Overdue Invoices#
Retrieves a list of overdue (uncollectible) invoices for a specific subscription, along with a summary of amounts due per currency.
Parameters
Name | Type | Description |
---|---|---|
|
| The identifier of the subscription. |
Returns
Returns an object containing the subscription, a list of overdue invoices, and a summary object where keys are currency IDs.
Example
import payment from '@blocklet/payment-js';
async function getOverdue(subscriptionId) {
try {
const result = await payment.subscriptions.overdueInvoices(subscriptionId);
console.log('Overdue Summary:', result.summary);
console.log('Number of overdue invoices:', result.invoices.length);
} catch (error) {
console.error(`Error fetching overdue invoices for ${subscriptionId}:`, error.message);
}
}
getOverdue('sub_xxxxxxxxxxxxxx');
Return Stake#
For subscriptions paid via staking, this method initiates the process of returning the staked amount to the customer. This can only be done for canceled subscriptions.
Parameters
Name | Type | Description |
---|---|---|
|
| The identifier of the canceled subscription. |
Returns
Returns an object confirming the job was scheduled.
Example
import payment from '@blocklet/payment-js';
async function returnSubscriptionStake(subscriptionId) {
try {
const result = await payment.subscriptions.returnStake(subscriptionId);
if (result.success) {
console.log(`Stake return scheduled for subscription ${result.subscriptionId}`);
}
} catch (error) {
console.error(`Error returning stake for ${subscriptionId}:`, error.message);
}
}
returnSubscriptionStake('sub_xxxxxxxxxxxxxx');
This section has covered the core API methods for managing subscriptions. For more detailed control over what a customer is subscribed to, including reporting metered usage, please see the Subscription Items documentation.