Last active
February 21, 2016 13:36
-
-
Save svfat/63019da36d73d994da97 to your computer and use it in GitHub Desktop.
Django TastyPie + dj-stripe API endpoint for subscriptions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from djstripe.models import Customer | |
from djstripe.settings import CANCELLATION_AT_PERIOD_END | |
from tastypie import http | |
def subscription(self, request, **kwargs): | |
self.method_check(request, ['get', 'post', 'delete']) | |
if request.user.is_authenticated(): | |
user = request.user | |
customer = Customer.objects.get(subscriber=user) | |
if request.method == 'GET': | |
try: | |
data = {'subscription': customer.current_subscription} | |
resp = self.create_response(request, data) | |
except BaseException: | |
data = {'subscription': None} | |
resp = self.create_response(request, data) | |
elif request.method == 'POST': | |
try: | |
stripe_token = request.POST.get('stripe_token') | |
plan = request.POST.get('plan') | |
if stripe_token and plan: | |
customer.update_card(stripe_token) | |
customer.subscribe(plan) | |
data = {'subscription': customer.current_subscription} | |
resp = self.create_response(request, data) | |
else: | |
if not plan: | |
resp = http.HttpBadRequest( | |
"\"plan\" is missing or incorrect" | |
) | |
elif not stripe_token: | |
resp = http.HttpBadRequest( | |
"\"stripe_token\" is missing or incorrect" | |
) | |
except BaseException: | |
resp = http.HttpBadRequest("Something went wrong processing the payment") | |
elif request.method == 'DELETE': | |
try: | |
customer.cancel_subscription( | |
at_period_end=CANCELLATION_AT_PERIOD_END | |
) | |
data = {'success': True} | |
resp = self.create_response(request, data) | |
except BaseException: | |
resp = http.HttpBadRequest( | |
"Something went wrong cancelling the subscription." | |
) | |
else: | |
resp = http.HttpBadRequest('Wrong HTTP method: {}'.format(request.method)) | |
return resp | |
else: | |
return http.HttpUnauthorized() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment