Stripe Subscriptions module API explorer

/api/user/subscriptions/add-subscription-item (GET)

Account information like email addresses is generated with faker-js it is not real user information.

await global.api.user.subscriptions.AddSubscriptionItem.get(req)

Returns object

{
  "subscriptionid": "sub_1LEOZdHHqepMFuCXabBMZTZZ",
  "object": "subscription",
  "stripeObject": {
    "id": "sub_1LEOZdHHqepMFuCXabBMZTZZ",
    "object": "subscription",
    "application": null,
    "application_fee_percent": null,
    "automatic_tax": {
      "enabled": false
    },
    "billing_cycle_anchor": 1656123493,
    "billing_thresholds": null,
    "cancel_at": null,
    "cancel_at_period_end": false,
    "canceled_at": null,
    "collection_method": "charge_automatically",
    "created": 1656123493,
    "current_period_end": 1658715493,
    "current_period_start": 1656123493,
    "customer": "cus_LwH7TKkNTdkRNP",
    "days_until_due": null,
    "default_payment_method": "pm_1LEOZaHHqepMFuCXybtwx517",
    "default_source": null,
    "default_tax_rates": [],
    "description": null,
    "discount": null,
    "ended_at": null,
    "items": {
      "object": "list",
      "data": [
        {
          "id": "si_LwH74WJAgR8XKm",
          "object": "subscription_item",
          "billing_thresholds": null,
          "created": 1656123494,
          "metadata": {},
          "plan": {
            "id": "price_1LEOZYHHqepMFuCXpqPuH0Dj",
            "object": "plan",
            "active": true,
            "aggregate_usage": null,
            "amount": 1000,
            "amount_decimal": "1000",
            "billing_scheme": "per_unit",
            "created": 1656123488,
            "currency": "usd",
            "interval": "month",
            "interval_count": 1,
            "livemode": false,
            "metadata": {},
            "nickname": null,
            "product": "prod_LwH7fY5WoVkWNP",
            "tiers_mode": null,
            "transform_usage": null,
            "trial_period_days": null,
            "usage_type": "licensed"
          },
          "price": {
            "id": "price_1LEOZYHHqepMFuCXpqPuH0Dj",
            "object": "price",
            "active": true,
            "billing_scheme": "per_unit",
            "created": 1656123488,
            "currency": "usd",
            "custom_unit_amount": null,
            "livemode": false,
            "lookup_key": null,
            "metadata": {},
            "nickname": null,
            "product": "prod_LwH7fY5WoVkWNP",
            "recurring": {
              "aggregate_usage": null,
              "interval": "month",
              "interval_count": 1,
              "trial_period_days": null,
              "usage_type": "licensed"
            },
            "tax_behavior": "inclusive",
            "tiers_mode": null,
            "transform_quantity": null,
            "type": "recurring",
            "unit_amount": 1000,
            "unit_amount_decimal": "1000"
          },
          "quantity": 1,
          "subscription": "sub_1LEOZdHHqepMFuCXabBMZTZZ",
          "tax_rates": []
        },
        {
          "id": "si_LwH7kK3cyzA2XY",
          "object": "subscription_item",
          "billing_thresholds": null,
          "created": 1656123498,
          "metadata": {},
          "plan": {
            "id": "price_1LEOZZHHqepMFuCXook85tk1",
            "object": "plan",
            "active": true,
            "aggregate_usage": null,
            "amount": 0,
            "amount_decimal": "0",
            "billing_scheme": "per_unit",
            "created": 1656123489,
            "currency": "usd",
            "interval": "month",
            "interval_count": 1,
            "livemode": false,
            "metadata": {},
            "nickname": null,
            "product": "prod_LwH7fY5WoVkWNP",
            "tiers_mode": null,
            "transform_usage": null,
            "trial_period_days": null,
            "usage_type": "licensed"
          },
          "price": {
            "id": "price_1LEOZZHHqepMFuCXook85tk1",
            "object": "price",
            "active": true,
            "billing_scheme": "per_unit",
            "created": 1656123489,
            "currency": "usd",
            "custom_unit_amount": null,
            "livemode": false,
            "lookup_key": null,
            "metadata": {},
            "nickname": null,
            "product": "prod_LwH7fY5WoVkWNP",
            "recurring": {
              "aggregate_usage": null,
              "interval": "month",
              "interval_count": 1,
              "trial_period_days": null,
              "usage_type": "licensed"
            },
            "tax_behavior": "inclusive",
            "tiers_mode": null,
            "transform_quantity": null,
            "type": "recurring",
            "unit_amount": 0,
            "unit_amount_decimal": "0"
          },
          "quantity": 2,
          "subscription": "sub_1LEOZdHHqepMFuCXabBMZTZZ",
          "tax_rates": []
        }
      ],
      "has_more": false,
      "total_count": 2,
      "url": "/v1/subscription_items?subscription=sub_1LEOZdHHqepMFuCXabBMZTZZ"
    },
    "latest_invoice": "in_1LEOZdHHqepMFuCXbSmiNl9G",
    "livemode": false,
    "metadata": {},
    "next_pending_invoice_item_invoice": null,
    "pause_collection": null,
    "payment_settings": {
      "payment_method_options": null,
      "payment_method_types": null,
      "save_default_payment_method": "off"
    },
    "pending_invoice_item_interval": null,
    "pending_setup_intent": null,
    "pending_update": null,
    "plan": null,
    "quantity": null,
    "schedule": null,
    "start_date": 1656123493,
    "status": "active",
    "test_clock": null,
    "transfer_data": null,
    "trial_end": null,
    "trial_start": null
  },
  "customerid": "cus_LwH7TKkNTdkRNP",
  "accountid": "acct_b4416f18694d537b",
  "paymentmethodid": null,
  "productid": null,
  "priceids": [
    "price_1LEOZYHHqepMFuCXpqPuH0Dj"
  ],
  "couponid": null,
  "appid": "tests_1656123487",
  "createdAt": "2022-06-25T02:18:16.097Z",
  "updatedAt": "2022-06-25T02:18:18.468Z"
}

Exceptions

These exceptions are thrown (NodeJS) or returned as JSON (HTTP) if you provide incorrect data or do not meet the requirements:

Exception Circumstances
duplicate-price invalid price is already on subscription
invalid-account ineligible accessing account
invalid-price invalid price is not active
invalid-priceid missing posted priceid
invalid posted priceid
invalid-quantity invalid posted quantity
invalid posted quantity is negative
invalid posted quantity is zero
invalid-subscriptionid missing querystring subscriptionid
invalid querystring subscriptionid

NodeJS source (view on github)

const dashboard = require('@layeredapps/dashboard')
const stripeCache = require('../../../../stripe-cache.js')
const subscriptions = require('../../../../../index.js')

module.exports = {
  patch: async (req) => {
    if (!req.query || !req.query.subscriptionid) {
      throw new Error('invalid-subscriptionid')
    }
    const subscription = await global.api.user.subscriptions.Subscription.get(req)
    if (!subscription) {
      throw new Error('invalid-subscriptionid')
    }
    if (!req.body || !req.body.quantity) {
      throw new Error('invalid-quantity')
    }
    if (!req.body.priceid) {
      throw new Error('invalid-priceid')
    }
    req.query.priceid = req.body.priceid
    const price = await global.api.user.subscriptions.ActivePrice.get(req)
    if (!price) {
      throw new Error('invalid-priceid')
    }
    if (!price.stripeObject.active) {
      throw new Error('invalid-price')
    }
    try {
      const quantity = parseInt(req.body.quantity, 10)
      if (quantity < 1 || quantity.toString() !== req.body.quantity) {
        throw new Error('invalid-quantity')
      }
    } catch (error) {
      throw new Error('invalid-quantity')
    }
    for (const item of subscription.stripeObject.items.data) {
      if (item.price.id === req.body.priceid) {
        throw new Error('duplicate-price')
      }
    }
    const updateInfo = {
      subscription: req.query.subscriptionid,
      price: price.priceid,
      quantity: req.body.quantity
    }
    await stripeCache.execute('subscriptionItems', 'create', updateInfo, req.stripeKey)
    const subscriptionNow = await stripeCache.execute('subscriptions', 'retrieve', req.query.subscriptionid, req.stripeKey)
    if (!subscriptionNow) {
      throw new Error('unknown-error')
    }
    await subscriptions.Storage.Subscription.update({
      stripeObject: subscriptionNow
    }, {
      where: {
        subscriptionid: req.query.subscriptionid,
        appid: req.appid || global.appid
      }
    })
    await dashboard.StorageCache.remove(req.query.subscriptionid)
    return global.api.user.subscriptions.Subscription.get(req)
  }
}

Test source (view on github)

/* eslint-env mocha */
const assert = require('assert')
const TestHelper = require('../../../../../test-helper.js')
const TestStripeAccounts = require('../../../../../test-stripe-accounts.js')
const DashboardTestHelper = require('@layeredapps/dashboard/test-helper.js')

describe('/api/user/subscriptions/add-subscription-item', function () {
  before(TestHelper.disableMetrics)
  after(TestHelper.enableMetrics)
  let cachedResponses
  async function bundledData (retryNumber) {
    if (retryNumber > 0) {
      cachedResponses = {}
    }
    if (cachedResponses && cachedResponses.finished) {
      return
    }
    cachedResponses = {}
    await TestHelper.setupBefore()
    await DashboardTestHelper.setupBeforeEach()
    await TestHelper.setupBeforeEach()
    const administrator = await TestStripeAccounts.createOwnerWithPrice()
    const price1 = administrator.price
    const inactivePrice = await TestHelper.createPrice(administrator, {
      productid: administrator.product.productid,
      active: 'false',
      unit_amount: 2000,
      currency: 'usd',
      tax_behavior: 'inclusive',
      recurring_interval: 'month',
      recurring_interval_count: '1',
      recurring_usage_type: 'licensed'
    })
    const price2 = await TestHelper.createPrice(administrator)
    const user = await TestStripeAccounts.createUserWithPaidSubscription(price1)
    const user2 = await TestHelper.createUser()
    // missing and invalid subscription id
    let req = TestHelper.createRequest('/api/user/subscriptions/add-subscription-item')
    req.account = user.account
    req.session = user.session
    req.body = {
      quantity: '10',
      priceid: price1.priceid
    }
    try {
      await req.patch()
    } catch (error) {
      cachedResponses.missing = error.message
    }
    req = TestHelper.createRequest('/api/user/subscriptions/add-subscription-item?subscriptionid=invalid')
    req.account = user.account
    req.session = user.session
    req.body = {
      quantity: '10',
      priceid: price1.priceid
    }
    try {
      await req.patch()
    } catch (error) {
      cachedResponses.invalid = error.message
    }
    // invalid account
    req = TestHelper.createRequest(`/api/user/subscriptions/add-subscription-item?subscriptionid=${user.subscription.subscriptionid}`)
    req.account = user2.account
    req.session = user2.session
    req.body = {
      quantity: '1',
      priceid: price1.priceid
    }
    try {
      await req.patch()
    } catch (error) {
      cachedResponses.account = error.message
    }
    // invalid price id
    req = TestHelper.createRequest(`/api/user/subscriptions/add-subscription-item?subscriptionid=${user.subscription.subscriptionid}`)
    req.account = user.account
    req.session = user.session
    req.body = {
      quantity: '7',
      priceid: ''
    }
    try {
      await req.patch()
    } catch (error) {
      cachedResponses.missingPriceID = error.message
    }
    req = TestHelper.createRequest(`/api/user/subscriptions/add-subscription-item?subscriptionid=${user.subscription.subscriptionid}`)
    req.account = user.account
    req.session = user.session
    req.body = {
      quantity: '7',
      priceid: 'invalid'
    }
    try {
      await req.patch()
    } catch (error) {
      cachedResponses.invalidPriceID = error.message
    }
    // invalid price
    req = TestHelper.createRequest(`/api/user/subscriptions/add-subscription-item?subscriptionid=${user.subscription.subscriptionid}`)
    req.account = user.account
    req.session = user.session
    req.body = {
      quantity: '7',
      priceid: inactivePrice.priceid
    }
    try {
      await req.patch()
    } catch (error) {
      cachedResponses.invalidPriceNotActive = error.message
    }
    // invalid quantity
    req = TestHelper.createRequest(`/api/user/subscriptions/add-subscription-item?subscriptionid=${user.subscription.subscriptionid}`)
    req.account = user.account
    req.session = user.session
    req.body = {
      quantity: 'letters',
      priceid: price1.priceid
    }
    try {
      await req.patch()
    } catch (error) {
      cachedResponses.invalidQuantity = error.message
    }
    req = TestHelper.createRequest(`/api/user/subscriptions/add-subscription-item?subscriptionid=${user.subscription.subscriptionid}`)
    req.account = user.account
    req.session = user.session
    req.body = {
      quantity: '-1',
      priceid: price1.priceid
    }
    try {
      await req.patch()
    } catch (error) {
      cachedResponses.negativeQuantity = error.message
    }
    req = TestHelper.createRequest(`/api/user/subscriptions/add-subscription-item?subscriptionid=${user.subscription.subscriptionid}`)
    req.account = user.account
    req.session = user.session
    req.body = {
      quantity: '0',
      priceid: price1.priceid
    }
    try {
      await req.patch()
    } catch (error) {
      cachedResponses.zeroQuantity = error.message
    }
    // returns
    req = TestHelper.createRequest(`/api/user/subscriptions/add-subscription-item?subscriptionid=${user.subscription.subscriptionid}`)
    req.account = user.account
    req.session = user.session
    req.body = {
      quantity: '2',
      priceid: price1.priceid
    }
    try {
      await req.patch()
    } catch (error) {
      cachedResponses.invalidDuplicatePrice = error.message
    }
    req = TestHelper.createRequest(`/api/user/subscriptions/add-subscription-item?subscriptionid=${user.subscription.subscriptionid}`)
    req.account = user.account
    req.session = user.session
    req.body = {
      quantity: '2',
      priceid: price2.priceid
    }
    req.filename = __filename
    req.saveResponse = true
    cachedResponses.returns = await req.patch()
    cachedResponses.finished = true
  }

  describe('exceptions', () => {
    describe('invalid-subscriptionid', () => {
      it('missing querystring subscriptionid', async function () {
        await bundledData(this.test.currentRetry())
        const errorMessage = cachedResponses.missing
        assert.strictEqual(errorMessage, 'invalid-subscriptionid')
      })

      it('invalid querystring subscriptionid', async function () {
        await bundledData(this.test.currentRetry())
        const errorMessage = cachedResponses.invalid
        assert.strictEqual(errorMessage, 'invalid-subscriptionid')
      })
    })

    describe('invalid-account', () => {
      it('ineligible accessing account', async function () {
        await bundledData(this.test.currentRetry())
        const errorMessage = cachedResponses.account
        assert.strictEqual(errorMessage, 'invalid-account')
      })
    })

    describe('invalid-quantity', () => {
      it('invalid posted quantity', async function () {
        await bundledData(this.test.currentRetry())
        const errorMessage = cachedResponses.invalidQuantity
        assert.strictEqual(errorMessage, 'invalid-quantity')
      })

      it('invalid posted quantity is negative', async function () {
        await bundledData(this.test.currentRetry())
        const errorMessage = cachedResponses.negativeQuantity
        assert.strictEqual(errorMessage, 'invalid-quantity')
      })

      it('invalid posted quantity is zero', async function () {
        await bundledData(this.test.currentRetry())
        const errorMessage = cachedResponses.zeroQuantity
        assert.strictEqual(errorMessage, 'invalid-quantity')
      })
    })

    describe('invalid-priceid', () => {
      it('missing posted priceid', async function () {
        await bundledData(this.test.currentRetry())
        const errorMessage = cachedResponses.missingPriceID
        assert.strictEqual(errorMessage, 'invalid-priceid')
      })

      it('invalid posted priceid', async function () {
        await bundledData(this.test.currentRetry())
        const errorMessage = cachedResponses.invalidPriceID
        assert.strictEqual(errorMessage, 'invalid-priceid')
      })
    })

    describe('invalid-price', () => {
      it('invalid price is not active', async function () {
        await bundledData(this.test.currentRetry())
        const errorMessage = cachedResponses.invalidPriceNotActive
        assert.strictEqual(errorMessage, 'invalid-price')
      })
    })

    describe('duplicate-price', () => {
      it('invalid price is already on subscription', async function () {
        await bundledData(this.test.currentRetry())
        const errorMessage = cachedResponses.invalidDuplicatePrice
        assert.strictEqual(errorMessage, 'duplicate-price')
      })
    })
  })

  describe('returns', () => {
    it('object', async () => {
      const subscriptionNow = cachedResponses.returns
      assert.strictEqual(subscriptionNow.stripeObject.items.data[1].quantity, 2)
    })
  })
})