예제 #1
0
    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)
예제 #2
0
파일: views.py 프로젝트: lijielife/darg
    def post(self, request, *args, **kwargs):
        form = PlanForm(request.POST)
        try:
            customer = subscriber_request_callback(request).customer
        except Customer.DoesNotExist as exc:
            error_message = _("You must already be subscribed to a plan before"
                              " you can change it.")
            form.add_error(None, error_message)
            return self.form_invalid(form)

        if form.is_valid():
            plan_name = form.cleaned_data["plan"]

            # check if plan is subscribable
            is_subscribable, errors = customer.subscriber.validate_plan(
                plan_name)
            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)

            try:
                # When a customer upgrades their plan, and
                # DJSTRIPE_PRORATION_POLICY_FOR_UPGRADES is set to True,
                # we force the proration of the current plan and use it towards
                # the upgraded plan, no matter what DJSTRIPE_PRORATION_POLICY
                # is set to.
                prorate = False
                if PRORATION_POLICY_FOR_UPGRADES:
                    current_subscription_amount = (
                        customer.current_subscription.amount)
                    selected_plan = next(plan for plan in PLAN_LIST
                                         if plan.get('plan') == plan_name)
                    selected_plan_price = (selected_plan["price"] /
                                           decimal.Decimal(100))

                    # Is it an upgrade?
                    if selected_plan_price > current_subscription_amount:
                        prorate = True

                # create invoiceitem for shareholders if necessary
                utils.subscriptions.stripe_company_shareholder_invoice_item(
                    customer, plan_name)

                # create invoiceitem for securities if necessary
                utils.subscriptions.stripe_company_security_invoice_item(
                    customer, plan_name)

                customer.subscribe(plan_name, prorate=prorate)
            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)
예제 #3
0
파일: views.py 프로젝트: kirami/Appevate
    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)
예제 #4
0
파일: views.py 프로젝트: lijielife/darg
    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)
예제 #5
0
    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)
예제 #6
0
파일: views.py 프로젝트: kirami/Appevate
 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)
예제 #7
0
    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)
예제 #8
0
    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)
예제 #9
0
    def execute_stripe_payment(self):
        # As per Aslan's request
        # Yearly donations will no longer exist. They are One Time Donations  now.

        stripe_ref = None
        customer, created = Customer.get_or_create(
            subscriber=subscriber_request_callback(self.request))
        if self.plan_type == 'month':
            subscribe_to_plan(customer, self.stripe_token, self.amount,
                              self.plan_type, self.flow_type)
        else:
            stripe_ref = one_time_donation(customer, self.stripe_token,
                                           self.amount)
            if self.product_id:
                # We need to record the product id if donation comes from the Catalog.
                pass

        return stripe_ref
예제 #10
0
파일: views.py 프로젝트: lijielife/darg
    def get(self, request, *args, **kwargs):
        plan_slug = self.kwargs.get('plan')
        if plan_slug not in PAYMENT_PLANS:
            return redirect("djstripe:subscribe",
                            company_id=kwargs.get('company_id'))

        plan = PAYMENT_PLANS[plan_slug]
        customer, created = Customer.get_or_create(
            subscriber=subscriber_request_callback(self.request))

        if (hasattr(customer, "current_subscription")
                and customer.current_subscription.plan == plan['plan']
                and (customer.current_subscription.status !=
                     CurrentSubscription.STATUS_CANCELLED)):
            message = _("You already subscribed to this plan")
            messages.info(request, message, fail_silently=True)
            return redirect("djstripe:subscribe",
                            company_id=kwargs.get('company_id'))

        return super(ConfirmFormView, self).get(request, *args, **kwargs)
예제 #11
0
    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))
                customer.update_card(self.request.POST.get("stripe_token"))
                customer.subscribe(form.cleaned_data["plan"])
            except stripe.StripeError as e:
                # add form error here
                self.error = e.args[0]
                return self.form_invalid(form)

            # redirect to confirmation page
            return self.form_valid(form)
        else:
            return self.form_invalid(form)
예제 #12
0
    def post(self, request, format=None):
        """
        Create a new current subscription for the user.
        Returns with status code 201.
        """

        serializer = CreateSubscriptionSerializer(data=request.data)

        if serializer.is_valid():
            try:
                customer, created = Customer.get_or_create(
                    subscriber=subscriber_request_callback(self.request))
                customer.update_card(serializer.data["stripe_token"])
                customer.subscribe(serializer.data["plan"])
                return Response(serializer.data,
                                status=status.HTTP_201_CREATED)

            except:
                # TODO
                # Better error messages
                return Response("Something went wrong processing the payment.",
                                status=status.HTTP_400_BAD_REQUEST)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
예제 #13
0
def user_settings_view_new(request):

    profile_updated = False
    # if this is a POST request we need to process the form data
    if 'edit_profile' in request.POST:
        # create a form instance and populate it with data from the request:
        edit_profile_form = EditProfileForm(data=request.POST,
                                            user=request.user)
        # check whether it's valid:
        if edit_profile_form.is_valid():
            edit_profile_form.save(request)
            messages.success(request,
                             "You've successfully updated your profile.")
            profile_updated = True
    # if a GET (or any other method) we'll create a blank form
    else:
        edit_profile_form = EditProfileForm(user=request.user)

    if 'edit_active_card' in request.POST:
        try:
            stripe_token = request.POST.get('stripe_token')
            customer, created = Customer.get_or_create(
                subscriber=subscriber_request_callback(request))
            update_active_card(customer, stripe_token)
        except stripe.StripeError as e:
            # add form error here
            return _ajax_response(
                request, JsonResponse({'error': e.args[0]}, status=500))

        messages.success(request,
                         'Your account card has been changed successfully.')
        profile_updated = True

    if 'change_email' in request.POST:
        change_email_form = ChangeEmailForm(data=request.POST,
                                            user=request.user)
        if change_email_form.is_valid():
            change_email_form.save(request)
            messages.success(
                request, 'Your email address has been changed successfully.')
            profile_updated = True
    else:
        change_email_form = ChangeEmailForm(user=request.user)

    if 'change_password' in request.POST:
        change_password_form = ChangePasswordForm(data=request.POST,
                                                  user=request.user)
        if change_password_form.is_valid():
            change_password_form.save()
            messages.success(request,
                             'Your password has been changed successfully.')
            profile_updated = True
    else:
        change_password_form = ChangePasswordForm(user=request.user)

    # if this is a POST request we need to process the form data
    if 'artist_info' in request.POST:
        # create a form instance and populate it with data from the request:
        artist_info_form = ArtistInfoForm(data=request.POST,
                                          instance=request.user)
        # check whether it's valid:
        if artist_info_form.is_valid():
            artist_info_form.save(request)
            messages.success(request,
                             "You've successfully updated your profile.")
            profile_updated = True
        else:
            assert False, artist_info_form.errors
    # if a GET (or any other method) we'll create a blank form
    else:
        artist_info_form = ArtistInfoForm(instance=request.user)

    if 'billing_info' in request.POST:
        billing_address_form = BillingAddressForm(None, request.user,
                                                  request.POST)
        if billing_address_form.is_valid():
            billing_address_form.save()
            profile_updated = True
        else:
            billing_address_form = BillingAddressForm(None, request.user, None)

    if profile_updated:
        return HttpResponseRedirect('/accounts/settings/')

    plan = None
    period_end = {}
    period_end['date'] = None

    customer_detail = None
    customer_charges = None
    user_archive_access_until = None
    monthly_pledge_in_dollars = None
    cancel_at = None
    billing_address = None

    show_email_confirmation = False

    try:
        customer = request.user.customer
    except:
        customer = None

    user_archive_access_until = None
    if request.user.has_archive_access:
        user_archive_access_until = request.user.get_archive_access_expiry_date(
        )

    if customer and customer.has_active_subscription():
        plan_id = request.user.customer.current_subscription.plan
        try:
            plan = stripe.Plan.retrieve(id=plan_id)
        except stripe.error.InvalidRequestError:
            plan = None

    customer_charges = request.user.get_donations().order_by('-date')
    charges_value = 0
    for charge in customer_charges:
        if charge.amount:
            charges_value = charges_value + charge.amount

        artist_info_form = ArtistInfoForm(instance=request.user)
    customer_detail = CustomerDetail.get(id=request.user.customer.stripe_id)

    if customer_detail and customer_detail.subscription:
        monthly_pledge_in_dollars = customer_detail.subscription.plan.amount / 100

    if customer_detail and customer_detail.subscription:
        period_end["date"] = datetime.fromtimestamp(
            customer_detail.subscription.current_period_end).strftime(
                "%d/%m/%y")
        period_end["due"] = datetime.fromtimestamp(
            customer_detail.subscription.current_period_end) <= datetime.now()

    if customer_detail and customer_detail.subscription and customer_detail.subscriptions.data:
        cancel_at = customer_detail.subscriptions.data[0][
            'cancel_at_period_end']
    else:
        cancel_at = False

    try:
        billing_address = request.user.addresses.get(
            is_default_for_billing=True)
    except UserAddress.DoesNotExist:
        try:
            billing_address = request.user.addresses.first()
        except UserAddress.DoesNotExist:
            billing_address = UserAddress()

    return render(
        request, 'account/user_settings_new.html', {
            'STRIPE_PUBLIC_KEY': settings.STRIPE_PUBLIC_KEY,
            'change_email_form': change_email_form,
            'change_profile_form': edit_profile_form,
            'change_password_form': change_password_form,
            'current_user': request.user,
            'artist_info_form': artist_info_form,
            'plan': plan,
            'donations': request.user.get_donations() or None,
            'customer_detail': customer_detail or '',
            'customer_charges': customer_charges or '',
            'charges_value': request.user.get_donation_amount or '0',
            'period_end': period_end,
            'user_archive_access_until': user_archive_access_until
            or 'unverified account',
            'monthly_pledge_in_dollars': monthly_pledge_in_dollars or 'no',
            'cancelled': cancel_at or '',
            'donate_url': reverse('donate'),
            'billing_address': billing_address or '',
            'show_email_confirmation_dialog': show_email_confirmation
        })
예제 #14
0
파일: views.py 프로젝트: lijielife/darg
 def post(self, request, *args, **kwargs):
     context = dict(customer=sync_subscriber(
         settings.subscriber_request_callback(request)))
     return render(request, self.template_name, context)