Skip to main content

Blog

Stripeでカスタマーが特定のPlanをSubscribeしているか否かを判定する (Node.js)

Posted over 2 years ago
この記事をシェア:

例えば「無料プランは1ユーザー1つだけしか契約できない」とかしたいですよね。

そういう時、Stripeではsubscriptions.listのAPIを利用して特定のプランをSubscribeしているか否かを見ることができます。

コード

const hasSubscribed = async (customerId, plan) => {
    const result = await Stripe.subscriptions.list({
      customer: customerId,
      plan,
      status: 'active'
    })
    return result.data.length > 0
}

TypeScriptだとこうなります。

const hasSubscribed = async (customerId: string, plan: string): Promise<boolean> => {
    const result = await Stripe.subscriptions.list({
      customer: customerId,
      plan,
      status: 'active'
    })
    return result.data.length > 0
}

使い方

このように使いましょう。

const planId = 'free'
const customerId = 'cus_XXXXX'

if (await hasSubscribed(customerId, planId)) {
  throw new Error('The customer subscribed the plan already!')
}
...

「1回Subscribeしたら金輪際契約させねぇ」という強い意志

ちょっとどういうケースでこれが発生するか思いつかなかったのですが、理論上可能なので書いておきます。

subscriptions.listの引数statusallにすると、キャンセル済のモノも検索してくれるらしいです。

Passing in a value of all will return subscriptions of all statuses.

https://stripe.com/docs/api/subscriptions/list

なので「一度だけしかSubscribeさせたくない!」という場合はstatusactiveではなくallにすると良さそうです。知らんけど。

Tools to Support Stripe Development

We provide helpful tools to extend the Stripe Dashboard and streamline development and testing.

View All Tools

Support This Project

If you find this content helpful, consider supporting the project through GitHub Sponsors. Your support helps maintain and improve these tools.