Skip to content

Instantly share code, notes, and snippets.

@dkdndes
Last active July 9, 2019 09:55
Show Gist options
  • Save dkdndes/c02ef9b1b208d31fe96a20e6e5916563 to your computer and use it in GitHub Desktop.
Save dkdndes/c02ef9b1b208d31fe96a20e6e5916563 to your computer and use it in GitHub Desktop.
djstribe url missing in docu; place the code in /payments/ and /api/
# Payments
url(r'^payments/', include('djstripe.contrib.rest_framework.urls', namespace="rest_payments")),

DJStripe RestAPI

Its not documented, you need to checkout the source code here:

Load plans from stripe.com manualy

 from djstripe.models import Plan

 for plan in Plan.api_list():
      Plan.sync_from_stripe_data(plan)

create dj-stripe link with django users (loose coupling, and no automatic adding)

 $ python manage.py djstripe_init_customers
  • djstripe_init_customers - """Create customer objects for existing subscribers that don't have one."""
  • djstripe_sync_customers - """Sync subscriber data with stripe."""
  • djstripe_clear_expired_idempotency_keys - "Deleted expired Stripe idempotency keys."

Helper functions to check subscription

def subscriber_has_active_subscription(subscriber, plan=None):

Default all urls except excluded to subscriptions via Middleware

 class SubscriptionPaymentMiddleware(MiddlewareMixin):
     """
     Used to redirect users from subcription-locked request destinations.
     Rules:
         * "(app_name)" means everything from this app is exempt
         * "[namespace]" means everything with this name is exempt
         * "namespace:name" means this namespaced URL is exempt
         * "name" means this URL is exempt
         * The entire djstripe namespace is exempt
         * If settings.DEBUG is True, then django-debug-toolbar is exempt
         * A 'fn:' prefix means the rest of the URL is fnmatch'd.
         Example::
         DJSTRIPE_SUBSCRIPTION_REQUIRED_EXCEPTION_URLS = (
             "[blogs]",  # Anything in the blogs namespace
             "products:detail",  # A ProductDetail view you want shown to non-payers
             "home",  # Site homepage
             "fn:/accounts*",  # anything in the accounts/ URL path
         )
     """

Payment decorators for views to check subscription payment and status

  • subscriber_passes_pay_test - Decorator for views that checks the subscriber passes the given test for a "Paid Feature"
  • subscription_payment_required - Decorator for views that require subscription payment. Redirects to pay_page if necessary.

Links

from django.conf.urls import url, include
from django.conf.urls import url, include
from django.views.generic import TemplateView
from django.conf.urls.static import static
from django.contrib import admin
urlpatterns = [
# Stripe Payments
url(r'^', include('djstripe.urls', namespace="djstripe")),
]
import stripe
from django.conf import settings
from django.dispatch import receiver
from djstripe.models import Customer
from djstripe.signals import WEBHOOK_SIGNALS
from django.views.generic import FormView, TemplateView
from django.core.urlresolvers import reverse_lazy
from .forms import StripeForm
@receiver(WEBHOOK_SIGNALS['customer.subscription.deleted'])
def subscription_deleted(sender, **kwargs):
# print 'canceled'
pass
class StripeMixin(object):
def get_context_data(self, kwargs):
context = super(StripeMixin, self).get_context_data(kwargs)
context['publishable_key'] = settings.STRIPE_PUBLIC_KEY
return context
class SuccessView(TemplateView):
template_name = 'store/thank_you.html'
class CustomerMixin(object):
def get_customer(self):
try:
return self.request.user.customer
except BaseException:
return Customer.create(self.request.user)
class SubscribeView(StripeMixin, CustomerMixin, FormView):
template_name = 'store/subscribe.html'
form_class = StripeForm
success_url = reverse_lazy('thank_you')
def form_valid(self, form):
customer = self.get_customer()
customer.update_card(form.cleaned_data.get('stripe_token', None))
customer.subscribe('monthly')
return super(SubscribeView, self).form_valid(form)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment