Stripe Subscriptions module API explorer

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

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

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

Returns object

{
  "customerid": "cus_LwHIrtkOANQzIN",
  "object": "customer",
  "accountid": "acct_c1bb8be7e403c723",
  "couponid": "COUPON49",
  "stripeObject": {
    "id": "cus_LwHIrtkOANQzIN",
    "object": "customer",
    "address": null,
    "balance": 0,
    "created": 1656124124,
    "currency": null,
    "default_source": null,
    "delinquent": false,
    "description": "InstaPayment (work)",
    "discount": {
      "id": "di_1LEOjoHHqepMFuCXmc0rhyO0",
      "object": "discount",
      "checkout_session": null,
      "coupon": {
        "id": "COUPON49",
        "object": "coupon",
        "amount_off": null,
        "created": 1656124122,
        "currency": null,
        "duration": "once",
        "duration_in_months": null,
        "livemode": false,
        "max_redemptions": 129,
        "metadata": {},
        "name": "coupon name",
        "percent_off": 48,
        "redeem_by": null,
        "times_redeemed": 2,
        "valid": true
      },
      "customer": "cus_LwHIrtkOANQzIN",
      "end": null,
      "invoice": null,
      "invoice_item": null,
      "promotion_code": null,
      "start": 1656124124,
      "subscription": null
    },
    "email": "Candace_Kemmer91@gmail.com",
    "invoice_prefix": "D58ECA84",
    "invoice_settings": {
      "custom_fields": null,
      "default_payment_method": null,
      "footer": null,
      "rendering_options": null
    },
    "livemode": false,
    "metadata": {},
    "name": null,
    "next_invoice_sequence": 1,
    "phone": null,
    "preferred_locales": [],
    "shipping": null,
    "tax_exempt": "none",
    "test_clock": null
  },
  "appid": "tests_1656124121",
  "createdAt": "2022-06-25T02:28:44.372Z",
  "updatedAt": "2022-06-25T02:28:44.802Z"
}

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-couponid missing posted couponid
invalid posted couponid
invalid-customer invalid querystring customer has coupon
invalid-customerid missing querystring customerid
invalid querystring customerid

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.customerid) {
      throw new Error('invalid-customerid')
    }
    if (!req.body || !req.body.couponid) {
      throw new Error('invalid-couponid')
    }
    const customer = await global.api.user.subscriptions.Customer.get(req)
    if (!customer) {
      throw new Error('invalid-customer')
    }
    if (customer.stripeObject.discount) {
      throw new Error('invalid-customer')
    }
    req.query.couponid = req.body.couponid
    const coupon = await global.api.user.subscriptions.Coupon.get(req)
    if (!coupon) {
      throw new Error('invalid-couponid')
    }
    const customerInfo = {
      coupon: req.body.couponid
    }
    const customerNow = await stripeCache.execute('customers', 'update', req.query.customerid, customerInfo, req.stripeKey)
    await subscriptions.Storage.Customer.update({
      stripeObject: customerNow,
      couponid: req.body.couponid
    }, {
      where: {
        customerid: req.query.customerid,
        appid: req.appid || global.appid
      }
    })
    await dashboard.StorageCache.remove(req.query.customerid)
    return global.api.user.subscriptions.Customer.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-customer-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 TestHelper.createOwner()
    const coupon1 = await TestHelper.createCoupon(administrator, {
      active: 'true'
    })
    const coupon2 = await TestHelper.createCoupon(administrator, {
      active: 'true'
    })
    const user = await TestStripeAccounts.createUserWithoutPaymentMethod()
    // missing and invalid id
    let req = TestHelper.createRequest('/api/user/subscriptions/set-customer-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-customer-coupon?customerid=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 customer
    await TestHelper.createCustomerDiscount(administrator, user.customer, coupon1)
    req = TestHelper.createRequest(`/api/user/subscriptions/set-customer-coupon?customerid=${user.customer.customerid}`)
    req.account = user.account
    req.session = user.session
    req.body = {
      couponid: coupon2.couponid
    }
    try {
      await req.patch()
    } catch (error) {
      cachedResponses.invalidCustomer = error.message
    }
    // invalid account
    const user2 = await TestStripeAccounts.createUserWithoutPaymentMethod()
    req = TestHelper.createRequest(`/api/user/subscriptions/set-customer-coupon?customerid=${user.customer.customerid}`)
    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-customer-coupon?customerid=${user2.customer.customerid}`)
    req.account = user2.account
    req.session = user2.session
    req.body = {
      couponid: ''
    }
    try {
      await req.patch()
    } catch (error) {
      cachedResponses.missingCoupon = error.message
    }
    req = TestHelper.createRequest(`/api/user/subscriptions/set-customer-coupon?customerid=${user2.customer.customerid}`)
    req.account = user2.account
    req.session = user2.session
    req.body = {
      couponid: 'invalid'
    }
    try {
      await req.patch()
    } catch (error) {
      cachedResponses.invalidCoupon = error.message
    }
    // returns
    req = TestHelper.createRequest(`/api/user/subscriptions/set-customer-coupon?customerid=${user2.customer.customerid}`)
    req.account = user2.account
    req.session = user2.session
    req.body = {
      couponid: coupon1.couponid
    }
    req.filename = __filename
    req.saveResponse = true
    cachedResponses.returns = await req.patch()
    cachedResponses.finished = true
  }

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

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

    describe('invalid-customer', () => {
      it('invalid querystring customer has coupon', async function () {
        await bundledData(this.test.currentRetry())
        const errorMessage = cachedResponses.invalidCustomer
        assert.strictEqual(errorMessage, 'invalid-customer')
      })
    })

    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('returns', () => {
    it('object', async () => {
      const customerNow = cachedResponses.returns
      assert.strictEqual(customerNow.stripeObject.discount.coupon.object, 'coupon')
    })
  })
})