2022-07-21 12:48:18 +00:00
|
|
|
import logging
|
|
|
|
|
2022-07-21 12:48:14 +00:00
|
|
|
import stripe
|
|
|
|
|
2022-07-21 12:48:18 +00:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
2022-07-21 12:48:14 +00:00
|
|
|
def expand_name(first_name, last_name):
|
|
|
|
"""
|
|
|
|
Convert two name variables into one.
|
|
|
|
Last name without a first name is ignored.
|
|
|
|
"""
|
|
|
|
name = None
|
|
|
|
if first_name:
|
|
|
|
name = first_name
|
|
|
|
# We only want to put the last name if we have a first name
|
|
|
|
if last_name:
|
|
|
|
name += f" {last_name}"
|
|
|
|
return name
|
|
|
|
|
2022-07-21 12:48:18 +00:00
|
|
|
|
2022-07-21 12:48:14 +00:00
|
|
|
def get_or_create(email, first_name, last_name):
|
|
|
|
"""
|
|
|
|
Get a customer ID from Stripe if one with the given email exists.
|
|
|
|
Create a customer if one does not.
|
|
|
|
Raise an exception if two or more customers matching the given email exist.
|
|
|
|
"""
|
|
|
|
# Let's see if we're just missing the ID
|
|
|
|
matching_customers = stripe.Customer.list(email=email, limit=2)
|
|
|
|
if len(matching_customers) == 2:
|
|
|
|
# Something is horribly wrong
|
2022-07-21 12:48:18 +00:00
|
|
|
logger.error(f"Two customers found for email {email}")
|
2022-07-21 12:48:14 +00:00
|
|
|
raise Exception(f"Two customers found for email {email}")
|
|
|
|
|
|
|
|
elif len(matching_customers) == 1:
|
|
|
|
# We found a customer. Let's copy the ID
|
|
|
|
customer = matching_customers["data"][0]
|
|
|
|
customer_id = customer["id"]
|
|
|
|
return customer_id
|
|
|
|
|
|
|
|
else:
|
|
|
|
# We didn't find anything. Create the customer
|
|
|
|
|
|
|
|
# Create a name, since we have 2 variables which could be null
|
|
|
|
name = expand_name(first_name, last_name)
|
|
|
|
cast = {"email": email}
|
|
|
|
if name:
|
|
|
|
cast["name"] = name
|
|
|
|
customer = stripe.Customer.create(**cast)
|
2022-07-21 12:48:18 +00:00
|
|
|
logger.info(f"Created new Stripe customer {customer.id} with email {email}")
|
2022-07-21 12:48:14 +00:00
|
|
|
|
|
|
|
return customer.id
|
|
|
|
|
2022-07-21 12:48:18 +00:00
|
|
|
|
2022-07-21 12:48:14 +00:00
|
|
|
def update_customer_fields(stripe_id, email=None, first_name=None, last_name=None):
|
|
|
|
"""
|
|
|
|
Update the customer fields in Stripe.
|
|
|
|
"""
|
|
|
|
print("Update customer fields called")
|
|
|
|
if email:
|
|
|
|
print("Email modified")
|
|
|
|
stripe.Customer.modify(stripe_id, email=email)
|
2022-07-21 12:48:18 +00:00
|
|
|
logger.info(f"Modified Stripe customer {stripe_id} to have email {email}")
|
2022-07-21 12:48:14 +00:00
|
|
|
if first_name or last_name:
|
|
|
|
print("Name modified")
|
|
|
|
name = expand_name(first_name, last_name)
|
2022-07-21 12:48:18 +00:00
|
|
|
stripe.Customer.modify(stripe_id, name=name)
|
|
|
|
logger.info(f"Modified Stripe customer {stripe_id} to have email {name}")
|