def user_post_save(sender, instance, created, **kwargs): """Create a user profile when a new user account is created""" if created: for subscriber in get_subscriber_model().objects.filter( customer__isnull=True): Customer.get_or_create(subscriber=subscriber) print("Created subscriber for {0}".format(subscriber.email))
def setUp(self, stripe_customer_mock): self.url = reverse("djstripe:change_plan") self.user1 = get_user_model().objects.create_user( username="******", email="*****@*****.**", password="******") self.user2 = get_user_model().objects.create_user( username="******", email="*****@*****.**", password="******") Customer.get_or_create(subscriber=self.user1)
def setUp(self, stripe_customer_mock): self.url = reverse("djstripe:change_plan") self.user1 = get_user_model().objects.create_user( username="******", email="*****@*****.**", password="******" ) self.user2 = get_user_model().objects.create_user( username="******", email="*****@*****.**", password="******" ) Customer.get_or_create(subscriber=self.user1)
def post(self, request, *args, **kwargs): """ Handles POST requests, instantiating a form instance with the passed POST variables and then checked for validity. """ form_class = self.get_form_class() form = self.get_form(form_class) if form.is_valid(): try: customer, created = Customer.get_or_create( subscriber=subscriber_request_callback(self.request)) update_card = self.request.POST.get("stripe_token", None) if update_card: customer.update_card(update_card) product = Product.objects.get(id=form.cleaned_data['product']) charge = customer.charge(product.price, send_receipt=False) # don't send reciept until product purhcase is created # create a product_purchase model that is associated with the charge ProductPurchase.objects.create(charge=charge, product=product, downloads=product.downloads) # send reciept now that product pruchase is created charge.send_receipt() except stripe.StripeError as exc: form.add_error(None, str(exc)) return self.form_invalid(form) # redirect to confirmation page return self.form_valid(form) else: return self.form_invalid(form)
def get_count(self, obj): default = 1 plan = 200 today = APIRequestLog.objects.filter( path='/v1/dashboard/keywordtool/', user=obj, requested_at__date=datetime.today()).count() if Vip.objects.filter(user=obj): return 1000 customer, created = Customer.get_or_create(subscriber=obj) try: subscription = customer.current_subscription except CurrentSubscription.DoesNotExist: if default - today > 0: return default - today else: return 0 if subscription.status != 'active' and subscription.status != 'trialing': if default - today > 0: return default - today else: return 0 if plan - today > 0: return plan - today else: return 0
def user_info(request): if request.user.is_authenticated(): '''Generate new invite ID.''' invite_id_obj = InviteId() invite_id = invite_id_obj.get_unused_id(request.user.id) '''Construct New Invite URL.''' try: # pass invite_tweet = construct_invite_tweet(request, invite_id) except: pass subscribed = True customer, created = Customer.get_or_create(request.user) if created: subscribed = False if not customer.has_active_subscription(): subscribed = False user_id = request.user.id try: user_info = UserInfo(user_id) ft = TweetFeed() if subscribed: can_tweet = True else: has_trial_period_expired = ft.has_expired_trial_period(request.user.id) if has_trial_period_expired == True: has_tweet = ft.has_tweet_in_week(request.user.id) if not has_tweet: can_tweet = True else: can_tweet = False else: can_tweet = True return { 'userinfo' : user_info, "subscribed": subscribed, "can_tweet":can_tweet, 'invite_id':invite_id['uid']['id'], 'invite_tweet':invite_tweet } except: return {'userinfo':""} return {}
def get(self, request, *args, **kwargs): customer, created = Customer.get_or_create( subscriber=subscriber_request_callback(self.request)) if hasattr(customer, "current_subscription") and \ customer.current_subscription.status != CurrentSubscription.STATUS_CANCELLED: message = "You are already subscribed." messages.info(request, message, fail_silently=True) return redirect("djstripe:account") return super(SubscriptionCreateView, self).get(request, *args, **kwargs)
def get_context_data(self, **kwargs): user = self.request.user context = super(SearchLicence, self).get_context_data(**kwargs) if user.is_authenticated(): customer, created = Customer.get_or_create(subscriber=user.id) user_profile = profile.objects.get(customer=customer) context['are_id'] = user_profile.are_id return context
def form_valid(self, form): '''''' user = self.request.user customer, created = Customer.get_or_create(subscriber=user) amount = Decimal(form.amount) customer.charge(amount) user_profile = profile.objects.get(customer=customer) user_profile.credit += amount user_profile.save() return super(TopupView, self).form_valid(form)
def post(self, request, *args, **kwargs): """ Handles POST requests, instantiating a form instance with the passed POST variables and then checked for validity. """ form_class = self.get_form_class() form = self.get_form(form_class) if form.is_valid(): post_data = self.request.POST try: customer, created = Customer.get_or_create( subscriber=subscriber_request_callback(self.request)) customer.update_card(post_data.get("stripe_token")) if not hasattr(customer, "current_subscription"): self.is_new_customer = True # update customer email (if necessary) email = post_data.get('email') if (utils.mail.is_valid_email(email) and not customer.subscriber.email): customer.subscriber.email = email customer.subscriber.save() plan = form.cleaned_data['plan'] # check if plan is subscribable is_subscribable, errors = customer.subscriber.validate_plan( plan) if not is_subscribable: # for error in errors: # form.add_error(None, error.messages[0]) [form.add_error(None, err.messages[0]) for err in errors] return self.form_invalid(form) # create invoiceitem for shareholders if necessary utils.subscriptions.stripe_company_shareholder_invoice_item( customer, plan) # create invoiceitem for securities if necessary utils.subscriptions.stripe_company_security_invoice_item( customer, plan) # subscribe customer to selected plan customer.subscribe(plan) except stripe.StripeError as exc: form.add_error(None, str(exc)) return self.form_invalid(form) return self.form_valid(form) else: return self.form_invalid(form)
def get_active(self, obj): if Vip.objects.filter(user=obj): return True customer, created = Customer.get_or_create(subscriber=obj) try: subscription = customer.current_subscription except CurrentSubscription.DoesNotExist: return False if subscription.status != 'active' and subscription.status != 'trialing': return False return True
def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) if form.is_valid(): try: customer, created = Customer.get_or_create( subscriber=subscriber_request_callback(self.request)) customer.update_card(self.request.POST.get("stripeToken")) customer.subscribe(form.cleaned_data["plan"]) except stripe.StripeError as exc: form.add_error(None, str(exc)) return self.form_invalid(form) return self.form_valid(form) else: return self.form_invalid(form)
def form_valid(self, form): customer, created = Customer.get_or_create( subscriber=subscriber_request_callback(self.request)) if customer.has_active_subscription( ) and customer.current_subscription.cancel_at_period_end: customer.subscribe(customer.current_subscription.plan) messages.info( self.request, "You have reactivated your subscription. It expires at '{period_end}'." .format(period_end=customer.current_subscription. current_period_end)) return super(ReactivateSubscriptionView, self).form_valid(form)
def get_plan(self, obj): if Vip.objects.filter(user=obj): return 'Founding LIFETIME Member' customer, created = Customer.get_or_create(subscriber=obj) try: subscription = customer.current_subscription except CurrentSubscription.DoesNotExist: return 'FREE Plan' if subscription.status != 'active' and subscription.status != 'trialing': return 'FREE Plan' return subscription.plan
def get(self, request, format=None): """ Return the users current subscription. Returns with status code 200. """ try: customer, created = Customer.get_or_create( subscriber=subscriber_request_callback(self.request)) subscription = customer.current_subscription serializer = SubscriptionSerializer(subscription) return Response(serializer.data) except: return Response(status=status.HTTP_204_NO_CONTENT)
def customer(self): try: customer, _ = Customer.get_or_create(self) return customer except AuthenticationError as e: # if we are bypassing stripe, we swallow the exception and # emit a warning instead. This allows us to develop the app # without caring about setting up stripe for every development # environment if settings.BYPASS_STRIPE: logger.warning( "Warning: You are using an invalid Stripe API key. Since BYPASS_STRIPE is set to True, this " "error is ignored. To test your Stripe integration, make sure to set BYPASS_STRIPE to False." ) return None raise e
def delete(self, request, format=None): """ Marks the users current subscription as cancelled. Returns with status code 204. """ try: customer, created = Customer.get_or_create( subscriber=subscriber_request_callback(self.request)) customer.cancel_subscription( at_period_end=CANCELLATION_AT_PERIOD_END) return Response(status=status.HTTP_204_NO_CONTENT) except: return Response( "Something went wrong cancelling the subscription.", status=status.HTTP_400_BAD_REQUEST)
def has_permission(self, request, view): """ Check if the subscriber has an active subscription. Returns false if: * a subscriber isn't passed through the request See ``utils.subscriber_has_active_subscription`` for more rules. """ try: customer, created = Customer.get_or_create( subscriber=subscriber_request_callback(request) ) return customer.has_active_subscription() except AttributeError: return False
def has_active_subscription(self): """ Helper property to check if a user has an active subscription. """ # Anonymous users return false if self.is_anonymous(): return False # Import placed here to avoid circular imports from djstripe.models import Customer # Get or create the customer object customer, created = Customer.get_or_create(self) # If new customer, return false # If existing customer but inactive return false if created or not customer.has_active_subscription(): return False # Existing, valid customer so return true return True
def handle(self, *args, **options): for user in User.objects.filter(customer__isnull=True): # use get_or_create in case of race conditions on large # user bases Customer.get_or_create(user=user) print("Created customer for {0}".format(user.email))