views.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. """
  2. .. module:: dj-stripe.contrib.rest_framework.views.
  3. :synopsis: Views for the dj-stripe REST API.
  4. """
  5. from rest_framework import status
  6. from rest_framework.permissions import IsAuthenticated
  7. from rest_framework.response import Response
  8. from rest_framework.views import APIView
  9. from ...models import Customer
  10. from ...settings import CANCELLATION_AT_PERIOD_END, subscriber_request_callback
  11. from .serializers import CreateSubscriptionSerializer, SubscriptionSerializer
  12. class SubscriptionRestView(APIView):
  13. """API Endpoints for the Subscription object."""
  14. permission_classes = (IsAuthenticated,)
  15. def get(self, request, **kwargs):
  16. """
  17. Return the customer's valid subscriptions.
  18. Returns with status code 200.
  19. """
  20. customer, _created = Customer.get_or_create(
  21. subscriber=subscriber_request_callback(self.request)
  22. )
  23. serializer = SubscriptionSerializer(customer.subscription)
  24. return Response(serializer.data)
  25. def post(self, request, **kwargs):
  26. """
  27. Create a new current subscription for the user.
  28. Returns with status code 201.
  29. """
  30. serializer = CreateSubscriptionSerializer(data=request.data)
  31. if serializer.is_valid():
  32. try:
  33. customer, _created = Customer.get_or_create(
  34. subscriber=subscriber_request_callback(self.request)
  35. )
  36. customer.add_card(serializer.data["stripe_token"])
  37. charge_immediately = serializer.data.get("charge_immediately")
  38. if charge_immediately is None:
  39. charge_immediately = True
  40. customer.subscribe(serializer.data["plan"], charge_immediately)
  41. return Response(serializer.data, status=status.HTTP_201_CREATED)
  42. except Exception:
  43. # TODO: Better error messages
  44. return Response(
  45. "Something went wrong processing the payment.",
  46. status=status.HTTP_400_BAD_REQUEST,
  47. )
  48. return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
  49. def delete(self, request, **kwargs):
  50. """
  51. Mark the customers current subscription as canceled.
  52. Returns with status code 204.
  53. """
  54. try:
  55. customer, _created = Customer.get_or_create(
  56. subscriber=subscriber_request_callback(self.request)
  57. )
  58. customer.subscription.cancel(at_period_end=CANCELLATION_AT_PERIOD_END)
  59. return Response(status=status.HTTP_204_NO_CONTENT)
  60. except Exception:
  61. return Response(
  62. "Something went wrong cancelling the subscription.",
  63. status=status.HTTP_400_BAD_REQUEST,
  64. )