Я решил использовать начало и конец периода, а также текущее время 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
слушателя веб-крюка:
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