Stripe Subscriptions module API explorer

/api/user/subscriptions/create-refund (POST)

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

await global.api.user.subscriptions.CreateRefund.post(req)

Returns object

{
  "refundid": "re_3LEOcjHHqepMFuCX1edhJpif",
  "object": "refund",
  "stripeObject": {
    "id": "re_3LEOcjHHqepMFuCX1edhJpif",
    "object": "refund",
    "amount": 1,
    "balance_transaction": "txn_3LEOcjHHqepMFuCX1zEpFeGU",
    "charge": "ch_3LEOcjHHqepMFuCX1qCeBEef",
    "created": 1656123690,
    "currency": "usd",
    "metadata": {},
    "payment_intent": "pi_3LEOcjHHqepMFuCX1BYNuNYC",
    "reason": "requested_by_customer",
    "receipt_number": null,
    "source_transfer_reversal": null,
    "status": "succeeded",
    "transfer_reversal": null
  },
  "accountid": "acct_aa8d4c189fa899aa",
  "subscriptionid": "sub_1LEOcjHHqepMFuCXHI82CtRt",
  "customerid": "cus_LwHAjPuyMGy4km",
  "invoiceid": "in_1LEOcjHHqepMFuCXDNRfWLsx",
  "productid": null,
  "paymentmethodid": null,
  "appid": "tests_1656123668",
  "createdAt": "2022-06-25T02:21:30.585Z",
  "updatedAt": "2022-06-25T02:21:30.585Z"
}

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-charge ineligible querystring charge is refunded
ineligible querystring charge is out of refund period
invalid-chargeid missing querystring chargeid
invalid querystring chargeid

NodeJS source (view on github)

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

module.exports = {
  post: async (req) => {
    if (!req.query || !req.query.chargeid) {
      throw new Error('invalid-chargeid')
    }
    const charge = await global.api.user.subscriptions.Charge.get(req)
    if (!charge.stripeObject.amount || !charge.stripeObject.paid || charge.stripeObject.refunded || !global.subscriptionRefundPeriod ||
      charge.created <= Math.floor(new Date().getTime() / 1000) - global.subscriptionRefundPeriod) {
      throw new Error('invalid-charge')
    }
    req.query.invoiceid = charge.invoiceid
    const invoice = await global.api.user.subscriptions.Invoice.get(req)
    const refundInfo = {
      charge: req.query.chargeid,
      amount: charge.stripeObject.paid - (charge.stripeObject.amount_refunded || 0),
      reason: 'requested_by_customer'
    }
    req.query.subscriptionid = invoice.subscriptionid
    const subscription = await global.api.user.subscriptions.Subscription.get(req)
    if (subscription.stripeObject.status === 'active') {
      const subscriptionNow = await stripeCache.execute('subscriptions', 'del', subscription.subscriptionid, { prorate: false }, req.stripeKey)
      await subscriptions.Storage.Subscription.update({
        stripeObject: subscriptionNow
      }, {
        where: {
          subscriptionid: subscription.subscriptionid,
          appid: req.appid || global.appid
        }
      })
    }
    try {
      const refund = await stripeCache.execute('refunds', 'create', refundInfo, req.stripeKey)
      req.query.refundid = refund.id
      await subscriptions.Storage.Refund.create({
        appid: req.appid || global.appid,
        refundid: refund.id,
        accountid: req.account.accountid,
        subscriptionid: subscription.subscriptionid,
        customerid: invoice.customerid,
        invoiceid: invoice.invoiceid,
        productid: invoice.productid,
        paymentmethodid: invoice.paymentmethodid,
        stripeObject: refund
      })
      const chargeNow = await stripeCache.retrieve(req.query.chargeid, 'charges', req.stripeKey)
      await subscriptions.Storage.Charge.update({
        stripeObject: chargeNow
      }, {
        where: {
          chargeid: req.query.chargeid,
          appid: req.appid || global.appid
        }
      })
      return global.api.user.subscriptions.Refund.get(req)
    } catch (error) {
      if (error.message === 'invalid-amount') {
        throw new Error('invalid-charge')
      }
    }
  }
}

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/create-refund', function () {
  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 user = await TestHelper.createUser()
    // missing and invalid id
    const req = TestHelper.createRequest('/api/user/subscriptions/create-refund')
    req.account = user.account
    req.session = user.session
    try {
      await req.post()
    } catch (error) {
      cachedResponses.missing = error.message
    }
    const req2 = TestHelper.createRequest('/api/user/subscriptions/create-refund?chargeid=invalid')
    req2.account = user.account
    req2.session = user.session
    try {
      await req2.post()
    } catch (error) {
      cachedResponses.invalid = error.message
    }
    // invalid charge
    const user2 = await TestStripeAccounts.createUserWithPaidSubscription(administrator.price)
    await TestHelper.createRefund(administrator, user2.charge.chargeid)
    const req3 = TestHelper.createRequest(`/api/user/subscriptions/create-refund?chargeid=${user2.charge.chargeid}`)
    req3.account = user2.account
    req3.session = user2.session
    req3.body = {
      amount: '1000'
    }
    try {
      await req3.post()
    } catch (error) {
      cachedResponses.invalidCharge = error.message
    }
    global.subscriptionRefundPeriod = 0
    await TestStripeAccounts.createUserWithPaidSubscription(administrator.price, user2)
    const req4 = TestHelper.createRequest(`/api/user/subscriptions/create-refund?chargeid=${user2.charge.chargeid}`)
    req4.account = user2.account
    req4.session = user2.session
    try {
      await req4.post()
    } catch (error) {
      cachedResponses.invalidCharge2 = error.message
    }
    global.subscriptionRefundPeriod = 7 * 24 * 60 * 60
    // invalid account
    const req5 = TestHelper.createRequest(`/api/user/subscriptions/create-refund?chargeid=${user2.charge.chargeid}`)
    req5.account = user.account
    req5.session = user.session
    try {
      await req5.post()
    } catch (error) {
      cachedResponses.invalidAccount = error.message
    }
    // returns
    const req6 = TestHelper.createRequest(`/api/user/subscriptions/create-refund?chargeid=${user2.charge.chargeid}`)
    req6.account = user2.account
    req6.session = user2.session
    req6.filename = __filename
    req6.saveResponse = true
    cachedResponses.returns = await req6.post()
    // env
    global.subscriptionRefundPeriod = 0
    await TestStripeAccounts.createUserWithPaidSubscription(administrator.price, user2)
    const req7 = TestHelper.createRequest(`/api/user/subscriptions/create-refund?chargeid=${user2.charge.chargeid}`)
    req7.account = user2.account
    req7.session = user2.session
    req7.filename = __filename
    req7.saveResponse = true
    try {
      await req7.post()
    } catch (error) {
      cachedResponses.envError = error.message
    }
    global.subscriptionRefundPeriod = 7 * 24 * 60 * 60
    cachedResponses.envSuccess = await req7.post()
    cachedResponses.finished = true
  }

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

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

    describe('invalid-charge', () => {
      it('ineligible querystring charge is refunded', async function () {
        await bundledData(this.test.currentRetry())
        const errorMessage = cachedResponses.invalidCharge
        assert.strictEqual(errorMessage, 'invalid-charge')
      })

      it('ineligible querystring charge is out of refund period', async function () {
        await bundledData(this.test.currentRetry())
        const errorMessage = cachedResponses.invalidCharge2
        assert.strictEqual(errorMessage, 'invalid-charge')
      })
    })

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

  describe('returns', () => {
    it('object', async () => {
      const refund = cachedResponses.returns
      assert.strictEqual(refund.object, 'refund')
    })
  })

  describe('configuration', () => {
    it('environment SUBSCRIPTION_REFUND_PERIOD', async () => {
      const refundError = cachedResponses.envError
      assert.strictEqual(refundError, 'invalid-charge')
      const refundSuccess = cachedResponses.envSuccess
      assert.strictEqual(refundSuccess.object, 'refund')
    })
  })
})