【问题标题】:Calculating Proration Percentage in Stripe在 Stripe 中计算按比例分配的百分比
【发布时间】:2020-02-18 22:31:16
【问题描述】:

我有一个 SaaS 应用程序,其中包含按月计费的青铜、白银和黄金计划。每个计划都有一定数量的信用分配——比如说,10、25、50。

使用 Stripe 默认的按比例分配行为,如果客户在月中升级他们的计划,他们将立即升级。他们将通过next month 支付账单差额。

我有一个用于更改计划的 webhook 设置:

if event['data']['object'] == 'customer.subscription.updated':

我正在计算我应该给用户多少积分。因此,如果他们在本月中途从青铜级切换到黄金级,他们应该获得(1 - .5) * 50 = 25 信用分配。如果他们切换到一个月的一周,他们应该得到(1 - .25) * 50 = ~37 积分。

stripe 在他们的 webhook 中发送的变量是否为“.5”或“.25”,让我知道要完成计划的百分比?

【问题讨论】:

    标签: python stripe-payments


    【解决方案1】:

    我决定使用周期开始和结束以及当前的 webhook 时间来计算剩余百分比。我很惊讶这不是 Stripe 默认变量。

    这是一个示例笔记本答案 - 使用开始时间、结束时间和更新时间来计算计划剩余时间的百分比。

    current_period_end =  1574401972 # Plan ends 
    current_period_start = 1571723572 # Plan starts
    plan_updated = 1571769818 # Plan changed
    
    period_length = current_period_end - current_period_start
    period_used = plan_updated - current_period_start
    print(period_used / 3600 / 24, 'days of', period_length / 3600 / 24, 'days')
    period_remaining_pct = 1 - (period_used / period_length)
    print(int(period_remaining_pct * 100), '% remaining')
    

    在 Stripe 中,customer.subscription.updated webhook 监听器内部:

    import time
    
    if event['type'] == 'customer.subscription.updated':
    
            # Get time params
            session = event['data']['object']
            current_period_end = session['current_period_end']
            current_period_start = session['current_period_start']
            plan_updated = time.time()
    
            # Calculate remaining time on plan
            period_length = current_period_end - current_period_start
            period_used = plan_updated - current_period_start
            print(period_used / 3600 / 24, 'days of', period_length / 3600 / 24, 'days')
            period_remaining_pct = 1 - (period_used / period_length)
            print(int(period_remaining_pct * 100), '% remaining')
    

    从那里开始,它取决于您的应用,但在本例中为credits_to_give = period_remaining_pct * 50

    【讨论】:

    • P.S.在生产中未经测试——如果有人有更好的答案——或者这可能会引发错误——请编辑。
    猜你喜欢
    • 2019-02-22
    • 1970-01-01
    • 1970-01-01
    • 2014-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-01
    • 2021-01-10
    相关资源
    最近更新 更多