Blog
StripeのSubscription(定額課金)で、プラン変更時の差額計算をNode.jsでやる
Outdated Information
This article contains outdated information. Please note that some content may no longer be accurate or applicable.
Stripeを使って定額課金なサービスを作っているときに地味に便利なのが、この「差額計算」機能です。
差額ってどういうこと?
定額課金につきものなのが、「期間途中でのプラン変更」です。
たとえば1/1に新しく月額3,000円のプランを契約したとします。
月額課金ですので1/1に3,000円の決済が走り、2/1になると再び3,000円の決済がStripe側で実施されるという流れです。
では、期間途中の1/15に「2,000円または4,000円のプランに変更したい」となった場合の請求はどうなるでしょうか?
自前実装であればめんどくさいので「反映を翌月請求日からにする」「日割りにせず、翌月から新料金で請求する」のような対応になるかもしれません。
ですがStripeはこのあたりがよくできていて、日割り計算も勝手によしなにしてくれます。
そしてそれに関する記事がちょうど最近公開されていましたので、これを読んでもらうと良いかなと思います。
決済サービスStripeの備忘録 〜Proration(日割り)編〜 – Qiita
Stripeで日割りにした場合、基本的には差額を翌月の請求に乗せる or 差し引くという形になると考えてもらえればです。
「差額の計算」を事前にやる
で、Stripeのいいなと思うところは、「翌月の支払いがいくらになるか?」という計算もAPIからできるということです。
そしてちゃんと公式にドキュメントとサンプルコードがあります。
Upgrading and Downgrading Plans
変更後の翌月請求額を確認するコード(Node.js)
const stripe = require("stripe")("sk_test_XXXXX")
const moment = require('moment')
const prorationDate = Math.floor(Date.now() / 1000)
const customerId = 'cus_XXXX'
const currentSubscriptionId = 'sub_XXXXXX'
const nextPlanId = 'new-plan-id'
var subscription = stripe.subscriptions.retrieve("sub_49ty4767H20z6a");
var item_id = subscription.items.data[0].id;
stripe.subscriptions.retrieve(currentSubscriptionId)
.then(data => {
const itemId = data.items.data[0].id
const params = {
subscription: currentSubscriptionId,
subscription_items: [{
id: itemId,
plan: nextPlanId
}],
subscription_proration_date: prorationDate
}
return stripe.invoices.retrieveUpcoming(customerId, params)
})
.then(invoice => {
let cost = 0
invoice.lines.data.map(item => {
cost += item.amount
console.log(item.description || item.plan.id)
console.log(item.amount / 100)
console.log(moment.unix(item.period.start).toString())
console.log(moment.unix(item.period.end).toString())
console.log('')
})
console.log(cost / 100)
})
.catch(err => console.log(err))
これをコマンドラインなどから実行すると、以下のようにプランを変更した場合の明細と合計金額がでてきます。
$ node test.js
Unused time on Currently subscription plan after 15 Dec 2017
-82.96
Sat Dec 16 2017 00:12:48 GMT+0900
Sun Jan 07 2018 20:50:41 GMT+0900
Remaining time on Next subscription plan after 15 Dec 2017
110.61
Sat Dec 16 2017 00:12:48 GMT+0900
Sun Jan 07 2018 20:50:41 GMT+0900
example-plan-monthly
200
Sun Jan 07 2018 20:50:41 GMT+0900
Wed Feb 07 2018 20:50:41 GMT+0900
227.65
さいごに
個人的にこの痒いところに手が届く感じがStrieのすごくいいなと思うところです。
しかも機能面だけでなくちゃんとドキュメント(サンプルコードつき)で用意されているというのがすごく親切で好感を持てます。
ということで、SaaSなどで定額課金を検討されてる方はぜひStripeを。
そしてハマったところや面白い機能があればぜひブログにしてくださいお願いします。m(_ _)m
Tools to Support Stripe Development
We provide helpful tools to extend the Stripe Dashboard and streamline development and testing.
View All ToolsSupport This Project
If you find this content helpful, consider supporting the project through GitHub Sponsors. Your support helps maintain and improve these tools.
