Properly wire stripe card to payment methods

This commit is contained in:
fnux 2020-03-03 16:55:56 +01:00
commit 94a39ed81d
6 changed files with 117 additions and 43 deletions

View file

@ -1,4 +1,5 @@
from django.shortcuts import render
from django.db import transaction
from django.contrib.auth import get_user_model
from rest_framework import viewsets, permissions, status
from rest_framework.response import Response
@ -69,13 +70,34 @@ class PaymentMethodViewSet(viewsets.ModelViewSet):
def get_queryset(self):
return PaymentMethod.objects.filter(owner=self.request.user)
# XXX: Handling of errors is far from great down there.
@transaction.atomic
def create(self, request):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save(owner=request.user)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
# Retrieve Stripe customer ID for user.
customer_id = stripe.get_customer_id_for(request.user)
if customer_id == None:
return Response(
{'error': 'Could not resolve customer stripe ID.'},
status=status.HTTP_500_INTERNAL_SERVER_ERROR)
# Register card under stripe customer.
credit_card = stripe.CreditCard(**serializer.validated_data.pop('credit_card'))
card_request = stripe.create_card(customer_id, credit_card)
if card_request['error']:
return Response({'stripe_error': card_request['error']}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
card_id = card_request['response_object']['id']
# Save payment method locally.
serializer.validated_data['stripe_card_id'] = card_request['response_object']['id']
payment_method = PaymentMethod.objects.create(owner=request.user, **serializer.validated_data)
# We do not want to return the credit card details sent with the POST
# request.
output_serializer = PaymentMethodSerializer(payment_method)
return Response(output_serializer.data)
# TODO: find a way to customize serializer for actions.
# drf-action-serializer module seems to do that.