Stripe Subscriptions module API explorer

/api/user/subscriptions/set-subscription-coupon (PATCH)

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

await global.api.user.subscriptions.SetSubscriptionCoupon.patch(req)

Returns object

{
  "subscriptionid": "sub_1LEOlsHHqepMFuCXcfN6Dase",
  "object": "subscription",
  "stripeObject": {
    "id": "sub_1LEOlsHHqepMFuCXcfN6Dase",
    "object": "subscription",
    "application": null,
    "application_fee_percent": null,
    "automatic_tax": {
      "enabled": false
    },
    "billing_cycle_anchor": 1656124252,
    "billing_thresholds": null,
    "cancel_at": null,
    "cancel_at_period_end": false,
    "canceled_at": null,
    "collection_method": "charge_automatically",
    "created": 1656124252,
    "current_period_end": 1658716252,
    "current_period_start": 1656124252,
    "customer": "cus_LwHKrqp056k3Cf",
    "days_until_due": null,
    "default_payment_method": "pm_1LEOlZHHqepMFuCXfKul45gB",
    "default_source": null,
    "default_tax_rates": [],
    "description": null,
    "discount": {
      "id": "di_1LEOlyHHqepMFuCXeu5auuiG",
      "object": "discount",
      "checkout_session": null,
      "coupon": {
        "id": "COUPON51",
        "object": "coupon",
        "amount_off": 50,
        "created": 1656124231,
        "currency": "usd",
        "duration": "repeating",
        "duration_in_months": 4,
        "livemode": false,
        "max_redemptions": null,
        "metadata": {},
        "name": "coupon name",
        "percent_off": null,
        "redeem_by": null,
        "times_redeemed": 2,
        "valid": true
      },
      "customer": "cus_LwHKrqp056k3Cf",
      "end": 1666665058,
      "invoice": null,
      "invoice_item": null,
      "promotion_code": null,
      "start": 1656124258,
      "subscription": "sub_1LEOlsHHqepMFuCXcfN6Dase"
    },
    "ended_at": null,
    "items": {
      "object": "list",
      "data": [
        {
          "id": "si_LwHKQbAdbzuLTj",
          "object": "subscription_item",
          "billing_thresholds": null,
          "created": 1656124253,
          "metadata": {},
          "plan": {
            "id": "price_1LEOlXHHqepMFuCXGGahT7et",
            "object": "plan",
            "active": true,
            "aggregate_usage": null,
            "amount": 1000,
            "amount_decimal": "1000",
            "billing_scheme": "per_unit",
            "created": 1656124231,
            "currency": "usd",
            "interval": "month",
            "interval_count": 1,
            "livemode": false,
            "metadata": {},
            "nickname": null,
            "product": "prod_LwHKqHdbuvCBzp",
            "tiers_mode": null,
            "transform_usage": null,
            "trial_period_days": null,
            "usage_type": "licensed"
          },
          "price": {
            "id": "price_1LEOlXHHqepMFuCXGGahT7et",
            "object": "price",
            "active": true,
            "billing_scheme": "per_unit",
            "created": 1656124231,
            "currency": "usd",
            "custom_unit_amount": null,
            "livemode": false,
            "lookup_key": null,
            "metadata": {},
            "nickname": null,
            "product": "prod_LwHKqHdbuvCBzp",
            "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_1LEOlsHHqepMFuCXcfN6Dase",
          "tax_rates": []
        }
      ],
      "has_more": false,
      "total_count": 1,
      "url": "/v1/subscription_items?subscription=sub_1LEOlsHHqepMFuCXcfN6Dase"
    },
    "latest_invoice": "in_1LEOlsHHqepMFuCXqjo3GxMg",
    "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": {
      "id": "price_1LEOlXHHqepMFuCXGGahT7et",
      "object": "plan",
      "active": true,
      "aggregate_usage": null,
      "amount": 1000,
      "amount_decimal": "1000",
      "billing_scheme": "per_unit",
      "created": 1656124231,
      "currency": "usd",
      "interval": "month",
      "interval_count": 1,
      "livemode": false,
      "metadata": {},
      "nickname": null,
      "product": "prod_LwHKqHdbuvCBzp",
      "tiers_mode": null,
      "transform_usage": null,
      "trial_period_days": null,
      "usage_type": "licensed"
    },
    "quantity": 1,
    "schedule": null,
    "start_date": 1656124252,
    "status": "active",
    "test_clock": null,
    "transfer_data": null,
    "trial_end": null,
    "trial_start": null
  },
  "customerid": "cus_LwHKrqp056k3Cf",
  "accountid": "acct_b24bec19fd750258",
  "paymentmethodid": null,
  "productid": null,
  "priceids": [
    "price_1LEOlXHHqepMFuCXGGahT7et"
  ],
  "couponid": "COUPON51",
  "appid": "tests_1656124230",
  "createdAt": "2022-06-25T02:30:55.164Z",
  "updatedAt": "2022-06-25T02:30:59.274Z"
}

Exceptions

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

Exception Circumstances
invalid-account ineligible accessing account
invalid-coupon invalid posted coupon is other currency
invalid-couponid missing posted couponid
invalid posted couponid
invalid-subscription invalid querystring subscription has coupon
invalid querystring subscription is canceling
invalid-subscriptionid missing querystring subscriptionid
invalid querystring subscriptionid

NodeJS source (view on github)

const dashboard = require('@layeredapps/dashboard')
const subscriptions = require('../../../../../index.js')
const stripeCache = require('../../../../stripe-cache.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 ((subscription.stripeObject.status !== 'active' && subscription.stripeObject.status !== 'trialing') || subscription.stripeObject.cancel_at_period_end) {
      throw new Error('invalid-subscription')
    }
    if (!req.body || !req.body.couponid) {
      throw new Error('invalid-couponid')
    }
    if (subscription.stripeObject.discount) {
      throw new Error('invalid-subscription')
    }
    req.query.couponid = req.body.couponid
    const coupon = await global.api.user.subscriptions.Coupon.get(req)
    if (!coupon) {
      throw new Error('invalid-couponid')
    }
    const subscriptionInfo = {
      coupon: req.body.couponid
    }
    let subscriptionNow
    try {
      subscriptionNow = await stripeCache.execute('subscriptions', 'update', req.query.subscriptionid, subscriptionInfo, req.stripeKey)
    } catch (error) {
      if (error.message === 'invalid-currency') {
        throw new Error('invalid-coupon')
      }
      throw error
    }
    await subscriptions.Storage.Subscription.update({
      stripeObject: subscriptionNow,
      couponid: req.body.couponid
    }, {
      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/set-subscription-coupon', 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 coupon1 = await TestHelper.createCoupon(administrator, {
      active: 'true'
    })
    const coupon2 = await TestHelper.createCoupon(administrator, {
      active: 'true'
    })
    const currencyCoupon = await TestHelper.createCoupon(administrator, {
      active: 'true',
      amount_off: '2500',
      currency: 'jpy'
    })
    const user = await TestStripeAccounts.createUserWithPaidSubscription(administrator.price)
    // missing and invalid id
    let req = TestHelper.createRequest('/api/user/subscriptions/set-subscription-coupon')
    req.account = user.account
    req.session = user.session
    req.body = {
      couponid: coupon1.couponid
    }
    try {
      await req.patch()
    } catch (error) {
      cachedResponses.missing = error.message
    }
    req = TestHelper.createRequest('/api/user/subscriptions/set-subscription-coupon?subscriptionid=invalid')
    req.account = user.account
    req.session = user.session
    req.body = {
      couponid: coupon1.couponid
    }
    try {
      await req.patch()
    } catch (error) {
      cachedResponses.invalid = error.message
    }
    // invalid subscription
    await TestHelper.createSubscriptionDiscount(administrator, user.subscription, coupon1)
    req = TestHelper.createRequest(`/api/user/subscriptions/set-subscription-coupon?subscriptionid=${user.subscription.subscriptionid}`)
    req.account = user.account
    req.session = user.session
    req.body = {
      couponid: coupon2.couponid
    }
    try {
      await req.patch()
    } catch (error) {
      cachedResponses.invalidSubscription = error.message
    }
    await TestStripeAccounts.createUserWithPaidSubscription(administrator.price, user)
    await TestHelper.cancelSubscription(user)
    req = TestHelper.createRequest(`/api/user/subscriptions/set-subscription-coupon?subscriptionid=${user.subscription.subscriptionid}`)
    req.account = user.account
    req.session = user.session
    req.body = {
      couponid: coupon1.couponid
    }
    try {
      await req.patch()
    } catch (error) {
      cachedResponses.invalidSubscription2 = error.message
    }
    // invalid account
    await TestStripeAccounts.createUserWithPaidSubscription(administrator.price, user)
    const user2 = await TestHelper.createUser()
    req = TestHelper.createRequest(`/api/user/subscriptions/set-subscription-coupon?subscriptionid=${user.subscription.subscriptionid}`)
    req.account = user2.account
    req.session = user2.session
    req.body = {
      couponid: coupon1.couponid
    }
    try {
      await req.patch()
    } catch (error) {
      cachedResponses.invalidAccount = error.message
    }
    // invalid and missing coupon
    req = TestHelper.createRequest(`/api/user/subscriptions/set-subscription-coupon?subscriptionid=${user.subscription.subscriptionid}`)
    req.account = user.account
    req.session = user.session
    req.body = {
      couponid: ''
    }
    try {
      await req.patch()
    } catch (error) {
      cachedResponses.missingCoupon = error.message
    }
    req = TestHelper.createRequest(`/api/user/subscriptions/set-subscription-coupon?subscriptionid=${user.subscription.subscriptionid}`)
    req.account = user.account
    req.session = user.session
    req.body = {
      couponid: 'invalid'
    }
    try {
      await req.patch()
    } catch (error) {
      cachedResponses.invalidCoupon = error.message
    }
    // invalid coupon
    req = TestHelper.createRequest(`/api/user/subscriptions/set-subscription-coupon?subscriptionid=${user.subscription.subscriptionid}`)
    req.account = user.account
    req.session = user.session
    req.body = {
      couponid: currencyCoupon.couponid
    }
    try {
      await req.patch()
    } catch (error) {
      cachedResponses.currencyCoupon = error.message
    }
    // returns
    req = TestHelper.createRequest(`/api/user/subscriptions/set-subscription-coupon?subscriptionid=${user.subscription.subscriptionid}`)
    req.account = user.account
    req.session = user.session
    req.body = {
      couponid: coupon1.couponid
    }
    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-subscription', () => {
      it('invalid querystring subscription has coupon', async function () {
        await bundledData(this.test.currentRetry())
        const errorMessage = cachedResponses.invalidSubscription
        assert.strictEqual(errorMessage, 'invalid-subscription')
      })

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

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

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

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

    describe('invalid-coupon', () => {
      it('invalid posted coupon is other currency', async function () {
        await bundledData(this.test.currentRetry())
        const errorMessage = cachedResponses.currencyCoupon
        assert.strictEqual(errorMessage, 'invalid-coupon')
      })
    })
  })

  describe('returns', () => {
    it('object', async () => {
      const subscriptionNow = cachedResponses.returns
      assert.strictEqual(subscriptionNow.stripeObject.discount.coupon.object, 'coupon')
    })
  })
})