def test_create_trial_callback(self, customer_create_mock, callback_mock): user = get_user_model().objects.create_user(username="******", email="*****@*****.**") Customer.create(user) customer_create_mock.assert_called_once_with(email=user.email) callback_mock.assert_called_once_with(user)
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 test_create_default_plan(self, customer_create_mock, callback_mock, default_plan_fake, subscribe_mock): user = get_user_model().objects.create_user(username="******", email="*****@*****.**") Customer.create(user) customer_create_mock.assert_called_once_with(email=user.email) callback_mock.assert_called_once_with(user) subscribe_mock.assert_called_once_with(plan=default_plan_fake, trial_days="donkey")
def test_bad_object_value(self): with self.assertRaises(ValueError): # Errors because the object is not correct Customer._stripe_object_to_record({ "id": "test_XXXXXXXX", "livemode": False, "object": "not_a_customer" })
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 test_create_trial_callback_without_default_plan(self, create_mock, callback_mock): user = get_user_model().objects.create_user(username="******", email="*****@*****.**") Customer.create(user, idempotency_key="foo") create_mock.assert_called_once_with( api_key=settings.STRIPE_SECRET_KEY, email=user.email, idempotency_key="foo", metadata={"djstripe_subscriber": user.id} ) callback_mock.assert_called_once_with(user)
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 on_email_changed(request, user, from_email_address, to_email_address, **kwargs): from djstripe.models import Customer customer = Customer.objects.filter(subscriber=user).first() if not customer: # Don't bother creating a customer for this user, it'll happen later. return stripe_obj = customer.api_retrieve() stripe_obj.email = to_email_address.email Customer.sync_from_stripe_data(stripe_obj.save())
def test_customer_dashboard_url(self): expected_url = "https://dashboard.stripe.com/test/customers/{}".format(self.customer.stripe_id) self.assertEqual(self.customer.get_stripe_dashboard_url(), expected_url) self.customer.livemode = True expected_url = "https://dashboard.stripe.com/customers/{}".format(self.customer.stripe_id) self.assertEqual(self.customer.get_stripe_dashboard_url(), expected_url) unsaved_customer = Customer() self.assertEqual(unsaved_customer.get_stripe_dashboard_url(), "")
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 create_for_user(self, user): from djstripe.models import Customer stripe_customer = Customer.sync_from_stripe_data(self) stripe_customer.subscriber = user stripe_customer.save() return stripe_customer
def test_customer_sync_has_bad_subscriber_metadata(self): fake_customer = deepcopy(FAKE_CUSTOMER) fake_customer["metadata"] = {"djstripe_subscriber": "does_not_exist"} customer = Customer.sync_from_stripe_data(fake_customer) self.assertEqual(customer.subscriber, None) self.assertEqual(customer.metadata, {"djstripe_subscriber": "does_not_exist"})
def test_customer_sync_default_source_string(self): Customer.objects.all().delete() customer_fake = deepcopy(FAKE_CUSTOMER) customer_fake["default_source"] = customer_fake["sources"]["data"][0]["id"] = "card_sync_source_string" customer = Customer.sync_from_stripe_data(customer_fake) self.assertEqual(customer.default_source.stripe_id, customer_fake["default_source"]) self.assertEqual(customer.sources.count(), 2)
def test_customer_create_metadata_disabled(self, customer_mock): user = get_user_model().objects.create_user( username="******") fake_customer = deepcopy(FAKE_CUSTOMER) fake_customer["id"] = "cus_test_create_metadata_disabled" customer_mock.return_value = fake_customer djstripe_settings.SUBSCRIBER_CUSTOMER_KEY = "" customer = Customer.create(user) djstripe_settings.SUBSCRIBER_CUSTOMER_KEY = "djstripe_subscriber" customer_mock.assert_called_once_with(api_key=STRIPE_SECRET_KEY, email="", idempotency_key=None, metadata={}) self.assertEqual(customer.metadata, None) self.assert_fks( customer, expected_blank_fks={ "djstripe.Customer.coupon", "djstripe.Customer.default_source" }, )
def validate(self, data): card = data.get('credit_card') if card: client = self.instance.client if client != self.context.get('request').user: raise serializers.ValidationError( _("Only client for the hire services can update credit card" )) if client.profile.type != FINAL: raise serializers.ValidationError( _("Client user must be a final client, not professional")) # Validate credit card for client customer, created = Customer.get_or_create(client) if created: raise serializers.ValidationError( _("Client just register in stripe. Not linked credit cards" )) cards = customer.sources.get_queryset().values_list('stripe_id', flat=True) if card not in cards: raise serializers.ValidationError( _("Credit card number not belongs to the client")) return data
def list(self, request, *args, **kwargs): user = self.request.user customer, created = Customer.get_or_create(user) cards = customer.sources.get_queryset() serializer = self.get_serializer(cards, many=True) return Response(data=serializer.data, status=status.HTTP_200_OK)
def stripe_customer(self): if (isinstance(self.subscriber, get_user_model())): customer, _created = Customer.get_or_create( subscriber=self.subscriber) return customer raise SuspiciousOperation('%s is not a valid subscriber' % self.subscriber)
def test_sync_customer_delete_discount(self): test_coupon = Coupon.sync_from_stripe_data(FAKE_COUPON) self.customer.coupon = test_coupon self.customer.save() self.assertEqual(self.customer.coupon.id, FAKE_COUPON["id"]) customer = Customer.sync_from_stripe_data(FAKE_CUSTOMER) self.assertEqual(customer.coupon, None)
def add_card_view(request): if request.method == 'GET': context = {} return render(request, 'accountpage/add_card.html', context) elif request.method == 'POST': (st_customer, _) = Customer.get_or_create(request.user) res = st_customer.add_card(request.POST.get('stripe-token')) return redirect('/accounts/profile')
def test_sync_customer_with_discount(self, coupon_retrieve_mock): self.assertIsNone(self.customer.coupon) fake_customer = deepcopy(FAKE_CUSTOMER) fake_customer["discount"] = deepcopy(FAKE_DISCOUNT_CUSTOMER) customer = Customer.sync_from_stripe_data(fake_customer) self.assertEqual(customer.coupon.stripe_id, FAKE_COUPON["id"]) self.assertIsNotNone(customer.coupon_start) self.assertIsNone(customer.coupon_end)
def test_sync_customer_delete_discount(self): test_coupon = Coupon.sync_from_stripe_data(FAKE_COUPON) self.customer.coupon = test_coupon self.customer.save() self.assertEqual(self.customer.coupon.stripe_id, FAKE_COUPON["id"]) customer = Customer.sync_from_stripe_data(FAKE_CUSTOMER) self.assertEqual(customer.coupon, None)
def test_sync_customer_with_discount(self, coupon_retrieve_mock): self.assertIsNone(self.customer.coupon) fake_customer = deepcopy(FAKE_CUSTOMER) fake_customer["discount"] = deepcopy(FAKE_DISCOUNT_CUSTOMER) customer = Customer.sync_from_stripe_data(fake_customer) self.assertEqual(customer.coupon.id, FAKE_COUPON["id"]) self.assertIsNotNone(customer.coupon_start) self.assertIsNone(customer.coupon_end)
def test_customer_sync_no_sources(self, customer_mock): self.customer.sources.all().delete() fake_customer = deepcopy(FAKE_CUSTOMER) fake_customer["default_source"] = None customer = Customer.sync_from_stripe_data(fake_customer) self.assertEqual(customer.sources.count(), 0) self.assertEqual(customer.default_source, None)
def test_customer_sync_default_source_string(self): Customer.objects.all().delete() Card.objects.all().delete() customer_fake = deepcopy(FAKE_CUSTOMER) customer_fake["default_source"] = customer_fake["sources"]["data"][0]["id"] = "card_sync_source_string" customer = Customer.sync_from_stripe_data(customer_fake) self.assertEqual(customer.default_source.id, customer_fake["default_source"]) self.assertEqual(customer.legacy_cards.count(), 2) self.assertEqual(len(list(customer.payment_methods)), 2)
def test_customer_sync_has_subscriber_metadata(self): user = get_user_model().objects.create(username="******", id=12345) fake_customer = deepcopy(FAKE_CUSTOMER) fake_customer["metadata"] = {"djstripe_subscriber": "12345"} customer = Customer.sync_from_stripe_data(fake_customer) self.assertEqual(customer.subscriber, user) self.assertEqual(customer.metadata, {"djstripe_subscriber": "12345"})
def setUp(self): self.settings(ROOT_URLCONF=self.urlconf) self.factory = RequestFactory() self.user = get_user_model().objects.create_user(username="******", email="*****@*****.**") self.customer = Customer.sync_from_stripe_data(FAKE_CUSTOMER) self.customer.subscriber = self.user self.customer.save() self.subscription = Subscription.sync_from_stripe_data(FAKE_SUBSCRIPTION) self.middleware = SubscriptionPaymentMiddleware()
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 setUp(self): self.plan = Plan.sync_from_stripe_data(deepcopy(FAKE_PLAN)) self.url = reverse("djstripe:cancel_subscription") self.user = get_user_model().objects.create_user( username="******", email="*****@*****.**", password="******") self.assertTrue( self.client.login(username="******", password="******")) stripe_customer = Customer.sync_from_stripe_data(FAKE_CUSTOMER) stripe_customer.subscriber = self.user stripe_customer.save()
def test_customer_sync_non_local_card(self, card_retrieve_mock): fake_customer = deepcopy(FAKE_CUSTOMER_II) user = get_user_model().objects.create_user(username="******", email="*****@*****.**") Customer.objects.create(subscriber=user, stripe_id=FAKE_CUSTOMER_II["id"], livemode=False) customer = Customer.sync_from_stripe_data(fake_customer) self.assertEqual(FAKE_CUSTOMER_II["default_source"]["id"], customer.default_source.stripe_id) self.assertEqual(1, customer.sources.count())
def test_sync_customer_discount_already_present(self, coupon_retrieve_mock): fake_customer = deepcopy(FAKE_CUSTOMER) fake_customer["discount"] = deepcopy(FAKE_DISCOUNT_CUSTOMER) # Set the customer's coupon to be what we'll sync customer = Customer.objects.get(stripe_id=FAKE_CUSTOMER["id"]) customer.coupon = Coupon.sync_from_stripe_data(FAKE_COUPON) customer.save() customer = Customer.sync_from_stripe_data(fake_customer) self.assertEqual(customer.coupon.stripe_id, FAKE_COUPON["id"])
def test_sync_customer_discount_already_present(self, coupon_retrieve_mock): fake_customer = deepcopy(FAKE_CUSTOMER) fake_customer["discount"] = deepcopy(FAKE_DISCOUNT_CUSTOMER) # Set the customer's coupon to be what we'll sync customer = Customer.objects.get(id=FAKE_CUSTOMER["id"]) customer.coupon = Coupon.sync_from_stripe_data(FAKE_COUPON) customer.save() customer = Customer.sync_from_stripe_data(fake_customer) self.assertEqual(customer.coupon.id, FAKE_COUPON["id"])
def test_customer_sync_unsupported_source(self): fake_customer = deepcopy(FAKE_CUSTOMER_II) fake_customer["default_source"]["object"] = "fish" user = get_user_model().objects.create_user(username="******", email="*****@*****.**") Customer.objects.create(subscriber=user, stripe_id=FAKE_CUSTOMER_II["id"], livemode=False) customer = Customer.sync_from_stripe_data(fake_customer) self.assertEqual(None, customer.default_source) self.assertEqual(0, customer.sources.count())
def add_card(request): stripe_token = request.data['stripe_token'] customer, _ = Customer.get_or_create(subscriber=request.user) try: customer.add_card(stripe_token) except Exception: return Response({"message": "There was an error during adding a card"}, status=status.HTTP_400_BAD_REQUEST) else: return Response({"message": "Card was successfully added"}, status=status.HTTP_200_OK)
def setUp(self): self.settings(ROOT_URLCONF=self.urlconf) self.factory = RequestFactory() self.user = get_user_model().objects.create_user( username="******", email="*****@*****.**") self.customer = Customer.sync_from_stripe_data(FAKE_CUSTOMER) self.customer.subscriber = self.user self.customer.save() self.subscription = Subscription.sync_from_stripe_data( FAKE_SUBSCRIPTION) self.middleware = SubscriptionPaymentMiddleware()
def setUp(self): self.plan = Plan.sync_from_stripe_data(deepcopy(FAKE_PLAN)) self.url = reverse("djstripe:cancel_subscription") self.user = get_user_model().objects.create_user( username="******", email="*****@*****.**", password="******" ) self.assertTrue(self.client.login(username="******", password="******")) stripe_customer = Customer.sync_from_stripe_data(FAKE_CUSTOMER) stripe_customer.subscriber = self.user stripe_customer.save()
def sync_customers(apps, schema_editor): # This is okay, since we're only doing a forward migration. from djstripe.models import Customer from djstripe.context_managers import stripe_temporary_api_version with stripe_temporary_api_version("2016-03-07"): if Customer.objects.count(): print("syncing customers. This may take a while.") for customer in tqdm(Customer.objects.all(), desc="Sync", unit=" customers"): try: Customer.sync_from_stripe_data(customer.api_retrieve()) except InvalidRequestError: tqdm.write("There was an error while syncing customer \ ({customer_id}).".format(customer_id=customer.stripe_id)) except IntegrityError: print(customer.api_retrieve()) six.reraise(*sys.exc_info()) print("Customer sync complete.")
def get_context_data(self, **kwargs): context = super(SubscribeView, self).get_context_data(**kwargs) context['publishable_key'] = settings.STRIPE_PUBLIC_KEY profile = self.request.user.profile if profile.stripe_customer_id: customer = Customer.objects.get(stripe_id=profile.stripe_customer_id) else: customer = Customer.create(self.request.user) profile.stripe_customer_id = customer.stripe_id profile.save() context['customer'] = customer return context
def test_customer_sync_has_bad_subscriber_metadata(self): fake_customer = deepcopy(FAKE_CUSTOMER) fake_customer["id"] = "cus_sync_has_bad_subscriber_metadata" fake_customer["metadata"] = {"djstripe_subscriber": "does_not_exist"} customer = Customer.sync_from_stripe_data(fake_customer) self.assertEqual(customer.subscriber, None) self.assertEqual(customer.metadata, {"djstripe_subscriber": "does_not_exist"}) self.assert_fks( customer, expected_blank_fks={"djstripe.Customer.coupon", "djstripe.Customer.subscriber"}, )
def setUp(self): self.settings(ROOT_URLCONF=self.urlconf) self.factory = RequestFactory() self.user = get_user_model().objects.create_user( username="******", email="*****@*****.**" ) self.customer = Customer.sync_from_stripe_data(FAKE_CUSTOMER) self.customer.subscriber = self.user self.customer.save() with patch( "stripe.Product.retrieve", return_value=deepcopy(FAKE_PRODUCT), autospec=True ): self.subscription = Subscription.sync_from_stripe_data(FAKE_SUBSCRIPTION) self.middleware = SubscriptionPaymentMiddleware()
def test_customer_sync_default_source_string(self): Customer.objects.all().delete() Card.objects.all().delete() customer_fake = deepcopy(FAKE_CUSTOMER) customer_fake["default_source"] = customer_fake["sources"]["data"][0][ "id" ] = "card_sync_source_string" customer = Customer.sync_from_stripe_data(customer_fake) self.assertEqual(customer.default_source.id, customer_fake["default_source"]) self.assertEqual(customer.legacy_cards.count(), 2) self.assertEqual(len(list(customer.payment_methods)), 2) self.assert_fks( customer, expected_blank_fks={"djstripe.Customer.coupon", "djstripe.Customer.subscriber"}, )
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 test_customer_sync_has_subscriber_metadata_disabled(self): user = get_user_model().objects.create(username="******", id=98765) fake_customer = deepcopy(FAKE_CUSTOMER) fake_customer["id"] = "cus_test_metadata_disabled" fake_customer["metadata"] = {"djstripe_subscriber": "98765"} with patch( "djstripe.settings.SUBSCRIBER_CUSTOMER_KEY", return_value="", autospec=True ): customer = Customer.sync_from_stripe_data(fake_customer) self.assertNotEqual(customer.subscriber, user) self.assertNotEqual(customer.subscriber_id, 98765) self.assert_fks( customer, expected_blank_fks={"djstripe.Customer.coupon", "djstripe.Customer.subscriber"}, )
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 test_customer_sync_no_sources(self, customer_mock): fake_customer = deepcopy(FAKE_CUSTOMER) fake_customer["id"] = "cus_test_sync_no_sources" fake_customer["default_source"] = None fake_customer["sources"] = None customer_mock.return_value = fake_customer user = get_user_model().objects.create_user(username="******") customer = Customer.create(user) self.assertEqual( customer_mock.call_args_list[0][1].get("metadata"), {"djstripe_subscriber": user.pk} ) self.assertEqual(customer.sources.count(), 0) self.assertEqual(customer.legacy_cards.count(), 0) self.assertEqual(customer.default_source, None) self.assert_fks( customer, expected_blank_fks={"djstripe.Customer.coupon", "djstripe.Customer.default_source"}, )
def test_customer_create_metadata_disabled(self, customer_mock): user = get_user_model().objects.create_user( username="******" ) fake_customer = deepcopy(FAKE_CUSTOMER) fake_customer["id"] = "cus_test_create_metadata_disabled" customer_mock.return_value = fake_customer djstripe_settings.SUBSCRIBER_CUSTOMER_KEY = "" customer = Customer.create(user) djstripe_settings.SUBSCRIBER_CUSTOMER_KEY = "djstripe_subscriber" customer_mock.assert_called_once_with( api_key=STRIPE_SECRET_KEY, email="", idempotency_key=None, metadata={} ) self.assertEqual(customer.metadata, None) self.assert_fks( customer, expected_blank_fks={"djstripe.Customer.coupon", "djstripe.Customer.default_source"}, )
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))