[credit card] implement payment

This commit is contained in:
Nico Schottelius 2020-12-29 01:43:33 +01:00
commit 1b06d8ee03
16 changed files with 290 additions and 64 deletions

View file

@ -3,7 +3,7 @@ import stripe.error
import logging
import datetime
from django.core.exceptions import ObjectDoesNotExist
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.conf import settings
from django.contrib.auth import get_user_model
@ -80,20 +80,6 @@ def get_setup_intent(setup_intent_id):
def get_payment_method(payment_method_id):
return stripe.PaymentMethod.retrieve(payment_method_id)
@handle_stripe_error
def charge_customer(amount, customer_id, card_id):
# Amount is in CHF but stripes requires smallest possible unit.
# https://stripe.com/docs/api/payment_intents/create#create_payment_intent-amount
adjusted_amount = int(amount * 100)
return stripe.PaymentIntent.create(
amount=adjusted_amount,
currency=CURRENCY,
customer=customer_id,
payment_method=card_id,
off_session=True,
confirm=True,
)
@handle_stripe_error
def create_customer(name, email):
return stripe.Customer.create(name=name, email=email)
@ -111,7 +97,6 @@ def get_customer_cards(customer_id):
customer=customer_id,
type="card",
)
print(stripe_cards["data"])
for stripe_card in stripe_cards["data"]:
card = {}
@ -129,7 +114,21 @@ def sync_cards_for_user(user):
customer_id = get_customer_id_for(user)
cards = get_customer_cards(customer_id)
active_cards = StripeCreditCard.objects.filter(owner=user,
active=True)
if len(active_cards) > 0:
has_active_card = True
else:
has_active_card = False
for card in cards:
active = False
if not has_active_card:
active = True
has_active_card = True
StripeCreditCard.objects.get_or_create(card_id=card['id'],
owner = user,
defaults = {
@ -137,6 +136,36 @@ def sync_cards_for_user(user):
'brand': card['brand'],
'expiry_date': datetime.date(card['year'],
card['month'],
1)
1),
'active': active
}
)
@handle_stripe_error
def charge_customer(user, amount, currency='CHF'):
# Amount is in CHF but stripes requires smallest possible unit.
# https://stripe.com/docs/api/payment_intents/create#create_payment_intent-amount
# FIXME: might need to be adjusted for other currencies
if currency == 'CHF':
adjusted_amount = int(amount * 100)
else:
return Exception("Programming error: unsupported currency")
try:
card = StripeCreditCard.objects.get(owner=user,
active=True)
except StripeCreditCard.DoesNotExist:
raise ValidationError("No active credit card - cannot create payment")
customer_id = get_customer_id_for(user)
return stripe.PaymentIntent.create(
amount=adjusted_amount,
currency=currency,
customer=customer_id,
payment_method=card.card_id,
off_session=True,
confirm=True,
)