JavaScriptNode.jsSaaS / FaaSStripe

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

例えば「無料プランは1ユーザー1つだけしか契約できない」とかしたいですよね。 そういう時、Stripeではsubscriptions.listのAPIを利用して特定のプランをSubscribeしているか否かを見ることがで […]

広告ここから
広告ここまで

例えば「無料プランは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にすると良さそうです。知らんけど。

ブックマークや限定記事(予定)など

WP Kyotoサポーター募集中

WordPressやフロントエンドアプリのホスティング、Algolia・AWSなどのサービス利用料を支援する「WP Kyotoサポーター」を募集しています。
月額または年額の有料プランを契約すると、ブックマーク機能などのサポーター限定機能がご利用いただけます。

14日間のトライアルも用意しておりますので、「このサイトよく見るな」という方はぜひご検討ください。

広告ここから
広告ここまで

Related Category posts