Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactored Stripe views, collections and unit tests #27

Merged
merged 6 commits into from
Apr 1, 2022
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 11 additions & 6 deletions pfunk/contrib/ecommerce/collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from pfunk.fields import EmailField, SlugField, ManyToManyField, ListField, ReferenceField, StringField, EnumField, FloatField
from pfunk.contrib.auth.resources import GenericGroupBasedRole, GenericUserBasedRole, Public, UserRole
from pfunk.contrib.ecommerce.resources import StripePublic
from pfunk.contrib.ecommerce.views import ListStripePackage, DetailStripePackage
from pfunk.contrib.ecommerce.views import BaseWebhookView, ListStripePackage, DetailStripePackage, CheckoutSuccessView
from pfunk.web.views.json import CreateView, UpdateView, DeleteView


Expand All @@ -22,11 +22,15 @@ class StripePackage(Collection):
fields and functions to match your system.

Read and detail views are naturally public. Write operations
requires authentication from admin group.
requires authentication from admin group. While it grealty
depends on your app, it is recommended to have this only
modified by the admins and use `StripeCustomer` model to
attach a `stripe_id` to a model that is bound for payment.
"""
use_crud_views = False
collection_roles = [GenericGroupBasedRole]
collection_views = [ListStripePackage, DetailStripePackage, CreateView, UpdateView, DeleteView]
collection_views = [ListStripePackage, DetailStripePackage,
CheckoutSuccessView, CreateView, UpdateView, DeleteView]
stripe_id = StringField(required=True)
name = StringField(required=True)
price = FloatField(required=True)
Expand All @@ -48,10 +52,11 @@ class StripeCustomer(Collection):
can you structure your collections. Override the
fields and functions to match your system.
"""
collection_roles = [GenericUserBasedRole]
user = ReferenceField(User)
customer_id = StringField(required=True)
package = ReferenceField(StripePackage)
collection_roles = [GenericUserBasedRole]
stripe_id = StringField(required=True, unique=True)
description = StringField()
collection_views = [BaseWebhookView]

def __unicode__(self):
return self.customer_id
Expand Down
90 changes: 51 additions & 39 deletions pfunk/contrib/ecommerce/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from envs import env
from datetime import datetime
from json import JSONDecodeError
from werkzeug.routing import Rule
from jinja2 import Environment, BaseLoader

from pfunk.contrib.email import ses
Expand All @@ -15,6 +16,7 @@
from pfunk.contrib.auth.collections import Group, User
from pfunk.web.views.base import ActionMixin


stripe.api_key = env('STRIPE_API_KEY')
STRIPE_PUBLISHABLE_KEY = env('STRIPE_PUBLISHABLE_KEY')
STRIPE_WEBHOOK_SECRET = env('STRIPE_WEBHOOK_SECRET')
Expand Down Expand Up @@ -71,30 +73,51 @@ def get_context_data(self, **kwargs):
return context


class CheckoutSuccessView(DetailView):
class CheckoutSuccessView(DetailView, ActionMixin):
""" Defines action from the result of `CheckoutView` """
action = 'checkout-success'
http_method_names = ['get']

@classmethod
def url(cls, collection):
return Rule(f'/{collection.get_class_name()}/{cls.action}/<string:id>/', endpoint=cls.as_view(collection),
methods=cls.http_methods)

def get_object(self, queryset=None):
def get_query(self, *args, **kwargs):
""" Acquires the object from the `SessionView` """
try:
session_id = self.request.GET['session_id']
except KeyError:
raise DocNotFound
session_id = self.request.kwargs.get('id')
self.stripe_session = stripe.checkout.Session.retrieve(session_id)
return self.model.objects.get(stripe_id=self.stripe_session.client_reference_id)

def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['stripe_session'] = self.stripe_session
return context
# NOTE: Chose listing instead of indexing under the assumption of limited paid packages. Override if needed
pkg = [pkg for pkg in self.collection.all() if pkg.stripe_id ==
self.stripe_session.client_reference_id]
if pkg:
return pkg
raise DocNotFound


class BaseWebhookView(JSONView, ActionMixin):
class BaseWebhookView(CreateView, ActionMixin):
""" Base class to use for executing Stripe webhook actions """
login_required = False
action = 'webhook'
http_method_names = ['post']
webhook_signing_secret = STRIPE_WEBHOOK_SECRET

def get_query(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
self.event = self.check_signing_secret()
try:
self.event_json = json.loads(self.request.body)
except TypeError:
self.event_json = self.request.body

try:
self.object = self.event.data.object
except AttributeError:
self.object = None

return self.event_action()

def event_action(self):
""" Transforms Stripe action to snake case for easier
calling in child class
Expand All @@ -106,25 +129,12 @@ def event_action(self):
that
"""
event_type = self.event.type.replace('.', '_')
action = getattr(self, event_type, None)
if isinstance(action, collections.Callable):
action()
return {'success': 'ok'}
raise super().not_found_class()

def post(self, request, *args, **kwargs):
self.request = request
self.args = args
self.kwargs = kwargs
self.event = self.check_signing_secret()
self.event_json = json.loads(self.request.body)

try:
self.object = self.event.data.object
except AttributeError:
self.object = None

return self.event_action()
if event_type is str:
action = getattr(self, event_type, None)
if isinstance(action, collections.Callable):
action()
return {'success': 'ok'}
raise NotImplementedError

def check_ip(self):
"""
Expand All @@ -137,7 +147,7 @@ def check_ip(self):
except (KeyError, JSONDecodeError):
return True
try:
return self.request.META['REMOTE_ADDR'] in valid_ips
return self.request.source_ip in valid_ips
except KeyError:
return False

Expand All @@ -150,8 +160,7 @@ def send_html_email(self, subject, from_email: str, to_email_list: list, templat
DEFAULT_FROM_EMAIL (str): default `from` email
"""
if not context:
context = {'object': self.object,
'request_body': self.request.body}
context = {'request_body': self.request.body}
if template_name:
rtemplate = Environment(
loader=BaseLoader()).from_string(template_name)
Expand All @@ -172,13 +181,15 @@ def send_html_email(self, subject, from_email: str, to_email_list: list, templat

def check_signing_secret(self):
"""
Make sure the request's Stripe signature to make sure it matches our signing secret.
:return: HttpResponse or Stripe Event Object
Make sure the request's Stripe signature to make sure it matches our signing secret
then returns the event

:return: Stripe Event Object
"""
# If we are running tests we can't verify the signature but we need the event objects

event = stripe.Webhook.construct_event(
self.request.body, self.request.META['HTTP_STRIPE_SIGNATURE'], self.webhook_signing_secret
self.request.body, self.request.headers['HTTP_STRIPE_SIGNATURE'], self.webhook_signing_secret
)
return event

Expand All @@ -187,8 +198,9 @@ def get_transfer_data(self):

def checkout_session_completed(self):
""" A method to override to implement custom actions
after successful Stripe checkout
after successful Stripe checkout.

This is a Stripe event.
Use this method by subclassing this class in your
custom claas
"""
Expand Down
Loading