Stripe Subscriptions module API explorer

/api/user/subscriptions/set-payment-method-detached (PATCH)

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

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

Returns object

{
  "paymentmethodid": "pm_1LEOkeHHqepMFuCXTKdPubGc",
  "object": "paymentmethod",
  "accountid": "acct_93566ec5a13fb3a4",
  "customerid": "cus_LwHJvZKIruVVXj",
  "stripeObject": {
    "id": "pm_1LEOkeHHqepMFuCXTKdPubGc",
    "object": "payment_method",
    "billing_details": {
      "address": {
        "city": "New York",
        "country": "US",
        "line1": "285 Fulton St",
        "line2": "Apt 893",
        "postal_code": "10007",
        "state": "NY"
      },
      "email": null,
      "name": "Santiago Gusikowski",
      "phone": null
    },
    "card": {
      "brand": "visa",
      "checks": {
        "address_line1_check": "pass",
        "address_postal_code_check": "pass",
        "cvc_check": "pass"
      },
      "country": "US",
      "exp_month": 1,
      "exp_year": 2023,
      "fingerprint": "IRcdqfBUCskmPkNV",
      "funding": "credit",
      "generated_from": null,
      "last4": "1111",
      "networks": {
        "available": [
          "visa"
        ],
        "preferred": null
      },
      "three_d_secure_usage": {
        "supported": true
      },
      "wallet": null
    },
    "created": 1656124176,
    "customer": null,
    "livemode": false,
    "metadata": {},
    "type": "card"
  },
  "appid": "tests_1656124175",
  "createdAt": "2022-06-25T02:29:37.561Z",
  "updatedAt": "2022-06-25T02:29:41.844Z"
}

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-paymentmethod invalid querystring payment method is default
invalid-paymentmethodid missing querystring paymentmethodid
invalid querystring paymentmethodid

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.paymentmethodid) {
      throw new Error('invalid-paymentmethodid')
    }
    const paymentMethod = await global.api.user.subscriptions.PaymentMethod.get(req)
    if (!paymentMethod) {
      throw new Error('invalid-paymentmethodid')
    }
    if (!paymentMethod.customerid) {
      throw new Error('invalid-paymentmethod')
    }
    req.query.customerid = paymentMethod.customerid
    const customer = await global.api.user.subscriptions.Customer.get(req)
    if (customer.stripeObject.invoice_settings && customer.stripeObject.invoice_settings.default_payment_method === req.query.paymentmethodid) {
      throw new Error('invalid-paymentmethod')
    }
    const paymentMethodNow = await stripeCache.execute('paymentMethods', 'detach', req.query.paymentmethodid, req.stripeKey)
    await subscriptions.Storage.PaymentMethod.update({
      stripeObject: paymentMethodNow
    }, {
      where: {
        paymentmethodid: req.query.paymentmethodid,
        appid: req.appid || global.appid
      }
    })
    await dashboard.StorageCache.remove(req.query.paymentmethodid)
    return global.api.user.subscriptions.PaymentMethod.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-payment-method-detached', 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 user = await TestStripeAccounts.createUserWithPaymentMethod()
    const user2 = await TestHelper.createUser()
    // invalid account
    const req = TestHelper.createRequest(`/api/user/subscriptions/set-payment-method-detached?paymentmethodid=${user.paymentMethod.paymentmethodid}`)
    req.account = user2.account
    req.session = user2.session
    try {
      await req.patch()
    } catch (error) {
      cachedResponses.invalidAccount = error.message
    }
    // invalid payment method is default
    const req2 = TestHelper.createRequest(`/api/user/subscriptions/set-payment-method-detached?paymentmethodid=${user.paymentMethod.paymentmethodid}`)
    req2.account = user.account
    req2.session = user.session
    try {
      await req2.patch()
    } catch (error) {
      cachedResponses.invalidPaymentMethod = error.message
    }
    // response
    const paymentMethod1 = user.paymentMethod
    await TestHelper.createPaymentMethod(user, {
      cvc: '111',
      number: '4111111111111111',
      exp_month: '1',
      exp_year: (new Date().getFullYear() + 1).toString().substring(2),
      name: user.profile.fullName,
      line1: '285 Fulton St',
      line2: 'Apt 893',
      city: 'New York',
      state: 'NY',
      postal_code: '10007',
      country: 'US',
      default: 'true'
    })
    const req3 = TestHelper.createRequest(`/api/user/subscriptions/set-payment-method-detached?paymentmethodid=${paymentMethod1.paymentmethodid}`)
    req3.account = user.account
    req3.session = user.session
    req3.filename = __filename
    req3.saveResponse = true
    cachedResponses.returns = await req3.patch()
    cachedResponses.finished = true
  }

  describe('exceptions', () => {
    describe('invalid-paymentmethodid', () => {
      it('missing querystring paymentmethodid', async function () {
        await bundledData(this.test.currentRetry())
        const user = await TestHelper.createUser()
        const req = TestHelper.createRequest('/api/user/subscriptions/set-payment-method-detached')
        req.account = user.account
        req.session = user.session
        let errorMessage
        try {
          await req.patch()
        } catch (error) {
          errorMessage = error.message
        }
        assert.strictEqual(errorMessage, 'invalid-paymentmethodid')
      })

      it('invalid querystring paymentmethodid', async function () {
        await bundledData(this.test.currentRetry())
        const user = await TestHelper.createUser()
        const req = TestHelper.createRequest('/api/user/subscriptions/set-payment-method-detached?paymentmethodid=invalid')
        req.account = user.account
        req.session = user.session
        let errorMessage
        try {
          await req.patch()
        } catch (error) {
          errorMessage = error.message
        }
        assert.strictEqual(errorMessage, 'invalid-paymentmethodid')
      })
    })

    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-paymentmethod', () => {
      it('invalid querystring payment method is default', async function () {
        await bundledData(this.test.currentRetry())
        const errorMessage = cachedResponses.invalidPaymentMethod
        assert.strictEqual(errorMessage, 'invalid-paymentmethod')
      })
    })
  })

  describe('returns', () => {
    it('object', async () => {
      const paymentMethodNow = cachedResponses.returns
      assert.strictEqual(paymentMethodNow.stripeObject.customer, null)
    })
  })
})