Skip to main content

Subscriptions

Subscriptions are used to manage recurring payment plans for customers. The Subscriptions API allows you to create, retrieve, update, cancel, and manage the lifecycle of these recurring billing arrangements.

For managing the individual items within a subscription, see the Subscription Items API.

Retrieve a Subscription

Fetches the details of an existing subscription by its unique identifier.

Parameters

NameTypeDescription
idstringThe ID of the subscription to retrieve.

Returns

Returns a subscription object if a valid ID was provided. The TSubscriptionExpanded object includes the following properties:

NameTypeDescription
idstringUnique identifier for the subscription.
statusstringThe status of the subscription (e.g., active, trialing, past_due, canceled).
customer_idstringThe ID of the customer associated with this subscription.
currency_idstringThe ID of the currency used for this subscription.
current_period_startnumberThe start of the current billing period as a Unix timestamp.
current_period_endnumberThe end of the current billing period as a Unix timestamp.
itemsTSubscriptionItem[]An array of subscription items associated with this subscription.
customerTCustomerThe expanded customer object.
paymentCurrencyTPaymentCurrencyThe expanded payment currency object.
paymentMethodTPaymentMethodThe expanded payment method object.
metadataobjectA set of key-value pairs that you can attach to an object.

Example

Retrieving a subscription

javascript
async function getSubscription(subscriptionId) {
  try {
    const subscription = await payment.subscriptions.retrieve(subscriptionId);
    console.log('Subscription retrieved:', subscription);
    return subscription;
  } catch (error) {
    console.error('Error retrieving subscription:', error.message);
  }
}

// Example usage:
getProductDetails('sub_xxxxxxxxxxxxxx');

Example Response

json
{
  "id": "sub_xxxxxxxxxxxxxx",
  "status": "active",
  "customer_id": "cus_xxxxxxxxxxxxxx",
  "currency_id": "curr_xxxxxxxxxxxxxx",
  "current_period_start": 1672531200,
  "current_period_end": 1675209600,
  "items": [
    {
      "id": "si_xxxxxxxxxxxxxx",
      "price_id": "price_xxxxxxxxxxxxxx",
      "quantity": 1
    }
  ],
  "customer": { /* ... customer details ... */ },
  "paymentCurrency": { /* ... currency details ... */ },
  "paymentMethod": { /* ... method details ... */ },
  "metadata": {}
}

Update a Subscription

Updates an existing subscription by setting the values of the parameters passed.

Parameters

NameTypeDescription
idstringThe ID of the subscription to update.
dataobjectAn object containing the fields to update. See details below.

Data Object Properties

NameTypeDescription
descriptionstringAn optional description for the subscription.
metadataobjectA set of key-value pairs to store with the subscription.
payment_behaviorstringDetermines how to handle payments. Can be allow_incomplete, error_if_incomplete, or pending_if_incomplete.
proration_behaviorstringDetermines how to handle prorations. Can be always_invoice, create_prorations, or none.
trial_endnumber | stringUnix timestamp indicating the end of the trial period. Can also be 'now'.
itemsSubscriptionUpdateItem[]An array of items to update on the subscription. See details below.

SubscriptionUpdateItem Object Properties

NameTypeDescription
idstringThe ID of an existing subscription item to update or delete.
price_idstringThe ID of the price for a new subscription item.
quantitynumberThe quantity for the subscription item.
deletedbooleanSet to true to delete this subscription item.
clear_usagebooleanFor metered billing, indicates whether to clear usage on deletion.

Returns

Returns the updated subscription object.

Example

Updating a subscription's metadata

javascript
async function updateSubscriptionMetadata(subscriptionId) {
  try {
    const subscription = await payment.subscriptions.update(subscriptionId, {
      metadata: {
        order_id: 'order_12345'
      }
    });
    console.log('Subscription updated:', subscription);
    return subscription;
  } catch (error) {
    console.error('Error updating subscription:', error.message);
  }
}

// Example usage:
updateSubscriptionMetadata('sub_xxxxxxxxxxxxxx');

Example Response

json
{
  "id": "sub_xxxxxxxxxxxxxx",
  "status": "active",
  "metadata": {
    "order_id": "order_12345"
  }
  // ... other subscription properties
}

List Subscriptions

Returns a paginated list of subscriptions. You can filter the list based on various criteria.

Parameters

NameTypeDescription
statusstringFilter subscriptions by status (e.g., 'active', 'trialing'). Comma-separated for multiple values.
customer_idstringFilter subscriptions by a specific customer ID.
customer_didstringFilter subscriptions by a specific customer DID.
metadata.{key}stringFilter by custom metadata fields.
orderstring | string[]Sort order (e.g., 'created_at:DESC').
activeFirstbooleanIf true, active and trialing subscriptions are listed first.
pagenumberThe page number for pagination (default: 1).
pageSizenumberThe number of items per page (default: 20).

Returns

Returns a paginated list of subscription objects.

NameTypeDescription
listTSubscriptionExpanded[]An array of subscription objects for the current page.
countnumberThe total number of subscriptions matching the query.
pagingobjectAn object containing pagination details (page, pageSize).

Example

Listing all active subscriptions

javascript
async function listActiveSubscriptions() {
  try {
    const response = await payment.subscriptions.list({
      status: 'active',
      pageSize: 10
    });
    console.log(`Found ${response.count} active subscriptions.`);
    console.log('First page:', response.list);
    return response;
  } catch (error) {
    console.error('Error listing subscriptions:', error.message);
  }
}

// Example usage:
listActiveSubscriptions();

Example Response

json
{
  "count": 50,
  "list": [
    {
      "id": "sub_xxxxxxxxxxxxxx",
      "status": "active"
      // ... other subscription properties
    }
    // ... more subscriptions
  ],
  "paging": {
    "page": 1,
    "pageSize": 10
  }
}

Search Subscriptions

Performs a search for subscriptions based on a query string.

Parameters

NameTypeDescription
querystringThe search string to match against subscription fields.
pagenumberThe page number for pagination (default: 1).
pageSizenumberThe number of items per page (default: 20).

Returns

Returns a paginated list of subscription objects matching the search query.

Example

Searching for a subscription

javascript
async function searchForSubscription(query) {
  try {
    const response = await payment.subscriptions.search({ query });
    console.log(`Search results for "${query}":`, response.list);
    return response;
  } catch (error) {
    console.error('Error searching subscriptions:', error.message);
  }
}

// Example usage:
searchForSubscription('some_customer_did');

Cancel a Subscription

Cancels a customer's subscription. The subscription can be canceled immediately or at the end of the current billing period.

Parameters

NameTypeDescription
idstringThe ID of the subscription to cancel.
bodyobjectAn object containing cancellation details.

Body Object Properties

NameTypeDescription
atstringWhen to cancel. Can be 'now', 'current_period_end', or 'custom'. Default is 'current_period_end'.
timenumber | stringRequired if at is 'custom'. A future Unix timestamp for cancellation.
refundstringSpecifies if a refund should be issued. Can be 'none', 'proration', or 'last'.
feedbackstringCustomer feedback for the cancellation.
commentstringInternal comment about the cancellation.
reasonstringThe reason for cancellation (e.g., 'cancellation_requested').

Returns

Returns the updated subscription object with cancellation details.

Example

Canceling a subscription at period end

javascript
async function cancelSubscription(subscriptionId) {
  try {
    const subscription = await payment.subscriptions.cancel(subscriptionId, {
      at: 'current_period_end',
      reason: 'cancellation_requested'
    });
    console.log('Subscription scheduled for cancellation:', subscription);
    return subscription;
  } catch (error) {
    console.error('Error canceling subscription:', error.message);
  }
}

// Example usage:
cancelSubscription('sub_xxxxxxxxxxxxxx');

Recover a Subscription

Reactivates a subscription that has been scheduled for cancellation but has not yet been canceled.

Parameters

NameTypeDescription
idstringThe ID of the subscription to recover.

Returns

Returns the updated, active subscription object.

Example

Recovering a canceled subscription

javascript
async function recoverSubscription(subscriptionId) {
  try {
    const subscription = await payment.subscriptions.recover(subscriptionId);
    console.log('Subscription recovered:', subscription);
    return subscription;
  } catch (error) {
    console.error('Error recovering subscription:', error.message);
  }
}

// Example usage:
recoverSubscription('sub_xxxxxxxxxxxxxx');

Pause a Subscription

Pauses payment collection for a subscription.

Parameters

NameTypeDescription
idstringThe ID of the subscription to pause.
bodyobjectAn object containing pause details.

Body Object Properties

NameTypeDescription
behaviorstringThe behavior of invoices created while paused. Can be 'keep_as_draft', 'mark_uncollectible', or 'void'.
resumes_atnumberA Unix timestamp for when the subscription should automatically resume.

Returns

Returns the updated subscription object with a paused status.

Example

Pausing a subscription

javascript
async function pauseSubscription(subscriptionId) {
  try {
    const subscription = await payment.subscriptions.pause(subscriptionId, {
      behavior: 'keep_as_draft'
    });
    console.log('Subscription paused:', subscription);
    return subscription;
  } catch (error) {
    console.error('Error pausing subscription:', error.message);
  }
}

// Example usage:
pauseSubscription('sub_xxxxxxxxxxxxxx');

Resume a Subscription

Resumes payment collection for a paused subscription.

Parameters

NameTypeDescription
idstringThe ID of the subscription to resume.

Returns

Returns the updated, active subscription object.

Example

Resuming a subscription

javascript
async function resumeSubscription(subscriptionId) {
  try {
    const subscription = await payment.subscriptions.resume(subscriptionId);
    console.log('Subscription resumed:', subscription);
    return subscription;
  } catch (error) {
    console.error('Error resuming subscription:', error.message);
  }
}

// Example usage:
resumeSubscription('sub_xxxxxxxxxxxxxx');

Delete a Subscription

Permanently deletes a subscription and all its related data. This action is irreversible and should only be used in non-production environments.

Parameters

NameTypeDescription
idstringThe ID of the subscription to delete.

Returns

Returns the deleted subscription object.

Example

Deleting a subscription

javascript
async function deleteSubscription(subscriptionId) {
  try {
    const subscription = await payment.subscriptions.del(subscriptionId);
    console.log('Subscription deleted:', subscription);
    return subscription;
  } catch (error) {
    console.error('Error deleting subscription:', error.message);
  }
}

// Example usage:
deleteSubscription('sub_xxxxxxxxxxxxxx');

List Overdue Invoices

Retrieves a list of overdue (uncollectible) invoices for a specific subscription, along with a summary of the amounts due.

Parameters

NameTypeDescription
idstringThe ID of the subscription.

Returns

Returns an object containing the subscription, a list of overdue invoices, and a summary of the total amounts owed per currency.

NameTypeDescription
subscriptionTSubscriptionThe subscription object.
invoicesTInvoice[]An array of overdue invoice objects.
summaryobjectAn object summarizing the total overdue amount for each currency.

Example

Fetching overdue invoices

javascript
async function getOverdueInvoices(subscriptionId) {
  try {
    const result = await payment.subscriptions.overdueInvoices(subscriptionId);
    console.log('Overdue Invoices Summary:', result.summary);
    console.log('Invoices:', result.invoices);
    return result;
  } catch (error) {
    console.error('Error fetching overdue invoices:', error.message);
  }
}

// Example usage:
getOverdueInvoices('sub_xxxxxxxxxxxxxx');

Return Stake

Initiates the process of returning staked funds associated with a canceled subscription that used an ArcBlock payment method.

Parameters

NameTypeDescription
idstringThe ID of the canceled subscription.

Returns

Returns an object indicating the success of scheduling the stake return job.

NameTypeDescription
successbooleantrue if the stake return job was successfully scheduled.
subscriptionIdstringThe ID of the subscription for which the stake is being returned.

Example

Returning a stake

javascript
async function returnSubscriptionStake(subscriptionId) {
  try {
    const result = await payment.subscriptions.returnStake(subscriptionId);
    console.log('Stake return initiated:', result);
    return result;
  } catch (error) {
    console.error('Error returning stake:', error.message);
  }
}

// Example usage:
returnSubscriptionStake('sub_xxxxxxxxxxxxxx');