我决定使用周期开始和结束以及当前的 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