计算带钢中的按比例分配百分比

2024-06-06 06:00:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个SaaS应用程序,每个月都有青铜、银、金计划的账单。每个计划都有一定数量的信贷分配——比如说,10、25、50

使用条带默认分配行为,如果客户在月中升级计划,他们将立即升级。他们将支付%的账单差额

我更改了计划的webhook设置:

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

我期待着计算多少学分,我应该给用户。因此,如果他们在本月中途从铜牌转换为黄金,他们应该获得(1 - .5) * 50 = 25信贷分配。如果他们将一周改为一个月,他们应该获得(1 - .25) * 50 = ~37学分

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


Tags: event应用程序data数量客户ifwebhook计划
1条回答
网友
1楼 · 发布于 2024-06-06 06:00:37

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

下面是一个示例笔记本答案,以开始时间、结束时间和更新时间计算计划剩余时间的百分比

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.updatedwebhook侦听器内:

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

相关问题 更多 >