Used to check for browser translation.
用于检测浏览器翻译。
ブラウザの翻訳を検出する
API Reference

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

id

string

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

id

string

The identifier of the subscription to be updated.

data

object

An object containing the fields to update. See details below.

data Object Properties

Name

Type

Description

description

string

An optional description for the subscription.

metadata

object

A set of key-value pairs that you can attach to an object.

payment_behavior

string

Determines how to handle failures when collecting payment. Can be allow_incomplete, error_if_incomplete, or pending_if_incomplete.

proration_behavior

string

Determines how to handle prorations when the billing cycle changes. Can be always_invoice, create_prorations, or none.

billing_cycle_anchor

string

Resets the billing cycle anchor. Can be now or unchanged.

trial_end

number | string

A Unix timestamp indicating the end of the trial period. Can also be set to now to end the trial immediately.

items

SubscriptionUpdateItem[]

A list of subscription items to update. See the table below for details.

service_actions

ServiceAction[]

A list of service actions associated with the subscription.

items Object Properties

Name

Type

Description

id

string

The ID of the subscription item to update or delete. Required for updates and deletions.

price_id

string

The ID of the price to add. Required for adding a new item.

quantity

number

The quantity of the subscription item.

deleted

boolean

Set to true to delete this subscription item.

clear_usage

boolean

For metered billing, set to true to clear usage on deletion.

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

status

string

Filter subscriptions by status. Comma-separated for multiple values (e.g., 'active,trialing').

customer_id

string

Filter subscriptions by a specific customer ID.

customer_did

string

Filter subscriptions by a specific customer DID.

metadata.{key}

string

Filter by custom metadata fields.

order

string | string[]

Sort order (e.g., 'created_at:asc').

activeFirst

boolean

If true, active and trialing subscriptions are listed first.

page

number

The page number for pagination. Defaults to 1.

pageSize

number

The number of items per page. Defaults to 20.

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

query

string

The search query string.

page

number

The page number for pagination. Defaults to 1.

pageSize

number

The number of items per page. Defaults to 20.

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

id

string

The identifier of the subscription to cancel.

data

object

An object containing cancellation details. See below.

data Object Properties

Name

Type

Description

at

string

When to cancel the subscription. Options: 'now', 'current_period_end', 'custom'. Defaults to 'current_period_end'.

time

number | string

Required if at is 'custom'. A Unix timestamp for the custom cancellation time.

refund

string

Specifies if a refund should be issued. Options: 'none', 'proration', 'last'. Defaults to 'none'.

feedback

string

Customer feedback for the cancellation.

comment

string

Internal comment about the cancellation.

reason

string

The reason for cancellation (e.g., 'cancellation_requested', 'payment_failed').

staking

string

For stake-based subscriptions, how to handle the stake. Options: 'none', 'proration', 'slash'.

slashReason

string

Required if staking is 'slash'. The reason for slashing the stake.

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

id

string

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

id

string

The identifier of the subscription to pause.

data

object

An object containing pause details. See below.

data Object Properties

Name

Type

Description

type

string

Specifies when the subscription should resume. Use 'custom' to set a specific resume time.

resumesAt

number | string

Required if type is 'custom'. A Unix timestamp for when the subscription should resume.

behavior

string

Determines the behavior of invoices created while paused. Can be 'keep_as_draft', 'void', or 'mark_uncollectible'. Defaults to 'keep_as_draft'.

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

id

string

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

id

string

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

id

string

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

id

string

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.