2018-03-31 04:13:44 +02:00
|
|
|
import datetime
|
2018-12-12 19:41:03 +01:00
|
|
|
from decimal import Decimal
|
2018-01-30 21:03:59 +01:00
|
|
|
from functools import wraps
|
2018-01-30 20:49:25 +01:00
|
|
|
import logging
|
|
|
|
import os
|
2018-07-03 21:49:55 +02:00
|
|
|
from typing import Any, Callable, Dict, Optional, TypeVar, Tuple
|
2018-06-28 00:48:51 +02:00
|
|
|
import ujson
|
2018-01-30 20:49:25 +01:00
|
|
|
|
|
|
|
from django.conf import settings
|
2018-06-28 00:48:51 +02:00
|
|
|
from django.db import transaction
|
2018-01-30 21:03:59 +01:00
|
|
|
from django.utils.translation import ugettext as _
|
2018-08-14 03:33:31 +02:00
|
|
|
from django.utils.timezone import now as timezone_now
|
2018-07-13 17:34:39 +02:00
|
|
|
from django.core.signing import Signer
|
2018-01-30 20:49:25 +01:00
|
|
|
import stripe
|
|
|
|
|
2018-01-30 21:03:59 +01:00
|
|
|
from zerver.lib.exceptions import JsonableError
|
2018-01-30 20:49:25 +01:00
|
|
|
from zerver.lib.logging_util import log_to_file
|
2018-06-28 00:48:51 +02:00
|
|
|
from zerver.lib.timestamp import datetime_to_timestamp, timestamp_to_datetime
|
2018-07-13 17:34:39 +02:00
|
|
|
from zerver.lib.utils import generate_random_token
|
2018-08-09 21:38:22 +02:00
|
|
|
from zerver.lib.actions import do_change_plan_type
|
2018-06-28 00:48:51 +02:00
|
|
|
from zerver.models import Realm, UserProfile, RealmAuditLog
|
2018-12-12 23:23:15 +01:00
|
|
|
from corporate.models import Customer, CustomerPlan, Plan, Coupon
|
2018-01-30 20:49:25 +01:00
|
|
|
from zproject.settings import get_secret
|
|
|
|
|
|
|
|
STRIPE_PUBLISHABLE_KEY = get_secret('stripe_publishable_key')
|
2018-03-31 04:13:44 +02:00
|
|
|
stripe.api_key = get_secret('stripe_secret_key')
|
2018-01-30 20:49:25 +01:00
|
|
|
|
|
|
|
BILLING_LOG_PATH = os.path.join('/var/log/zulip'
|
|
|
|
if not settings.DEVELOPMENT
|
|
|
|
else settings.DEVELOPMENT_LOG_DIRECTORY,
|
|
|
|
'billing.log')
|
2018-09-25 12:33:30 +02:00
|
|
|
billing_logger = logging.getLogger('corporate.stripe')
|
2018-01-30 20:49:25 +01:00
|
|
|
log_to_file(billing_logger, BILLING_LOG_PATH)
|
|
|
|
log_to_file(logging.getLogger('stripe'), BILLING_LOG_PATH)
|
|
|
|
|
2018-01-30 21:03:59 +01:00
|
|
|
CallableT = TypeVar('CallableT', bound=Callable[..., Any])
|
|
|
|
|
2018-12-22 01:43:44 +01:00
|
|
|
MIN_INVOICED_LICENSES = 30
|
2018-09-08 00:49:54 +02:00
|
|
|
DEFAULT_INVOICE_DAYS_UNTIL_DUE = 30
|
|
|
|
|
2018-03-31 04:13:44 +02:00
|
|
|
def get_seat_count(realm: Realm) -> int:
|
|
|
|
return UserProfile.objects.filter(realm=realm, is_active=True, is_bot=False).count()
|
|
|
|
|
2018-07-13 17:34:39 +02:00
|
|
|
def sign_string(string: str) -> Tuple[str, str]:
|
|
|
|
salt = generate_random_token(64)
|
|
|
|
signer = Signer(salt=salt)
|
|
|
|
return signer.sign(string), salt
|
|
|
|
|
|
|
|
def unsign_string(signed_string: str, salt: str) -> str:
|
|
|
|
signer = Signer(salt=salt)
|
|
|
|
return signer.unsign(signed_string)
|
|
|
|
|
2018-07-27 17:47:03 +02:00
|
|
|
class BillingError(Exception):
|
2018-08-06 06:16:29 +02:00
|
|
|
# error messages
|
2018-08-11 01:23:42 +02:00
|
|
|
CONTACT_SUPPORT = _("Something went wrong. Please contact %s." % (settings.ZULIP_ADMINISTRATOR,))
|
2018-08-06 06:16:29 +02:00
|
|
|
TRY_RELOADING = _("Something went wrong. Please reload the page.")
|
|
|
|
|
|
|
|
# description is used only for tests
|
|
|
|
def __init__(self, description: str, message: str) -> None:
|
|
|
|
self.description = description
|
|
|
|
self.message = message
|
2018-07-27 17:47:03 +02:00
|
|
|
|
2018-08-06 23:07:26 +02:00
|
|
|
class StripeCardError(BillingError):
|
|
|
|
pass
|
|
|
|
|
|
|
|
class StripeConnectionError(BillingError):
|
|
|
|
pass
|
|
|
|
|
2018-01-30 21:03:59 +01:00
|
|
|
def catch_stripe_errors(func: CallableT) -> CallableT:
|
|
|
|
@wraps(func)
|
|
|
|
def wrapped(*args: Any, **kwargs: Any) -> Any:
|
2018-07-26 10:16:20 +02:00
|
|
|
if settings.DEVELOPMENT and not settings.TEST_SUITE: # nocoverage
|
|
|
|
if STRIPE_PUBLISHABLE_KEY is None:
|
2018-08-06 06:16:29 +02:00
|
|
|
raise BillingError('missing stripe config', "Missing Stripe config. "
|
|
|
|
"See https://zulip.readthedocs.io/en/latest/subsystems/billing.html.")
|
2018-07-26 10:16:20 +02:00
|
|
|
if not Plan.objects.exists():
|
2018-08-06 06:16:29 +02:00
|
|
|
raise BillingError('missing plans',
|
|
|
|
"Plan objects not created. Please run ./manage.py setup_stripe")
|
2018-01-30 21:03:59 +01:00
|
|
|
try:
|
|
|
|
return func(*args, **kwargs)
|
2018-08-06 23:07:26 +02:00
|
|
|
# See https://stripe.com/docs/api/python#error_handling, though
|
|
|
|
# https://stripe.com/docs/api/ruby#error_handling suggests there are additional fields, and
|
|
|
|
# https://stripe.com/docs/error-codes gives a more detailed set of error codes
|
2018-01-30 21:03:59 +01:00
|
|
|
except stripe.error.StripeError as e:
|
2018-08-06 23:07:26 +02:00
|
|
|
err = e.json_body.get('error', {})
|
|
|
|
billing_logger.error("Stripe error: %s %s %s %s" % (
|
|
|
|
e.http_status, err.get('type'), err.get('code'), err.get('param')))
|
2018-01-30 21:03:59 +01:00
|
|
|
if isinstance(e, stripe.error.CardError):
|
2018-08-06 23:07:26 +02:00
|
|
|
# TODO: Look into i18n for this
|
|
|
|
raise StripeCardError('card error', err.get('message'))
|
|
|
|
if isinstance(e, stripe.error.RateLimitError) or \
|
|
|
|
isinstance(e, stripe.error.APIConnectionError): # nocoverage TODO
|
|
|
|
raise StripeConnectionError(
|
|
|
|
'stripe connection error',
|
|
|
|
_("Something went wrong. Please wait a few seconds and try again."))
|
|
|
|
raise BillingError('other stripe error', BillingError.CONTACT_SUPPORT)
|
2018-01-30 21:03:59 +01:00
|
|
|
return wrapped # type: ignore # https://github.com/python/mypy/issues/1927
|
|
|
|
|
|
|
|
@catch_stripe_errors
|
2018-08-06 18:22:55 +02:00
|
|
|
def stripe_get_customer(stripe_customer_id: str) -> stripe.Customer:
|
2018-11-17 04:41:42 +01:00
|
|
|
return stripe.Customer.retrieve(stripe_customer_id, expand=["default_source"])
|
2018-03-31 04:13:44 +02:00
|
|
|
|
|
|
|
@catch_stripe_errors
|
2018-08-06 18:23:48 +02:00
|
|
|
def stripe_get_upcoming_invoice(stripe_customer_id: str) -> stripe.Invoice:
|
2018-11-17 04:41:42 +01:00
|
|
|
return stripe.Invoice.upcoming(customer=stripe_customer_id)
|
2018-01-30 20:49:25 +01:00
|
|
|
|
2018-11-07 06:25:11 +01:00
|
|
|
# This allows us to access /billing in tests without having to mock the
|
|
|
|
# whole invoice object
|
|
|
|
def upcoming_invoice_total(stripe_customer_id: str) -> int:
|
|
|
|
return stripe_get_upcoming_invoice(stripe_customer_id).total
|
|
|
|
|
2018-07-10 10:56:21 +02:00
|
|
|
# Return type should be Optional[stripe.Subscription], which throws a mypy error.
|
|
|
|
# Will fix once we add type stubs for the Stripe API.
|
|
|
|
def extract_current_subscription(stripe_customer: stripe.Customer) -> Any:
|
|
|
|
if not stripe_customer.subscriptions:
|
|
|
|
return None
|
2018-07-24 14:35:22 +02:00
|
|
|
for stripe_subscription in stripe_customer.subscriptions:
|
2018-07-10 10:56:21 +02:00
|
|
|
if stripe_subscription.status != "canceled":
|
|
|
|
return stripe_subscription
|
|
|
|
|
2018-11-16 17:08:09 +01:00
|
|
|
def estimate_customer_arr(stripe_customer: stripe.Customer) -> int: # nocoverage
|
|
|
|
stripe_subscription = extract_current_subscription(stripe_customer)
|
|
|
|
if stripe_subscription is None:
|
|
|
|
return 0
|
|
|
|
# This is an overestimate for those paying by invoice
|
|
|
|
estimated_arr = stripe_subscription.plan.amount * stripe_subscription.quantity / 100.
|
2018-11-19 08:04:14 +01:00
|
|
|
if stripe_subscription.plan.interval == 'month':
|
2018-11-16 17:08:09 +01:00
|
|
|
estimated_arr *= 12
|
2018-12-12 19:41:03 +01:00
|
|
|
discount = Customer.objects.get(stripe_customer_id=stripe_customer.id).default_discount
|
|
|
|
if discount is not None:
|
|
|
|
estimated_arr *= 1 - discount/100.
|
2018-11-16 17:08:09 +01:00
|
|
|
return int(estimated_arr)
|
|
|
|
|
2018-03-31 04:13:44 +02:00
|
|
|
@catch_stripe_errors
|
2018-12-12 19:41:03 +01:00
|
|
|
def do_create_customer(user: UserProfile, stripe_token: Optional[str]=None) -> stripe.Customer:
|
2018-03-31 04:13:44 +02:00
|
|
|
realm = user.realm
|
2018-08-23 06:44:00 +02:00
|
|
|
# We could do a better job of handling race conditions here, but if two
|
|
|
|
# people from a realm try to upgrade at exactly the same time, the main
|
|
|
|
# bad thing that will happen is that we will create an extra stripe
|
|
|
|
# customer that we can delete or ignore.
|
2018-03-31 04:13:44 +02:00
|
|
|
stripe_customer = stripe.Customer.create(
|
|
|
|
description="%s (%s)" % (realm.string_id, realm.name),
|
2018-08-08 13:17:10 +02:00
|
|
|
email=user.email,
|
2018-03-31 04:13:44 +02:00
|
|
|
metadata={'realm_id': realm.id, 'realm_str': realm.string_id},
|
2018-12-12 19:41:03 +01:00
|
|
|
source=stripe_token)
|
2018-06-28 00:48:51 +02:00
|
|
|
event_time = timestamp_to_datetime(stripe_customer.created)
|
2018-08-23 03:40:38 +02:00
|
|
|
with transaction.atomic():
|
|
|
|
RealmAuditLog.objects.create(
|
|
|
|
realm=user.realm, acting_user=user, event_type=RealmAuditLog.STRIPE_CUSTOMER_CREATED,
|
|
|
|
event_time=event_time)
|
2018-08-23 07:47:05 +02:00
|
|
|
if stripe_token is not None:
|
|
|
|
RealmAuditLog.objects.create(
|
2018-09-05 09:40:29 +02:00
|
|
|
realm=user.realm, acting_user=user, event_type=RealmAuditLog.STRIPE_CARD_CHANGED,
|
2018-08-23 07:47:05 +02:00
|
|
|
event_time=event_time)
|
2018-08-22 08:35:00 +02:00
|
|
|
Customer.objects.create(realm=realm, stripe_customer_id=stripe_customer.id)
|
2018-08-22 07:49:48 +02:00
|
|
|
user.is_billing_admin = True
|
|
|
|
user.save(update_fields=["is_billing_admin"])
|
2018-07-10 12:11:34 +02:00
|
|
|
return stripe_customer
|
2018-03-31 04:13:44 +02:00
|
|
|
|
2018-08-14 03:33:31 +02:00
|
|
|
@catch_stripe_errors
|
|
|
|
def do_replace_payment_source(user: UserProfile, stripe_token: str) -> stripe.Customer:
|
|
|
|
stripe_customer = stripe_get_customer(Customer.objects.get(realm=user.realm).stripe_customer_id)
|
|
|
|
stripe_customer.source = stripe_token
|
|
|
|
# Deletes existing card: https://stripe.com/docs/api#update_customer-source
|
|
|
|
# This can also have other side effects, e.g. it will try to pay certain past-due
|
|
|
|
# invoices: https://stripe.com/docs/api#update_customer
|
2018-10-18 19:56:17 +02:00
|
|
|
updated_stripe_customer = stripe.Customer.save(stripe_customer)
|
2018-08-14 03:33:31 +02:00
|
|
|
RealmAuditLog.objects.create(
|
2018-09-05 09:40:29 +02:00
|
|
|
realm=user.realm, acting_user=user, event_type=RealmAuditLog.STRIPE_CARD_CHANGED,
|
2018-08-14 03:33:31 +02:00
|
|
|
event_time=timezone_now())
|
|
|
|
return updated_stripe_customer
|
|
|
|
|
2018-03-31 04:13:44 +02:00
|
|
|
@catch_stripe_errors
|
2018-08-22 07:49:48 +02:00
|
|
|
def do_subscribe_customer_to_plan(user: UserProfile, stripe_customer: stripe.Customer, stripe_plan_id: str,
|
2018-09-08 00:49:54 +02:00
|
|
|
seat_count: int, tax_percent: float, charge_automatically: bool) -> None:
|
2018-11-28 00:20:58 +01:00
|
|
|
if extract_current_subscription(stripe_customer) is not None: # nocoverage
|
|
|
|
# Unlikely race condition from two people upgrading (clicking "Make payment")
|
|
|
|
# at exactly the same time. Doesn't fully resolve the race condition, but having
|
|
|
|
# a check here reduces the likelihood.
|
2018-07-10 10:56:21 +02:00
|
|
|
billing_logger.error("Stripe customer %s trying to subscribe to %s, "
|
|
|
|
"but has an active subscription" % (stripe_customer.id, stripe_plan_id))
|
2018-08-06 06:16:29 +02:00
|
|
|
raise BillingError('subscribing with existing subscription', BillingError.TRY_RELOADING)
|
2018-08-14 05:19:18 +02:00
|
|
|
customer = Customer.objects.get(stripe_customer_id=stripe_customer.id)
|
2018-09-08 00:49:54 +02:00
|
|
|
if charge_automatically:
|
|
|
|
billing_method = 'charge_automatically'
|
|
|
|
days_until_due = None
|
|
|
|
else:
|
|
|
|
billing_method = 'send_invoice'
|
|
|
|
days_until_due = DEFAULT_INVOICE_DAYS_UNTIL_DUE
|
2018-08-23 06:30:26 +02:00
|
|
|
# Note that there is a race condition here, where if two users upgrade at exactly the
|
|
|
|
# same time, they will have two subscriptions, and get charged twice. We could try to
|
|
|
|
# reduce the chance of it with a well-designed idempotency_key, but it's not easy since
|
|
|
|
# we also need to be careful not to block the customer from retrying if their
|
|
|
|
# subscription attempt fails (e.g. due to insufficient funds).
|
|
|
|
|
|
|
|
# Success here implies the stripe_customer was charged: https://stripe.com/docs/billing/lifecycle#active
|
|
|
|
# Otherwise we should expect it to throw a stripe.error.
|
2018-03-31 04:13:44 +02:00
|
|
|
stripe_subscription = stripe.Subscription.create(
|
2018-07-10 12:11:34 +02:00
|
|
|
customer=stripe_customer.id,
|
2018-09-08 00:49:54 +02:00
|
|
|
billing=billing_method,
|
|
|
|
days_until_due=days_until_due,
|
2018-03-31 04:13:44 +02:00
|
|
|
items=[{
|
|
|
|
'plan': stripe_plan_id,
|
|
|
|
'quantity': seat_count,
|
|
|
|
}],
|
|
|
|
prorate=True,
|
|
|
|
tax_percent=tax_percent)
|
2018-06-28 00:48:51 +02:00
|
|
|
with transaction.atomic():
|
2018-08-14 03:33:31 +02:00
|
|
|
customer.has_billing_relationship = True
|
|
|
|
customer.save(update_fields=['has_billing_relationship'])
|
2018-06-28 00:48:51 +02:00
|
|
|
customer.realm.has_seat_based_plan = True
|
|
|
|
customer.realm.save(update_fields=['has_seat_based_plan'])
|
|
|
|
RealmAuditLog.objects.create(
|
|
|
|
realm=customer.realm,
|
2018-08-22 07:49:48 +02:00
|
|
|
acting_user=user,
|
2018-08-11 00:48:10 +02:00
|
|
|
event_type=RealmAuditLog.STRIPE_PLAN_CHANGED,
|
2018-06-28 00:48:51 +02:00
|
|
|
event_time=timestamp_to_datetime(stripe_subscription.created),
|
2018-09-08 00:49:54 +02:00
|
|
|
extra_data=ujson.dumps({'plan': stripe_plan_id, 'quantity': seat_count,
|
|
|
|
'billing_method': billing_method}))
|
2018-06-28 00:48:51 +02:00
|
|
|
|
|
|
|
current_seat_count = get_seat_count(customer.realm)
|
|
|
|
if seat_count != current_seat_count:
|
|
|
|
RealmAuditLog.objects.create(
|
|
|
|
realm=customer.realm,
|
2018-08-11 00:51:18 +02:00
|
|
|
event_type=RealmAuditLog.STRIPE_PLAN_QUANTITY_RESET,
|
2018-06-28 00:48:51 +02:00
|
|
|
event_time=timestamp_to_datetime(stripe_subscription.created),
|
|
|
|
requires_billing_update=True,
|
|
|
|
extra_data=ujson.dumps({'quantity': current_seat_count}))
|
2018-07-27 15:37:04 +02:00
|
|
|
|
2018-12-12 23:23:15 +01:00
|
|
|
def process_initial_upgrade(user: UserProfile, seat_count: int, schedule: int,
|
2018-09-08 00:49:54 +02:00
|
|
|
stripe_token: Optional[str]) -> None:
|
2018-12-12 23:23:15 +01:00
|
|
|
if schedule == CustomerPlan.ANNUAL:
|
|
|
|
plan = Plan.objects.get(nickname=Plan.CLOUD_ANNUAL)
|
|
|
|
else: # schedule == CustomerPlan.MONTHLY:
|
|
|
|
plan = Plan.objects.get(nickname=Plan.CLOUD_MONTHLY)
|
2018-08-14 03:33:31 +02:00
|
|
|
customer = Customer.objects.filter(realm=user.realm).first()
|
|
|
|
if customer is None:
|
2018-08-23 07:47:05 +02:00
|
|
|
stripe_customer = do_create_customer(user, stripe_token=stripe_token)
|
2018-09-08 00:49:54 +02:00
|
|
|
# elif instead of if since we want to avoid doing two round trips to
|
|
|
|
# stripe if we can
|
|
|
|
elif stripe_token is not None:
|
2018-08-14 03:33:31 +02:00
|
|
|
stripe_customer = do_replace_payment_source(user, stripe_token)
|
2018-09-08 00:49:54 +02:00
|
|
|
else:
|
|
|
|
stripe_customer = stripe_get_customer(customer.stripe_customer_id)
|
2018-07-27 15:37:04 +02:00
|
|
|
do_subscribe_customer_to_plan(
|
2018-08-22 07:49:48 +02:00
|
|
|
user=user,
|
2018-07-27 15:37:04 +02:00
|
|
|
stripe_customer=stripe_customer,
|
2018-08-06 06:47:15 +02:00
|
|
|
stripe_plan_id=plan.stripe_plan_id,
|
2018-07-27 15:37:04 +02:00
|
|
|
seat_count=seat_count,
|
|
|
|
# TODO: billing address details are passed to us in the request;
|
|
|
|
# use that to calculate taxes.
|
2018-09-08 00:49:54 +02:00
|
|
|
tax_percent=0,
|
|
|
|
charge_automatically=(stripe_token is not None))
|
2018-12-13 07:54:43 +01:00
|
|
|
do_change_plan_type(user.realm, Realm.STANDARD)
|
2018-07-03 21:49:55 +02:00
|
|
|
|
2018-12-12 19:41:03 +01:00
|
|
|
def attach_discount_to_realm(user: UserProfile, discount: Decimal) -> None:
|
2018-08-23 07:45:19 +02:00
|
|
|
customer = Customer.objects.filter(realm=user.realm).first()
|
|
|
|
if customer is None:
|
2018-12-12 19:41:03 +01:00
|
|
|
do_create_customer(user)
|
|
|
|
customer = Customer.objects.filter(realm=user.realm).first()
|
|
|
|
customer.default_discount = discount
|
|
|
|
customer.save()
|
2018-08-23 07:45:19 +02:00
|
|
|
|
2018-12-12 07:47:53 +01:00
|
|
|
def process_downgrade(user: UserProfile) -> None: # nocoverage
|
|
|
|
pass
|