Beispiel #1
0
    def post(self, *args, **kwargs):
        membership = self.get_object()
        membership.deactivate()
        messages.add_message(self.request, messages.SUCCESS,
                             self.success_message)
        # cancel Stripe subscription
        stripe_utils = StripeUtils()
        membership_order = MembershipOrder.objects.filter(
            customer__user=self.request.user).last()
        if membership_order:
            if membership_order.stripe_subscription_id:
                result = stripe_utils.unsubscribe_customer(
                    subscription_id=membership_order.stripe_subscription_id)
                stripe_subscription_obj = result.get('response_object')
                # Check if the subscription was canceled
                if (stripe_subscription_obj is None
                        or stripe_subscription_obj.status != 'canceled'):
                    error_msg = result.get('error')
                    logger.error(
                        "Could not cancel Digital Glarus subscription. "
                        "Reason: {reason}".format(reason=error_msg))
            else:
                logger.error(
                    "User {user} may have Stripe subscriptions created "
                    "manually. Please check.".format(
                        user=self.request.user.name))
        else:
            logger.error("MembershipOrder for {user} not found".format(
                user=self.request.user.name))

        return HttpResponseRedirect(self.success_url)
Beispiel #2
0
 def get(self, request, *args, **kwargs):
     context = {}
     if 'specs' not in request.session or 'user' not in request.session:
         return HttpResponseRedirect(reverse('datacenterlight:index'))
     if 'token' in self.request.session:
         token = self.request.session['token']
         stripe_utils = StripeUtils()
         card_details = stripe_utils.get_cards_details_from_token(
             token
         )
         if not card_details.get('response_object'):
             return HttpResponseRedirect(reverse('hosting:payment'))
         card_details_response = card_details['response_object']
         context['cc_last4'] = card_details_response['last4']
         context['cc_brand'] = card_details_response['brand']
     else:
         card_id = self.request.session.get('card_id')
         card_detail = UserCardDetail.objects.get(id=card_id)
         context['cc_last4'] = card_detail.last4
         context['cc_brand'] = card_detail.brand
     context.update({
         'site_url': reverse('datacenterlight:index'),
         'vm': request.session.get('specs'),
         'page_header_text': _('Confirm Order'),
         'billing_address_data': (
             request.session.get('billing_address_data')
         ),
         'cms_integration': get_cms_integration('default'),
     })
     return render(request, self.template_name, context)
Beispiel #3
0
    def get_or_create(cls, email=None, token=None):
        """
            Check if there is a registered stripe customer with that email
            or create a new one
        """
        stripe_customer = None
        try:
            stripe_utils = StripeUtils()
            stripe_customer = cls.objects.get(user__email=email)
            # check if user is not in stripe but in database
            stripe_utils.check_customer(stripe_customer.stripe_id, stripe_customer.user, token)
            return stripe_customer

        except StripeCustomer.DoesNotExist:
            user = CustomUser.objects.get(email=email)

            stripe_utils = StripeUtils()
            stripe_data = stripe_utils.create_customer(token, email)
            if stripe_data.get("response_object"):
                stripe_cus_id = stripe_data.get("response_object").get("id")

                stripe_customer = StripeCustomer.objects.create(user=user, stripe_id=stripe_cus_id)

                return stripe_customer
            else:
                return None
 def handle(self, *args, **options):
     try:
         stripe_utils = StripeUtils()
         for user in CustomUser.objects.all():
             if hasattr(user, 'stripecustomer'):
                 if user.stripecustomer:
                     card_details_resp = stripe_utils.get_card_details(
                         user.stripecustomer.stripe_id)
                     card_details = card_details_resp['response_object']
                     if card_details:
                         ucd = UserCardDetail.get_or_create_user_card_detail(
                             stripe_customer=user.stripecustomer,
                             card_details=card_details)
                         UserCardDetail.save_default_card_local(
                             user.stripecustomer.stripe_id, ucd.card_id)
                         print("Saved user card details for {}".format(
                             user.email))
                     else:
                         print(" --- Could not get card details for "
                               "{}".format(user.email))
                         print(" --- Error: {}".format(
                             card_details_resp['error']))
             else:
                 print(
                     " === {} does not have a StripeCustomer object".format(
                         user.email))
     except Exception as e:
         print(" *** Error occurred. Details {}".format(str(e)))
Beispiel #5
0
 def set_default_card_from_stripe(stripe_api_cus_id):
     stripe_utils = StripeUtils()
     cus_response = stripe_utils.get_customer(stripe_api_cus_id)
     cu = cus_response['response_object']
     default_source = cu.default_source
     if default_source is not None:
         UserCardDetail.save_default_card_local(stripe_api_cus_id,
                                                default_source)
Beispiel #6
0
    def form_valid(self, form):
        token = form.cleaned_data.get('token')
        user = self.request.user
        customer = user.stripecustomer
        stripe_utls = StripeUtils()
        card_response = stripe_utls.update_customer_card(
            customer.stripe_id, token)
        new_card_data = card_response.get('response_object')
        self.request.session.update({'new_change_credit_card': new_card_data})

        return super(EditCreditCardView, self).form_valid(form)
Beispiel #7
0
    def form_valid(self, form):
        token = form.cleaned_data.get('token')
        user = self.request.user
        customer = user.stripecustomer
        stripe_utls = StripeUtils()
        card_response = stripe_utls.update_customer_card(customer.stripe_id, token)
        new_card_data = card_response.get('response_object')
        self.request.session.update({
            'new_change_credit_card': new_card_data
        })

        return super(EditCreditCardView, self).form_valid(form)
Beispiel #8
0
    def get_or_create(cls, email=None, token=None):
        """
            Check if there is a registered stripe customer with that email
            or create a new one
        """
        stripe_customer = None
        try:
            stripe_utils = StripeUtils()
            stripe_customer = cls.objects.get(user__email=email)
            # check if user is not in stripe but in database
            customer = stripe_utils.check_customer(stripe_customer.stripe_id,
                                                   stripe_customer.user, token)

            if not customer.sources.data:
                stripe_utils.update_customer_token(customer, token)
            return stripe_customer

        except StripeCustomer.DoesNotExist:
            user = CustomUser.objects.get(email=email)

            stripe_utils = StripeUtils()
            stripe_data = stripe_utils.create_customer(token, email)
            if stripe_data.get('response_object'):
                stripe_cus_id = stripe_data.get('response_object').get('id')

                stripe_customer = StripeCustomer.objects.\
                    create(user=user, stripe_id=stripe_cus_id)

                return stripe_customer
            else:
                return None
Beispiel #9
0
 def test_get_stripe_plan_id_string(self):
     plan_id_string = StripeUtils.get_stripe_plan_id(cpu=2,
                                                     ram=20,
                                                     ssd=100,
                                                     version=1,
                                                     app='dcl')
     self.assertEqual(plan_id_string, 'dcl-v1-cpu-2-ram-20gb-ssd-100gb')
     plan_id_string = StripeUtils.get_stripe_plan_id(cpu=2,
                                                     ram=20,
                                                     ssd=100,
                                                     version=1,
                                                     app='dcl',
                                                     hdd=200)
     self.assertEqual(plan_id_string,
                      'dcl-v1-cpu-2-ram-20gb-ssd-100gb-hdd-200gb')
Beispiel #10
0
 def get(self, request, time=None):
     context = self._get_context(request, time)
     next = request.session.get('next')
     if next == 1 or next ==0:
         template = 'templates/creditcard.html'
         request.session['next'] +=1
     elif next == 2:
         customer = StripeCustomer.get_or_create(email=request.user.email,token=request.session['token'])
         stripe_utils = StripeUtils()
         charge = stripe_utils.make_charge(request.session['amount'],customer=customer.stripe_id)
         template = 'templates/validated.html'
         resp = charge.get('response_object')            
         context['msg'] = resp.get('status',None) 
         request.session['next'] = None
     return render(request, template, context)
Beispiel #11
0
 def set_default_card(stripe_api_cus_id, stripe_source_id):
     """
     Sets the given stripe source as the default source for the given
     Stripe customer
     :param stripe_api_cus_id: Stripe customer id
     :param stripe_source_id: The Stripe source id
     :return:
     """
     stripe_utils = StripeUtils()
     cus_response = stripe_utils.get_customer(stripe_api_cus_id)
     cu = cus_response['response_object']
     cu.default_source = stripe_source_id
     cu.save()
     UserCardDetail.save_default_card_local(stripe_api_cus_id,
                                            stripe_source_id)
Beispiel #12
0
class TestStripeCustomerDescription(TestCase):
    """
    A class to test setting the description field of the stripe customer
    https://stripe.com/docs/api#metadata
    """
    def setUp(self):
        self.customer_password = '******'
        self.customer_email = '*****@*****.**'
        self.customer_name = "Monty Python"
        self.customer = mommy.make('membership.CustomUser')
        self.customer.set_password(self.customer_password)
        self.customer.email = self.customer_email
        self.customer.save()
        self.stripe_utils = StripeUtils()
        stripe.api_key = settings.STRIPE_API_PRIVATE_KEY_TEST
        self.token = stripe.Token.create(card={
            "number": '4111111111111111',
            "exp_month": 12,
            "exp_year": 2022,
            "cvc": '123'
        }, )
        self.failed_token = stripe.Token.create(card={
            "number": '4000000000000341',
            "exp_month": 12,
            "exp_year": 2022,
            "cvc": '123'
        }, )

    def test_creating_stripe_customer(self):
        stripe_data = self.stripe_utils.create_customer(
            self.token.id, self.customer.email, self.customer_name)
        self.assertEqual(stripe_data.get('error'), None)
        customer_data = stripe_data.get('response_object')
        self.assertEqual(customer_data.description, self.customer_name)
Beispiel #13
0
 def get(self, request, *args, **kwargs):
     if 'specs' not in request.session or 'user' not in request.session:
         return HttpResponseRedirect(reverse('datacenterlight:index'))
     if 'token' not in request.session:
         return HttpResponseRedirect(reverse('datacenterlight:payment'))
     stripe_customer_id = request.session.get('customer')
     customer = StripeCustomer.objects.filter(id=stripe_customer_id).first()
     stripe_utils = StripeUtils()
     card_details = stripe_utils.get_card_details(
         customer.stripe_id, request.session.get('token'))
     context = {
         'site_url': reverse('datacenterlight:index'),
         'cc_last4': card_details.get('response_object').get('last4'),
         'cc_brand': card_details.get('response_object').get('brand')
     }
     return render(request, self.template_name, context)
Beispiel #14
0
 def get(self, request, time=None):
     context = self._get_context(request, time)
     next = request.session.get('next')
     if next == 1 or next == 0:
         template = 'templates/creditcard.html'
         request.session['next'] += 1
     elif next == 2:
         customer = StripeCustomer.get_or_create(
             email=request.user.email, token=request.session['token'])
         stripe_utils = StripeUtils()
         charge = stripe_utils.make_charge(request.session['amount'],
                                           customer=customer.stripe_id)
         template = 'templates/validated.html'
         resp = charge.get('response_object')
         context['msg'] = resp.get('status', None)
         request.session['next'] = None
     return render(request, template, context)
Beispiel #15
0
 def create_stripe_api_customer(cls,
                                email=None,
                                token=None,
                                customer_name=None):
     """
         This method creates a Stripe API customer with the given
         email, token and customer_name. This is different from
         get_or_create method below in that it does not create a
         CustomUser and associate the customer created in stripe
         with it, while get_or_create does that before creating the
         stripe user.
     """
     stripe_utils = StripeUtils()
     stripe_data = stripe_utils.create_customer(token, email, customer_name)
     if stripe_data.get('response_object'):
         stripe_cus_id = stripe_data.get('response_object').get('id')
         return stripe_cus_id
     else:
         return None
Beispiel #16
0
 def setUp(self):
     self.customer_password = '******'
     self.customer_email = '*****@*****.**'
     self.customer_name = "Monty Python"
     self.user = {'email': self.customer_email, 'name': self.customer_name}
     self.customer = mommy.make('membership.CustomUser')
     self.customer.set_password(self.customer_password)
     self.customer.email = self.customer_email
     self.customer.save()
     self.stripe_utils = StripeUtils()
     stripe.api_key = settings.STRIPE_API_PRIVATE_KEY_TEST
     self.token = stripe.Token.create(card={
         "number": '4111111111111111',
         "exp_month": 12,
         "exp_year": 2022,
         "cvc": '123'
     }, )
     # Run fetchvmtemplates so that we have the VM templates from
     # OpenNebula
     call_command('fetchvmtemplates')
Beispiel #17
0
 def get_or_create(cls, email=None, token=None):
     """
         Check if there is a registered stripe customer with that email
         or create a new one
     """
     try:
         stripe_utils = StripeUtils()
         stripe_customer = cls.objects.get(user__email=email)
         # check if user is not in stripe but in database
         customer = stripe_utils.check_customer(stripe_customer.stripe_id,
                                                stripe_customer.user, token)
         if "deleted" in customer and customer["deleted"]:
             raise StripeCustomer.DoesNotExist()
         return stripe_customer
     except StripeCustomer.DoesNotExist:
         user = CustomUser.objects.get(email=email)
         stripe_utils = StripeUtils()
         stripe_data = stripe_utils.create_customer(token, email, user.name)
         if stripe_data.get('response_object'):
             stripe_cus_id = stripe_data.get('response_object').get('id')
             if hasattr(user, 'stripecustomer'):
                 # User already had a Stripe account and we are here
                 # because the account was deleted in dashboard
                 # So, we simply update the stripe_id
                 user.stripecustomer.stripe_id = stripe_cus_id
                 user.stripecustomer.save()
                 stripe_customer = user.stripecustomer
             else:
                 # The user never had an associated Stripe account
                 # So, create one
                 stripe_customer = StripeCustomer.objects.create(
                     user=user, stripe_id=stripe_cus_id)
             return stripe_customer
         else:
             return None
Beispiel #18
0
 def setUp(self):
     self.customer_password = '******'
     self.customer_email = '*****@*****.**'
     self.customer_name = "Monty Python"
     self.customer = mommy.make('membership.CustomUser')
     self.customer.set_password(self.customer_password)
     self.customer.email = self.customer_email
     self.customer.save()
     self.stripe_utils = StripeUtils()
     stripe.api_key = settings.STRIPE_API_PRIVATE_KEY_TEST
     self.token = stripe.Token.create(card={
         "number": '4111111111111111',
         "exp_month": 12,
         "exp_year": 2022,
         "cvc": '123'
     }, )
     self.failed_token = stripe.Token.create(card={
         "number": '4000000000000341',
         "exp_month": 12,
         "exp_year": 2022,
         "cvc": '123'
     }, )
Beispiel #19
0
    def post(self, request, *args, **kwargs):
        form = self.get_form()
        if form.is_valid():

            # Get billing address data
            billing_address_data = form.cleaned_data

            context = self.get_context_data()

            template = request.session.get('template')
            specs = request.session.get('specs')

            vm_template_id = template.get('id', 1)

            final_price = specs.get('price')

            token = form.cleaned_data.get('token')

            owner = self.request.user

            # Get or create stripe customer
            customer = StripeCustomer.get_or_create(email=owner.email,
                                                    token=token)
            if not customer:
                form.add_error("__all__", "Invalid credit card")
                return self.render_to_response(self.get_context_data(form=form))

            # Create Billing Address
            billing_address = form.save()

            # Make stripe charge to a customer
            stripe_utils = StripeUtils()
            charge_response = stripe_utils.make_charge(amount=final_price,
                                                       customer=customer.stripe_id)
            charge = charge_response.get('response_object')

            # Check if the payment was approved
            if not charge:
                context.update({
                    'paymentError': charge_response.get('error'),
                    'form': form
                })
                return render(request, self.template_name, context)

            charge = charge_response.get('response_object')

            # Create OpenNebulaManager
            manager = OpenNebulaManager(email=owner.email,
                                        password=owner.password)
            # Get user ssh key
            if not UserHostingKey.objects.filter( user=self.request.user).exists():
                context.update({
                    'sshError': 'error',
                    'form': form
                })
                return render(request, self.template_name, context)
            # For now just get first one
            user_key = UserHostingKey.objects.filter(
                    user=self.request.user).first()
            
            # Create a vm using logged user
            vm_id = manager.create_vm(
                template_id=vm_template_id,
                # XXX: Confi
                specs=specs,
                ssh_key=user_key.public_key,
            )

            # Create a Hosting Order
            order = HostingOrder.create(
                price=final_price,
                vm_id=vm_id,
                customer=customer,
                billing_address=billing_address
            )

            # Create a Hosting Bill
            bill = HostingBill.create(
                customer=customer, billing_address=billing_address)

            # Create Billing Address for User if he does not have one
            if not customer.user.billing_addresses.count():
                billing_address_data.update({
                    'user': customer.user.id
                })
                billing_address_user_form = UserBillingAddressForm(
                    billing_address_data)
                billing_address_user_form.is_valid()
                billing_address_user_form.save()

            # Associate an order with a stripe payment
            order.set_stripe_charge(charge)

            # If the Stripe payment was successed, set order status approved
            order.set_approved()

            vm = VirtualMachineSerializer(manager.get_vm(vm_id)).data

            # Send notification to ungleich as soon as VM has been booked
            context = {
                'vm': vm,
                'order': order,
                'base_url': "{0}://{1}".format(request.scheme, request.get_host())

            }
            email_data = {
                'subject': 'New VM request',
                'to': request.user.email,
                'context': context,
                'template_name': 'new_booked_vm',
                'template_path': 'hosting/emails/'
            }
            email = BaseEmail(**email_data)
            email.send()

            return HttpResponseRedirect(reverse('hosting:orders', kwargs={'pk': order.id}))
        else:
            return self.form_invalid(form)
Beispiel #20
0
    def post(self, request, *args, **kwargs):
        form = self.get_form()

        if form.is_valid():
            data = form.cleaned_data
            context = self.get_context_data()
            token = data.get('token')
            membership_type = data.get('membership_type')

            # Get or create stripe customer
            customer = StripeCustomer.get_or_create(email=self.request.user.email,
                                                    token=token)
            if not customer:
                form.add_error("__all__", "Invalid credit card")
                return self.render_to_response(self.get_context_data(form=form))

            # Make stripe charge to a customer
            stripe_utils = StripeUtils()
            charge_response = stripe_utils.make_charge(amount=membership_type.first_month_price,
                                                       customer=customer.stripe_id)
            charge = charge_response.get('response_object')

            # Check if the payment was approved
            if not charge:
                context.update({
                    'paymentError': charge_response.get('error'),
                    'form': form
                })
                return render(request, self.template_name, context)

            charge = charge_response.get('response_object')

            # Create Billing Address
            billing_address = form.save()

            # Create Billing Address for User if he does not have one
            if not customer.user.billing_addresses.count():
                data.update({
                    'user': customer.user.id
                })
                billing_address_user_form = UserBillingAddressForm(data)
                billing_address_user_form.is_valid()
                billing_address_user_form.save()

            # Get membership dates
            membership_start_date, membership_end_date = membership_type.first_month_range

            # Create membership plan
            membership_data = {
                'type': membership_type,
                'start_date': membership_start_date,
                'end_date': membership_end_date
            }
            membership = Membership.create(membership_data)

            # Create membership order
            order_data = {
                'membership': membership,
                'customer': customer,
                'billing_address': billing_address,
                'stripe_charge': charge,
                'amount': membership_type.first_month_price,
                'start_date': membership_start_date,
                'end_date': membership_end_date
            }

            membership_order = MembershipOrder.create(order_data)

            request.session.update({
                'membership_price': membership.type.first_month_price,
                'membership_dates': membership.type.first_month_formated_range
            })

            context = {
                'membership': membership,
                'order': membership_order,
                'membership_start_date': membership_start_date,
                'membership_end_date': membership_end_date,
                'base_url': "{0}://{1}".format(request.scheme, request.get_host())

            }
            email_data = {
                'subject': 'Your membership has been charged',
                'to': request.user.email,
                'context': context,
                'template_name': 'membership_charge',
                'template_path': 'digitalglarus/emails/'
            }
            email = BaseEmail(**email_data)
            email.send()

            return HttpResponseRedirect(reverse('digitalglarus:membership_activated'))

        else:
            return self.form_invalid(form)
Beispiel #21
0
    def form_valid(self, form):
        data = form.cleaned_data
        context = self.get_context_data()
        token = data.get('token')
        start_date = data.get('start_date')
        end_date = data.get('end_date')
        is_free = context.get('is_free')
        normal_price, final_price, free_days = Booking.\
            booking_price(self.request.user, start_date, end_date)
        charge = None

        # if not credit_card_needed:
        # Get or create stripe customer
        customer = StripeCustomer.get_or_create(email=self.request.user.email,
                                                token=token)
        if not customer:
            form.add_error("__all__", "Invalid credit card")
            return self.render_to_response(self.get_context_data(form=form))

        # If booking is not free, make the stripe charge
        if not is_free:
            # Make stripe charge to a customer
            stripe_utils = StripeUtils()
            charge_response = stripe_utils.make_charge(amount=final_price,
                                                       customer=customer.stripe_id)
            charge = charge_response.get('response_object')

            # Check if the payment was approved
            if not charge:
                context.update({
                    'paymentError': charge_response.get('error'),
                    'form': form
                })
                return render(self.request, self.template_name, context)

            charge = charge_response.get('response_object')

        # Create Billing Address for Membership Order
        billing_address = form.save()

        # Create Billing Address for User if he does not have one
        if not customer.user.billing_addresses.count():
            data.update({
                'user': customer.user.id
            })
            billing_address_user_form = UserBillingAddressForm(data)
            billing_address_user_form.is_valid()
            billing_address_user_form.save()

        # Create Booking
        booking_data = {
            'start_date': start_date,
            'end_date': end_date,
            'start_date': start_date,
            'free_days': free_days,
            'price': normal_price,
            'final_price': final_price,
        }
        booking = Booking.create(booking_data)

        # Create Booking order
        order_data = {
            'booking': booking,
            'customer': customer,
            'billing_address': billing_address,
            'stripe_charge': charge,
            'amount': final_price,
            'original_price': normal_price,
            'special_month_price': BookingPrice.objects.last().special_month_price,
        }
        order = BookingOrder.create(order_data)

        return HttpResponseRedirect(self.get_success_url(order.id))
Beispiel #22
0
    def post(self, request, *args, **kwargs):
        template = request.session.get('template')
        specs = request.session.get('specs')
        user = request.session.get('user')
        stripe_customer_id = request.session.get('customer')
        customer = StripeCustomer.objects.filter(id=stripe_customer_id).first()
        billing_address_data = request.session.get('billing_address_data')
        billing_address_id = request.session.get('billing_address')
        billing_address = BillingAddress.objects.filter(
            id=billing_address_id).first()
        vm_template_id = template.get('id', 1)
        final_price = specs.get('price')

        # Make stripe charge to a customer
        stripe_utils = StripeUtils()
        charge_response = stripe_utils.make_charge(amount=final_price,
                                                   customer=customer.stripe_id)
        charge = charge_response.get('response_object')

        # Check if the payment was approved
        if not charge:
            context = {}
            context.update({'paymentError': charge_response.get('error')})
            return render(request, self.payment_template_name, context)

        charge = charge_response.get('response_object')

        # Create OpenNebulaManager
        manager = OpenNebulaManager(email=settings.OPENNEBULA_USERNAME,
                                    password=settings.OPENNEBULA_PASSWORD)

        # Create a vm using oneadmin, also specify the name
        vm_id = manager.create_vm(
            template_id=vm_template_id,
            specs=specs,
            vm_name="{email}-{template_name}-{date}".format(
                email=user.get('email'),
                template_name=template.get('name'),
                date=int(datetime.now().strftime("%s"))))

        # Create a Hosting Order
        order = HostingOrder.create(price=final_price,
                                    vm_id=vm_id,
                                    customer=customer,
                                    billing_address=billing_address)

        # Create a Hosting Bill
        HostingBill.create(customer=customer, billing_address=billing_address)

        # Create Billing Address for User if he does not have one
        if not customer.user.billing_addresses.count():
            billing_address_data.update({'user': customer.user.id})
            billing_address_user_form = UserBillingAddressForm(
                billing_address_data)
            billing_address_user_form.is_valid()
            billing_address_user_form.save()

        # Associate an order with a stripe payment
        order.set_stripe_charge(charge)

        # If the Stripe payment was successed, set order status approved
        order.set_approved()

        vm = VirtualMachineSerializer(manager.get_vm(vm_id)).data

        context = {
            'name': user.get('name'),
            'email': user.get('email'),
            'cores': specs.get('cpu'),
            'memory': specs.get('memory'),
            'storage': specs.get('disk_size'),
            'price': specs.get('price'),
            'template': template.get('name'),
            'vm.name': vm['name'],
            'vm.id': vm['vm_id'],
            'order.id': order.id
        }
        email_data = {
            'subject': settings.DCL_TEXT + " Order from %s" % context['email'],
            'from_email': settings.DCL_SUPPORT_FROM_ADDRESS,
            'to': ['*****@*****.**'],
            'body':
            "\n".join(["%s=%s" % (k, v) for (k, v) in context.items()]),
            'reply_to': [context['email']],
        }
        email = EmailMessage(**email_data)
        email.send()
        request.session['order_confirmation'] = True
        return HttpResponseRedirect(reverse('datacenterlight:order_success'))
Beispiel #23
0
    def post(self, request, *args, **kwargs):
        form = self.get_form()

        if form.is_valid():
            context = self.get_context_data()
            token = form.cleaned_data.get('token')
            donation_amount = form.cleaned_data.get('donation_amount')

            # Get or create stripe customer
            customer = StripeCustomer.get_or_create(email=self.request.user.email,
                                                    token=token)
            if not customer:
                form.add_error("__all__", "Invalid credit card")
                return self.render_to_response(self.get_context_data(form=form))

            # Create Billing Address
            billing_address = form.save()

            # Make stripe charge to a customer
            stripe_utils = StripeUtils()
            stripe_utils.CURRENCY = 'usd'
            charge_response = stripe_utils.make_charge(amount=donation_amount,
                                                       customer=customer.stripe_id)
            charge = charge_response.get('response_object')

            # Check if the payment was approved
            if not charge:
                context.update({
                    'paymentError': charge_response.get('error'),
                    'form': form
                })
                return render(request, self.template_name, context)

            # Create a donation
            charge = charge_response.get('response_object')
            donation_data = request.POST.copy()
            donation_data.update({
                'cc_brand': charge.source.brand,
                'stripe_charge_id': charge.id,
                'last4': charge.source.last4,
                'billing_address': billing_address.id,
                'donator': customer.id,
                'donation': donation_amount
            })
            donation_form = DonationForm(donation_data)
            if donation_form.is_valid():

                # reactivate donation status
                donation = donation_form.save()

                try:
                    donator_status = DonatorStatus.objects.get(user=self.request.user)
                    donator_status.set_active()
                except DonatorStatus.DoesNotExist:
                    pass

                donation = donation_form.save()

                context = {
                    'donation': donation,
                    'base_url': "{0}://{1}".format(request.scheme, request.get_host())

                }
                email_data = {
                    'subject': 'Your donation have been charged',
                    'to': request.user.email,
                    'context': context,
                    'template_name': 'donation_charge',
                    'template_path': 'nosystemd/emails/'
                }
                email = BaseEmail(**email_data)
                email.send()

                return HttpResponseRedirect(reverse('nosystemd:donations',
                                                    kwargs={'pk': donation.id}))
            else:
                self.form_invalid(donation_form)

        else:
            return self.form_invalid(form)
    def handle(self, *args, **options):
        translation.activate('en-us')
        memberships_orders = MembershipOrder.objects.filter(membership__active=True)
        current_month = datetime.now().month
        current_year = datetime.now().year

        print("--------- STARTING MEMBERSHIP CHARGING SCRIPT  ---------")
        print("Memberhips date: %s-%s" % (current_month, current_year))

        for membership_order in memberships_orders:
            member = membership_order.customer
            try:
                MembershipOrder.objects.get(created_at__month=current_month,
                                            created_at__year=current_year,
                                            customer=member)
            except MembershipOrder.DoesNotExist:
                try:
                    current_membership_price = membership_order.membership.type.price

                    last_membership_order = MembershipOrder.objects.filter(customer=member).last()

                    # Make stripe charge to a customer
                    stripe_utils = StripeUtils()
                    stripe_utils.CURRENCY = self.CURRENCY
                    charge_response = stripe_utils.make_charge(amount=current_membership_price,
                                                               customer=member.stripe_id)
                    charge = charge_response.get('response_object')
                    # Check if the payment was approved
                    if not charge:
                        # There is an error trying to creating the stripe charge
                        context = {
                            'paymentError': charge_response.get('error'),
                        }
                        print("--------- STRIPE PAYMENT ERROR ---------")
                        print(context)
                        print("-------------------------")
                        continue

                    # Create a donation
                    charge = charge_response.get('response_object')
                    membership_order_data = {
                        'cc_brand': charge.source.brand,
                        'stripe_charge_id': charge.id,
                        'last4': charge.source.last4,
                        'membership': last_membership_order.membership.id,
                        'billing_address': last_membership_order.billing_address.id,
                        'customer': member.id,
                        'amount': current_membership_price
                    }
                    membership_order_form = MembershipOrderForm(membership_order_data)
                    if membership_order_form.is_valid():
                        membership_order = membership_order_form.save()

                        context = {
                            'order': membership_order,
                            'base_url': "{0}://{1}".format('https', 'dynamicweb.ungleich.ch')

                        }
                        email_data = {
                            'subject': 'Your monthly membership has been charged',
                            'to': member.user.email,
                            'context': context,
                            'template_name': 'membership_monthly_charge',
                            'template_path': 'digitalglarus/emails/'
                        }
                        email = BaseEmail(**email_data)
                        email.send()

                        print("--------- PAYMENT DONATION SUCCESSFULL ---------")
                        print("Member: %s" % member.user.email)
                        print("Amount: %s %s" % (current_membership_price, self.CURRENCY))
                        print("-----------------------------------------------")

                except Exception as e:
                    print("--------- ERROR ---------")
                    print(e)
                    print("-------------------------")
                    continue
    def handle(self, *args, **options):
        donators = DonatorStatus.objects.filter(status=DonatorStatus.ACTIVE)
        current_month = datetime.now().month
        current_year = datetime.now().year

        print("--------- STARTING DONATIONS SCRIPT  ---------")
        print("Donations date: %s-%s" % (current_month, current_year))

        for donator_status in donators:
            donator = donator_status.user.stripecustomer
            try:
                Donation.objects.get(created_at__month=current_month,
                                     created_at__year=current_year,
                                     donator=donator)
            except Donation.DoesNotExist:
                try:
                    # Get donator last donation amount
                    last_donation = Donation.objects.filter(donator=donator).last()
                    donation_amount = last_donation.donation

                    # Make stripe charge to a customer
                    stripe_utils = StripeUtils()
                    stripe_utils.CURRENCY = self.CURRENCY
                    charge_response = stripe_utils.make_charge(amount=donation_amount,
                                                               customer=donator.stripe_id)
                    charge = charge_response.get('response_object')

                    # Check if the payment was approved
                    if not charge:
                        # There is an error trying to creating the stripe charge
                        context = {
                            'paymentError': charge_response.get('error'),
                        }
                        print("--------- STRIPE PAYMENT ERROR ---------")
                        print(context)
                        print("-------------------------")
                        continue
                    # Create a donation
                    charge = charge_response.get('response_object')
                    donation_data = {
                        'cc_brand': charge.source.brand,
                        'stripe_charge_id': charge.id,
                        'last4': charge.source.last4,
                        'billing_address': last_donation.billing_address.id,
                        'donator': donator.id,
                        'donation': donation_amount
                    }
                    donation_form = DonationForm(donation_data)
                    if donation_form.is_valid():
                        donation = donation_form.save()

                        context = {
                            'donation': donation,
                            'base_url': "{0}://{1}".format('https', 'dynamicweb.ungleich.ch')

                        }
                        email_data = {
                            'subject': 'Your donation have been charged',
                            'to': donation.donator.user.email,
                            'context': context,
                            'template_name': 'donation_charge',
                            'template_path': 'nosystemd/emails/'
                        }
                        email = BaseEmail(**email_data)
                        email.send()

                        print("--------- PAYMENT DONATION SUCCESSFULL ---------")
                        print("Donator: %s" % donation.donator.user.email)
                        print("Amount: %s %s" % (donation.donation, self.CURRENCY))
                        print("-----------------------------------------------")
                except Exception as e:
                    print("--------- ERROR ---------")
                    print(e)
                    print("-------------------------")
                    continue
Beispiel #26
0
    def post(self, request, *args, **kwargs):
        form = self.get_form()
        if form.is_valid():

            # Get billing address data
            billing_address_data = form.cleaned_data

            context = self.get_context_data()

            template = request.session.get('template')
            specs = request.session.get('specs')

            vm_template_id = template.get('id', 1)

            final_price = specs.get('price')

            token = form.cleaned_data.get('token')

            owner = self.request.user

            # Get or create stripe customer
            customer = StripeCustomer.get_or_create(email=owner.email,
                                                    token=token)
            if not customer:
                form.add_error("__all__", "Invalid credit card")
                return self.render_to_response(
                    self.get_context_data(form=form))

            # Create Billing Address
            billing_address = form.save()

            # Make stripe charge to a customer
            stripe_utils = StripeUtils()
            charge_response = stripe_utils.make_charge(
                amount=final_price, customer=customer.stripe_id)
            charge = charge_response.get('response_object')

            # Check if the payment was approved
            if not charge:
                context.update({
                    'paymentError': charge_response.get('error'),
                    'form': form
                })
                return render(request, self.template_name, context)

            charge = charge_response.get('response_object')

            # Create OpenNebulaManager
            manager = OpenNebulaManager(email=owner.email,
                                        password=owner.password)
            # Get user ssh key
            if not UserHostingKey.objects.filter(
                    user=self.request.user).exists():
                context.update({'sshError': 'error', 'form': form})
                return render(request, self.template_name, context)
            # For now just get first one
            user_key = UserHostingKey.objects.filter(
                user=self.request.user).first()

            # Create a vm using logged user
            vm_id = manager.create_vm(
                template_id=vm_template_id,
                # XXX: Confi
                specs=specs,
                ssh_key=user_key.public_key,
            )

            # Create a Hosting Order
            order = HostingOrder.create(price=final_price,
                                        vm_id=vm_id,
                                        customer=customer,
                                        billing_address=billing_address)

            # Create a Hosting Bill
            bill = HostingBill.create(customer=customer,
                                      billing_address=billing_address)

            # Create Billing Address for User if he does not have one
            if not customer.user.billing_addresses.count():
                billing_address_data.update({'user': customer.user.id})
                billing_address_user_form = UserBillingAddressForm(
                    billing_address_data)
                billing_address_user_form.is_valid()
                billing_address_user_form.save()

            # Associate an order with a stripe payment
            order.set_stripe_charge(charge)

            # If the Stripe payment was successed, set order status approved
            order.set_approved()

            vm = VirtualMachineSerializer(manager.get_vm(vm_id)).data

            # Send notification to ungleich as soon as VM has been booked
            context = {
                'vm': vm,
                'order': order,
                'base_url': "{0}://{1}".format(request.scheme,
                                               request.get_host())
            }
            email_data = {
                'subject': 'New VM request',
                'to': request.user.email,
                'context': context,
                'template_name': 'new_booked_vm',
                'template_path': 'hosting/emails/'
            }
            email = BaseEmail(**email_data)
            email.send()

            return HttpResponseRedirect(
                reverse('hosting:orders', kwargs={'pk': order.id}))
        else:
            return self.form_invalid(form)
Beispiel #27
0
    def post(self, request, *args, **kwargs):
        template = request.session.get('template')
        specs = request.session.get('specs')
        user = request.session.get('user')
        stripe_api_cus_id = request.session.get('customer')
        vm_template_id = template.get('id', 1)
        stripe_utils = StripeUtils()

        if 'token' in request.session:
            card_details = stripe_utils.get_cards_details_from_token(
                request.session.get('token')
            )
            if not card_details.get('response_object'):
                msg = card_details.get('error')
                messages.add_message(self.request, messages.ERROR, msg,
                                     extra_tags='failed_payment')
                response = {
                    'status': False,
                    'redirect': "{url}#{section}".format(
                        url=reverse('datacenterlight:payment'),
                        section='payment_error'),
                    'msg_title': str(_('Error.')),
                    'msg_body': str(
                        _('There was a payment related error.'
                          ' On close of this popup, you will be'
                          ' redirected back to the payment page.')
                    )
                }
                return JsonResponse(response)
            card_details_response = card_details['response_object']
            card_details_dict = {
                'last4': card_details_response['last4'],
                'brand': card_details_response['brand'],
                'card_id': card_details_response['card_id']
            }
            stripe_customer_obj = StripeCustomer.objects.filter(stripe_id=stripe_api_cus_id).first()
            if stripe_customer_obj:
                ucd = UserCardDetail.get_user_card_details(
                    stripe_customer_obj, card_details_response
                )
                if not ucd:
                    acc_result = stripe_utils.associate_customer_card(
                        stripe_api_cus_id, request.session['token'],
                        set_as_default=True
                    )
                    if acc_result['response_object'] is None:
                        msg = _(
                            'An error occurred while associating the card.'
                            ' Details: {details}'.format(
                                details=acc_result['error']
                            )
                        )
                        messages.add_message(self.request, messages.ERROR, msg,
                                             extra_tags='failed_payment')
                        response = {
                            'status': False,
                            'redirect': "{url}#{section}".format(
                                url=reverse('hosting:payment'),
                                section='payment_error'),
                            'msg_title': str(_('Error.')),
                            'msg_body': str(
                                _('There was a payment related error.'
                                  ' On close of this popup, you will be redirected'
                                  ' back to the payment page.')
                            )
                        }
                        return JsonResponse(response)
        elif 'card_id' in request.session:
            card_id = request.session.get('card_id')
            user_card_detail = UserCardDetail.objects.get(id=card_id)
            card_details_dict = {
                'last4': user_card_detail.last4,
                'brand': user_card_detail.brand,
                'card_id': user_card_detail.card_id
            }
        else:
            response = {
                'status': False,
                'redirect': "{url}#{section}".format(
                    url=reverse('datacenterlight:payment'),
                    section='payment_error'),
                'msg_title': str(_('Error.')),
                'msg_body': str(
                    _('There was a payment related error.'
                      ' On close of this popup, you will be redirected back to'
                      ' the payment page.'))
            }
            return JsonResponse(response)

        cpu = specs.get('cpu')
        memory = specs.get('memory')
        disk_size = specs.get('disk_size')
        amount_to_be_charged = specs.get('total_price')
        plan_name = StripeUtils.get_stripe_plan_name(cpu=cpu,
                                                     memory=memory,
                                                     disk_size=disk_size)
        stripe_plan_id = StripeUtils.get_stripe_plan_id(cpu=cpu,
                                                        ram=memory,
                                                        ssd=disk_size,
                                                        version=1,
                                                        app='dcl')
        stripe_plan = stripe_utils.get_or_create_stripe_plan(
            amount=amount_to_be_charged,
            name=plan_name,
            stripe_plan_id=stripe_plan_id)
        subscription_result = stripe_utils.subscribe_customer_to_plan(
            stripe_api_cus_id,
            [{"plan": stripe_plan.get(
                'response_object').stripe_plan_id}])
        stripe_subscription_obj = subscription_result.get('response_object')
        # Check if the subscription was approved and is active
        if (stripe_subscription_obj is None
                or stripe_subscription_obj.status != 'active'):
            # At this point, we have created a Stripe API card and
            # associated it with the customer; but the transaction failed
            # due to some reason. So, we would want to dissociate this card
            # here.
            # ...

            msg = subscription_result.get('error')
            messages.add_message(self.request, messages.ERROR, msg,
                                 extra_tags='failed_payment')
            response = {
                'status': False,
                'redirect': "{url}#{section}".format(
                    url=reverse('datacenterlight:payment'),
                    section='payment_error'),
                'msg_title': str(_('Error.')),
                'msg_body': str(
                    _('There was a payment related error.'
                      ' On close of this popup, you will be redirected back to'
                      ' the payment page.'))
            }
            return JsonResponse(response)

        # Create user if the user is not logged in and if he is not already
        # registered
        if not request.user.is_authenticated():
            try:
                custom_user = CustomUser.objects.get(
                    email=user.get('email'))
                stripe_customer = StripeCustomer.objects.filter(
                    user_id=custom_user.id).first()
                if stripe_customer is None:
                    stripe_customer = StripeCustomer.objects.create(
                        user=custom_user, stripe_id=stripe_api_cus_id
                    )
                stripe_customer_id = stripe_customer.id
            except CustomUser.DoesNotExist:
                logger.debug(
                    "Customer {} does not exist.".format(user.get('email')))
                password = CustomUser.get_random_password()
                base_url = "{0}://{1}".format(self.request.scheme,
                                              self.request.get_host())
                custom_user = CustomUser.register(
                    user.get('name'), password,
                    user.get('email'),
                    app='dcl', base_url=base_url, send_email=True,
                    account_details=password
                )
                logger.debug("Created user {}.".format(user.get('email')))
                stripe_customer = StripeCustomer.objects. \
                    create(user=custom_user, stripe_id=stripe_api_cus_id)
                stripe_customer_id = stripe_customer.id
                new_user = authenticate(username=custom_user.email,
                                        password=password)
                login(request, new_user)
        else:
            # We assume that if the user is here, his/her StripeCustomer
            # object already exists
            stripe_customer_id = request.user.stripecustomer.id
            custom_user = request.user

        if 'token' in request.session:
            ucd = UserCardDetail.get_or_create_user_card_detail(
                stripe_customer=self.request.user.stripecustomer,
                card_details=card_details_response
            )
            UserCardDetail.save_default_card_local(
                self.request.user.stripecustomer.stripe_id,
                ucd.card_id
            )
        else:
            card_id = request.session.get('card_id')
            user_card_detail = UserCardDetail.objects.get(id=card_id)
            card_details_dict = {
                'last4': user_card_detail.last4,
                'brand': user_card_detail.brand,
                'card_id': user_card_detail.card_id
            }
            if not user_card_detail.preferred:
                UserCardDetail.set_default_card(
                    stripe_api_cus_id=stripe_api_cus_id,
                    stripe_source_id=user_card_detail.card_id
                )

        # Save billing address
        billing_address_data = request.session.get('billing_address_data')
        logger.debug('billing_address_data is {}'.format(billing_address_data))
        billing_address_data.update({
            'user': custom_user.id
        })

        user = {
            'name': custom_user.name,
            'email': custom_user.email,
            'pass': custom_user.password,
            'request_scheme': request.scheme,
            'request_host': request.get_host(),
            'language': get_language(),
        }

        create_vm(
            billing_address_data, stripe_customer_id, specs,
            stripe_subscription_obj, card_details_dict, request,
            vm_template_id, template, user
        )

        response = {
            'status': True,
            'redirect': (
                reverse('hosting:virtual_machines')
                if request.user.is_authenticated()
                else reverse('datacenterlight:index')
            ),
            'msg_title': str(_('Thank you for the order.')),
            'msg_body': str(
                _('Your VM will be up and running in a few moments.'
                  ' We will send you a confirmation email as soon as'
                  ' it is ready.'))
        }

        return JsonResponse(response)
Beispiel #28
0
    def post(self, request, *args, **kwargs):
        form = self.get_form()

        if form.is_valid():
            context = self.get_context_data()
            specifications = request.session.get('vm_specs')
            vm_type = specifications.get('hosting_company')
            vm = VirtualMachineType.objects.get(hosting_company=vm_type)
            final_price = vm.calculate_price(specifications)

            plan_data = {
                'vm_type': vm,
                'cores': specifications.get('cores'),
                'memory': specifications.get('memory'),
                'disk_size': specifications.get('disk_size'),
                'configuration': specifications.get('configuration'),
                'price': final_price
            }
            token = form.cleaned_data.get('token')

            # Get or create stripe customer
            customer = StripeCustomer.get_or_create(email=self.request.user.email,
                                                    token=token)
            if not customer:
                form.add_error("__all__", "Invalid credit card")
                return self.render_to_response(self.get_context_data(form=form))

            # Create Virtual Machine Plan
            plan = VirtualMachinePlan.create(plan_data, request.user)

            # Create Billing Address
            billing_address = form.save()

            # Create a Hosting Order
            order = HostingOrder.create(vm_plan=plan, customer=customer,
                                        billing_address=billing_address)

            # Make stripe charge to a customer
            stripe_utils = StripeUtils()
            charge_response = stripe_utils.make_charge(amount=final_price,
                                                       customer=customer.stripe_id)
            charge = charge_response.get('response_object')

            # Check if the payment was approved
            if not charge:
                context.update({
                    'paymentError': charge_response.get('error'),
                    'form': form
                })
                return render(request, self.template_name, context)

            charge = charge_response.get('response_object')

            # Associate an order with a stripe payment
            order.set_stripe_charge(charge)

            # If the Stripe payment was successed, set order status approved
            order.set_approved()

            # Send notification to ungleich as soon as VM has been booked
            context = {
                'vm': plan,
                'order': order,
                'base_url': "{0}://{1}".format(request.scheme, request.get_host())

            }
            email_data = {
                'subject': 'New VM request',
                'to': request.user.email,
                'context': context,
                'template_name': 'new_booked_vm',
                'template_path': 'hosting/emails/'
            }
            email = BaseEmail(**email_data)
            email.send()

            return HttpResponseRedirect(reverse('hosting:orders', kwargs={'pk': order.id}))
        else:
            return self.form_invalid(form)
Beispiel #29
0
    def form_valid(self, form):
        data = form.cleaned_data
        context = self.get_context_data()
        token = data.get('token')
        start_date = data.get('start_date')
        end_date = data.get('end_date')
        is_free = context.get('is_free')
        normal_price, final_price, free_days = Booking.\
            booking_price(self.request.user, start_date, end_date)
        charge = None

        # if not credit_card_needed:
        # Get or create stripe customer
        customer = StripeCustomer.get_or_create(email=self.request.user.email,
                                                token=token)
        if not customer:
            form.add_error("__all__", "Invalid credit card")
            return self.render_to_response(self.get_context_data(form=form))

        # If booking is not free, make the stripe charge
        if not is_free:
            # Make stripe charge to a customer
            stripe_utils = StripeUtils()
            charge_response = stripe_utils.make_charge(
                amount=final_price, customer=customer.stripe_id)
            charge = charge_response.get('response_object')

            # Check if the payment was approved
            if not charge:
                context.update({
                    'paymentError': charge_response.get('error'),
                    'form': form
                })
                return render(self.request, self.template_name, context)

            charge = charge_response.get('response_object')

        # Create Billing Address for Membership Order
        billing_address = form.save()

        # Create Billing Address for User if he does not have one
        if not customer.user.billing_addresses.count():
            data.update({'user': customer.user.id})
            billing_address_user_form = UserBillingAddressForm(data)
            billing_address_user_form.is_valid()
            billing_address_user_form.save()

        # Create Booking
        booking_data = {
            'start_date': start_date,
            'end_date': end_date,
            'start_date': start_date,
            'free_days': free_days,
            'price': normal_price,
            'final_price': final_price,
        }
        booking = Booking.create(booking_data)

        # Create Booking order
        order_data = {
            'booking': booking,
            'customer': customer,
            'billing_address': billing_address,
            'stripe_charge': charge,
            'amount': final_price,
            'original_price': normal_price,
            'special_month_price':
            BookingPrice.objects.last().special_month_price,
        }
        order = BookingOrder.create(order_data)

        context = {
            'booking':
            booking,
            'order':
            order,
            'base_url':
            "{0}://{1}".format(self.request.scheme, self.request.get_host())
        }

        email_data = {
            'subject': 'Your booking order has been placed',
            'to': self.request.user.email,
            'context': context,
            'template_name': 'booking_order_email',
            'template_path': 'digitalglarus/emails/'
        }
        email = BaseEmail(**email_data)
        email.send()

        return HttpResponseRedirect(self.get_success_url(order.id))
Beispiel #30
0
    def post(self, request, *args, **kwargs):
        form = self.get_form()

        if form.is_valid():
            data = form.cleaned_data
            context = self.get_context_data()
            token = data.get('token')
            membership_type = data.get('membership_type')

            # Get or create stripe customer
            customer = StripeCustomer.get_or_create(
                email=self.request.user.email, token=token)
            if not customer:
                form.add_error("__all__", "Invalid credit card")
                return self.render_to_response(
                    self.get_context_data(form=form))

            # Make stripe charge to a customer
            stripe_utils = StripeUtils()
            charge_response = stripe_utils.make_charge(
                amount=membership_type.first_month_price,
                customer=customer.stripe_id)
            charge = charge_response.get('response_object')

            # Check if the payment was approved
            if not charge:
                context.update({
                    'paymentError': charge_response.get('error'),
                    'form': form
                })
                return render(request, self.template_name, context)

            charge = charge_response.get('response_object')

            # Create Billing Address
            billing_address = form.save()

            # Create Billing Address for User if he does not have one
            if not customer.user.billing_addresses.count():
                data.update({'user': customer.user.id})
                billing_address_user_form = UserBillingAddressForm(data)
                billing_address_user_form.is_valid()
                billing_address_user_form.save()

            # Get membership dates
            membership_start_date, membership_end_date = membership_type.first_month_range

            # Create or update membership plan
            membership_data = {
                'type': membership_type,
                'active': True,
                'start_date': membership_start_date,
                'end_date': membership_end_date
            }
            membership = Membership.activate_or_crete(membership_data,
                                                      self.request.user)

            # Create membership order
            order_data = {
                'membership': membership,
                'customer': customer,
                'billing_address': billing_address,
                'stripe_charge': charge,
                'amount': membership_type.first_month_price,
                'start_date': membership_start_date,
                'end_date': membership_end_date
            }

            membership_order = MembershipOrder.create(order_data)

            request.session.update({
                'membership_price':
                membership.type.first_month_price,
                'membership_dates':
                membership.type.first_month_formated_range
            })

            context = {
                'membership': membership,
                'order': membership_order,
                'membership_start_date': membership_start_date,
                'membership_end_date': membership_end_date,
                'base_url': "{0}://{1}".format(request.scheme,
                                               request.get_host())
            }
            email_data = {
                'subject': 'Your membership has been charged',
                'to': request.user.email,
                'context': context,
                'template_name': 'membership_charge',
                'template_path': 'digitalglarus/emails/'
            }
            email = BaseEmail(**email_data)
            email.send()

            return HttpResponseRedirect(
                reverse('digitalglarus:membership_activated'))

        else:
            return self.form_invalid(form)
Beispiel #31
0
    def post(self, request, *args, **kwargs):
        form = self.get_form()

        if form.is_valid():
            context = self.get_context_data()
            token = form.cleaned_data.get("token")
            donation_amount = form.cleaned_data.get("donation_amount")

            # Get or create stripe customer
            customer = StripeCustomer.get_or_create(email=self.request.user.email, token=token)
            if not customer:
                form.add_error("__all__", "Invalid credit card")
                return self.render_to_response(self.get_context_data(form=form))

            # Create Billing Address
            billing_address = form.save()

            # Make stripe charge to a customer
            stripe_utils = StripeUtils()
            stripe_utils.CURRENCY = "usd"
            charge_response = stripe_utils.make_charge(amount=donation_amount, customer=customer.stripe_id)
            charge = charge_response.get("response_object")

            # Check if the payment was approved
            if not charge:
                context.update({"paymentError": charge_response.get("error"), "form": form})
                return render(request, self.template_name, context)

            # Create a donation
            charge = charge_response.get("response_object")
            donation_data = request.POST.copy()
            donation_data.update(
                {
                    "cc_brand": charge.source.brand,
                    "stripe_charge_id": charge.id,
                    "last4": charge.source.last4,
                    "billing_address": billing_address.id,
                    "donator": customer.id,
                    "donation": donation_amount,
                }
            )
            donation_form = DonationForm(donation_data)
            if donation_form.is_valid():

                # reactivate donation status
                donation = donation_form.save()

                try:
                    donator_status = DonatorStatus.objects.get(user=self.request.user)
                    donator_status.set_active()
                except DonatorStatus.DoesNotExist:
                    pass

                donation = donation_form.save()

                context = {"donation": donation, "base_url": "{0}://{1}".format(request.scheme, request.get_host())}
                email_data = {
                    "subject": "Your donation have been charged",
                    "to": request.user.email,
                    "context": context,
                    "template_name": "donation_charge",
                    "template_path": "nosystemd/emails/",
                }
                email = BaseEmail(**email_data)
                email.send()

                return HttpResponseRedirect(reverse("nosystemd:donations", kwargs={"pk": donation.id}))
            else:
                self.form_invalid(donation_form)

        else:
            return self.form_invalid(form)
Beispiel #32
0
    def post(self, request, *args, **kwargs):
        user = request.session.get('user')
        stripe_api_cus_id = request.session.get('customer')
        stripe_utils = StripeUtils()

        if 'token' in request.session:
            card_details = stripe_utils.get_cards_details_from_token(
                request.session.get('token'))
            if not card_details.get('response_object'):
                msg = card_details.get('error')
                messages.add_message(self.request,
                                     messages.ERROR,
                                     msg,
                                     extra_tags='failed_payment')
                response = {
                    'status':
                    False,
                    'redirect':
                    "{url}#{section}".format(
                        url=(reverse(
                            'show_product',
                            kwargs={
                                'product_slug':
                                request.session['generic_payment_details']
                                ['product_slug']
                            }) if 'generic_payment_details' in request.session
                             else reverse('datacenterlight:payment')),
                        section='payment_error'),
                    'msg_title':
                    str(_('Error.')),
                    'msg_body':
                    str(
                        _('There was a payment related error.'
                          ' On close of this popup, you will be'
                          ' redirected back to the payment page.'))
                }
                return JsonResponse(response)
            card_details_response = card_details['response_object']
            card_details_dict = {
                'last4': card_details_response['last4'],
                'brand': card_details_response['brand'],
                'card_id': card_details_response['card_id']
            }
            stripe_customer_obj = StripeCustomer.objects.filter(
                stripe_id=stripe_api_cus_id).first()
            if stripe_customer_obj:
                ucd = UserCardDetail.get_user_card_details(
                    stripe_customer_obj, card_details_response)
                if not ucd:
                    acc_result = stripe_utils.associate_customer_card(
                        stripe_api_cus_id,
                        request.session['token'],
                        set_as_default=True)
                    if acc_result['response_object'] is None:
                        msg = _('An error occurred while associating the card.'
                                ' Details: {details}'.format(
                                    details=acc_result['error']))
                        messages.add_message(self.request,
                                             messages.ERROR,
                                             msg,
                                             extra_tags='failed_payment')
                        response = {
                            'status':
                            False,
                            'redirect':
                            "{url}#{section}".
                            format(url=(reverse(
                                'show_product',
                                kwargs={
                                    'product_slug':
                                    request.session['generic_payment_details']
                                    ['product_slug']
                                }) if 'generic_payment_details'
                                        in request.session else
                                        reverse('datacenterlight:payment')),
                                   section='payment_error'),
                            'msg_title':
                            str(_('Error.')),
                            'msg_body':
                            str(
                                _('There was a payment related error.'
                                  ' On close of this popup, you will be redirected'
                                  ' back to the payment page.'))
                        }
                        return JsonResponse(response)
        elif 'card_id' in request.session:
            card_id = request.session.get('card_id')
            user_card_detail = UserCardDetail.objects.get(id=card_id)
            card_details_dict = {
                'last4': user_card_detail.last4,
                'brand': user_card_detail.brand,
                'card_id': user_card_detail.card_id
            }
        else:
            response = {
                'status':
                False,
                'redirect':
                "{url}#{section}".format(
                    url=reverse('datacenterlight:payment'),
                    section='payment_error'),
                'msg_title':
                str(_('Error.')),
                'msg_body':
                str(
                    _('There was a payment related error.'
                      ' On close of this popup, you will be redirected back to'
                      ' the payment page.'))
            }
            return JsonResponse(response)

        if ('generic_payment_type' in request.session
                and self.request.session['generic_payment_type'] == 'generic'):
            gp_details = self.request.session['generic_payment_details']
            if gp_details['recurring']:
                # generic recurring payment
                logger.debug("Commencing a generic recurring payment")
            else:
                # generic one time payment
                logger.debug("Commencing a one time payment")
                charge_response = stripe_utils.make_charge(
                    amount=gp_details['amount'], customer=stripe_api_cus_id)
                stripe_onetime_charge = charge_response.get('response_object')

                # Check if the payment was approved
                if not stripe_onetime_charge:
                    msg = charge_response.get('error')
                    messages.add_message(self.request,
                                         messages.ERROR,
                                         msg,
                                         extra_tags='failed_payment')
                    response = {
                        'status':
                        False,
                        'redirect':
                        "{url}#{section}".format(
                            url=(reverse('show_product',
                                         kwargs={
                                             'product_slug':
                                             gp_details['product_slug']
                                         }) if 'generic_payment_details'
                                 in request.session else
                                 reverse('datacenterlight:payment')),
                            section='payment_error'),
                        'msg_title':
                        str(_('Error.')),
                        'msg_body':
                        str(
                            _('There was a payment related error.'
                              ' On close of this popup, you will be redirected'
                              ' back to the payment page.'))
                    }
                    return JsonResponse(response)

        if ('generic_payment_type' not in request.session
                or (request.session['generic_payment_details']['recurring'])):
            if 'generic_payment_details' in request.session:
                amount_to_be_charged = (round(
                    request.session['generic_payment_details']['amount'], 2))
                plan_name = "generic-{0}-{1:.2f}".format(
                    request.session['generic_payment_details']['product_id'],
                    amount_to_be_charged)
                stripe_plan_id = plan_name
            else:
                template = request.session.get('template')
                specs = request.session.get('specs')
                vm_template_id = template.get('id', 1)

                cpu = specs.get('cpu')
                memory = specs.get('memory')
                disk_size = specs.get('disk_size')
                amount_to_be_charged = specs.get('total_price')
                plan_name = StripeUtils.get_stripe_plan_name(
                    cpu=cpu,
                    memory=memory,
                    disk_size=disk_size,
                    price=amount_to_be_charged)
                stripe_plan_id = StripeUtils.get_stripe_plan_id(
                    cpu=cpu,
                    ram=memory,
                    ssd=disk_size,
                    version=1,
                    app='dcl',
                    price=amount_to_be_charged)
            stripe_plan = stripe_utils.get_or_create_stripe_plan(
                amount=amount_to_be_charged,
                name=plan_name,
                stripe_plan_id=stripe_plan_id)
            subscription_result = stripe_utils.subscribe_customer_to_plan(
                stripe_api_cus_id,
                [{
                    "plan": stripe_plan.get('response_object').stripe_plan_id
                }])
            stripe_subscription_obj = subscription_result.get(
                'response_object')
            # Check if the subscription was approved and is active
            if (stripe_subscription_obj is None
                    or stripe_subscription_obj.status != 'active'):
                # At this point, we have created a Stripe API card and
                # associated it with the customer; but the transaction failed
                # due to some reason. So, we would want to dissociate this card
                # here.
                # ...

                msg = subscription_result.get('error')
                messages.add_message(self.request,
                                     messages.ERROR,
                                     msg,
                                     extra_tags='failed_payment')
                response = {
                    'status':
                    False,
                    'redirect':
                    "{url}#{section}".format(
                        url=(reverse(
                            'show_product',
                            kwargs={
                                'product_slug':
                                request.session['generic_payment_details']
                                ['product_slug']
                            }) if 'generic_payment_details' in request.session
                             else reverse('datacenterlight:payment')),
                        section='payment_error'),
                    'msg_title':
                    str(_('Error.')),
                    'msg_body':
                    str(
                        _('There was a payment related error.'
                          ' On close of this popup, you will be redirected back to'
                          ' the payment page.'))
                }
                return JsonResponse(response)

        # Create user if the user is not logged in and if he is not already
        # registered
        if not request.user.is_authenticated():
            try:
                custom_user = CustomUser.objects.get(email=user.get('email'))
                stripe_customer = StripeCustomer.objects.filter(
                    user_id=custom_user.id).first()
                if stripe_customer is None:
                    stripe_customer = StripeCustomer.objects.create(
                        user=custom_user, stripe_id=stripe_api_cus_id)
                stripe_customer_id = stripe_customer.id
            except CustomUser.DoesNotExist:
                logger.debug("Customer {} does not exist.".format(
                    user.get('email')))
                password = CustomUser.get_random_password()
                base_url = "{0}://{1}".format(self.request.scheme,
                                              self.request.get_host())
                custom_user = CustomUser.register(user.get('name'),
                                                  password,
                                                  user.get('email'),
                                                  app='dcl',
                                                  base_url=base_url,
                                                  send_email=True,
                                                  account_details=password)
                logger.debug("Created user {}.".format(user.get('email')))
                stripe_customer = StripeCustomer.objects. \
                    create(user=custom_user, stripe_id=stripe_api_cus_id)
                stripe_customer_id = stripe_customer.id
                new_user = authenticate(username=custom_user.email,
                                        password=password)
                login(request, new_user)
        else:
            # We assume that if the user is here, his/her StripeCustomer
            # object already exists
            stripe_customer_id = request.user.stripecustomer.id
            custom_user = request.user

        if 'token' in request.session:
            ucd = UserCardDetail.get_or_create_user_card_detail(
                stripe_customer=self.request.user.stripecustomer,
                card_details=card_details_response)
            UserCardDetail.save_default_card_local(
                self.request.user.stripecustomer.stripe_id, ucd.card_id)
        else:
            card_id = request.session.get('card_id')
            user_card_detail = UserCardDetail.objects.get(id=card_id)
            card_details_dict = {
                'last4': user_card_detail.last4,
                'brand': user_card_detail.brand,
                'card_id': user_card_detail.card_id
            }
            if not user_card_detail.preferred:
                UserCardDetail.set_default_card(
                    stripe_api_cus_id=stripe_api_cus_id,
                    stripe_source_id=user_card_detail.card_id)

        # Save billing address
        billing_address_data = request.session.get('billing_address_data')
        logger.debug('billing_address_data is {}'.format(billing_address_data))
        billing_address_data.update({'user': custom_user.id})

        if 'generic_payment_type' in request.session:
            stripe_cus = StripeCustomer.objects.filter(
                stripe_id=stripe_api_cus_id).first()
            billing_address = BillingAddress(
                cardholder_name=billing_address_data['cardholder_name'],
                street_address=billing_address_data['street_address'],
                city=billing_address_data['city'],
                postal_code=billing_address_data['postal_code'],
                country=billing_address_data['country'])
            billing_address.save()

            order = HostingOrder.create(
                price=self.request.session['generic_payment_details']
                ['amount'],
                customer=stripe_cus,
                billing_address=billing_address,
                vm_pricing=VMPricing.get_default_pricing())

            # Create a Hosting Bill
            HostingBill.create(customer=stripe_cus,
                               billing_address=billing_address)

            # Create Billing Address for User if he does not have one
            if not stripe_cus.user.billing_addresses.count():
                billing_address_data.update({'user': stripe_cus.user.id})
                billing_address_user_form = UserBillingAddressForm(
                    billing_address_data)
                billing_address_user_form.is_valid()
                billing_address_user_form.save()

            if self.request.session['generic_payment_details']['recurring']:
                # Associate the given stripe subscription with the order
                order.set_subscription_id(stripe_subscription_obj.id,
                                          card_details_dict)
            else:
                # Associate the given stripe charge id with the order
                order.set_stripe_charge(stripe_onetime_charge)

            # Set order status approved
            order.set_approved()
            order.generic_payment_description = gp_details["description"]
            order.generic_product_id = gp_details["product_id"]
            order.save()
            # send emails
            context = {
                'name': user.get('name'),
                'email': user.get('email'),
                'amount': gp_details['amount'],
                'description': gp_details['description'],
                'recurring': gp_details['recurring'],
                'product_name': gp_details['product_name'],
                'product_id': gp_details['product_id'],
                'order_id': order.id
            }

            email_data = {
                'subject': (settings.DCL_TEXT +
                            " Payment received from %s" % context['email']),
                'from_email':
                settings.DCL_SUPPORT_FROM_ADDRESS,
                'to': ['*****@*****.**'],
                'body':
                "\n".join(["%s=%s" % (k, v) for (k, v) in context.items()]),
                'reply_to': [context['email']],
            }
            send_plain_email_task.delay(email_data)

            email_data = {
                'subject':
                _("Confirmation of your payment"),
                'from_email':
                settings.DCL_SUPPORT_FROM_ADDRESS,
                'to': [user.get('email')],
                'body':
                _("Hi {name},\n\n"
                  "thank you for your order!\n"
                  "We have just received a payment of CHF {amount:.2f}"
                  " from you.{recurring}\n\n"
                  "Cheers,\nYour Data Center Light team".format(
                      name=user.get('name'),
                      amount=gp_details['amount'],
                      recurring=(_(' This is a monthly recurring plan.')
                                 if gp_details['recurring'] else ''))),
                'reply_to': ['*****@*****.**'],
            }
            send_plain_email_task.delay(email_data)

            response = {
                'status':
                True,
                'redirect':
                (reverse('hosting:orders') if request.user.is_authenticated()
                 else reverse('datacenterlight:index')),
                'msg_title':
                str(_('Thank you for the payment.')),
                'msg_body':
                str(
                    _('You will soon receive a confirmation email of the '
                      'payment. You can always contact us at '
                      '[email protected] for any question that you may have.'))
            }
            clear_all_session_vars(request)

            return JsonResponse(response)

        user = {
            'name': custom_user.name,
            'email': custom_user.email,
            'pass': custom_user.password,
            'request_scheme': request.scheme,
            'request_host': request.get_host(),
            'language': get_language(),
        }

        create_vm(billing_address_data, stripe_customer_id, specs,
                  stripe_subscription_obj, card_details_dict, request,
                  vm_template_id, template, user)

        response = {
            'status':
            True,
            'redirect': (reverse('hosting:virtual_machines')
                         if request.user.is_authenticated() else
                         reverse('datacenterlight:index')),
            'msg_title':
            str(_('Thank you for the order.')),
            'msg_body':
            str(
                _('Your VM will be up and running in a few moments.'
                  ' We will send you a confirmation email as soon as'
                  ' it is ready.'))
        }

        return JsonResponse(response)
Beispiel #33
0
def create_vm_task(self, vm_template_id, user, specs, template, order_id):
    logger.debug("Running create_vm_task on {}".format(
        current_task.request.hostname))
    vm_id = None
    try:
        final_price = (specs.get('total_price')
                       if 'total_price' in specs else specs.get('price'))

        if 'pass' in user:
            on_user = user.get('email')
            on_pass = user.get('pass')
            logger.debug("Using user {user} to create VM".format(user=on_user))
            vm_name = None
        else:
            on_user = settings.OPENNEBULA_USERNAME
            on_pass = settings.OPENNEBULA_PASSWORD
            logger.debug("Using OpenNebula admin user to create VM")
            vm_name = "{email}-{template_name}-{date}".format(
                email=user.get('email'),
                template_name=template.get('name'),
                date=int(datetime.now().strftime("%s")))

        # Create OpenNebulaManager
        manager = OpenNebulaManager(email=on_user, password=on_pass)

        vm_id = manager.create_vm(
            template_id=vm_template_id,
            specs=specs,
            ssh_key=settings.ONEADMIN_USER_SSH_PUBLIC_KEY,
            vm_name=vm_name)

        if vm_id is None:
            raise Exception("Could not create VM")

        # Update HostingOrder with the created vm_id
        hosting_order = HostingOrder.objects.filter(id=order_id).first()
        error_msg = None

        try:
            hosting_order.vm_id = vm_id
            hosting_order.save()
            logger.debug("Updated hosting_order {} with vm_id={}".format(
                hosting_order.id, vm_id))
        except Exception as ex:
            error_msg = (
                "HostingOrder with id {order_id} not found. This means that "
                "the hosting order was not created and/or it is/was not "
                "associated with VM with id {vm_id}. Details {details}".format(
                    order_id=order_id, vm_id=vm_id, details=str(ex)))
            logger.error(error_msg)

        stripe_utils = StripeUtils()
        result = stripe_utils.set_subscription_metadata(
            subscription_id=hosting_order.subscription_id,
            metadata={"VM_ID": str(vm_id)})

        if result.get('error') is not None:
            emsg = "Could not update subscription metadata for {sub}".format(
                sub=hosting_order.subscription_id)
            logger.error(emsg)
            if error_msg:
                error_msg += ". " + emsg
            else:
                error_msg = emsg

        vm = VirtualMachineSerializer(manager.get_vm(vm_id)).data

        context = {
            'name': user.get('name'),
            'email': user.get('email'),
            'cores': specs.get('cpu'),
            'memory': specs.get('memory'),
            'storage': specs.get('disk_size'),
            'price': final_price,
            'template': template.get('name'),
            'vm_name': vm.get('name'),
            'vm_id': vm['vm_id'],
            'order_id': order_id
        }

        if error_msg:
            context['errors'] = error_msg
        if 'pricing_name' in specs:
            context['pricing'] = str(
                VMPricing.get_vm_pricing_by_name(name=specs['pricing_name']))
        email_data = {
            'subject': settings.DCL_TEXT + " Order from %s" % context['email'],
            'from_email': settings.DCL_SUPPORT_FROM_ADDRESS,
            'to': ['*****@*****.**'],
            'body':
            "\n".join(["%s=%s" % (k, v) for (k, v) in context.items()]),
            'reply_to': [context['email']],
        }
        email = EmailMessage(**email_data)
        email.send()

        if 'pass' in user:
            lang = 'en-us'
            if user.get('language') is not None:
                logger.debug("Language is set to {}".format(
                    user.get('language')))
                lang = user.get('language')
            translation.activate(lang)
            # Send notification to the user as soon as VM has been booked
            context = {
                'base_url':
                "{0}://{1}".format(user.get('request_scheme'),
                                   user.get('request_host')),
                'order_url':
                reverse('hosting:orders', kwargs={'pk': order_id}),
                'page_header':
                _('Your New VM %(vm_name)s at Data Center Light') % {
                    'vm_name': vm.get('name')
                },
                'vm_name':
                vm.get('name')
            }
            email_data = {
                'subject': context.get('page_header'),
                'to': user.get('email'),
                'context': context,
                'template_name': 'new_booked_vm',
                'template_path': 'hosting/emails/',
                'from_address': settings.DCL_SUPPORT_FROM_ADDRESS,
            }
            email = BaseEmail(**email_data)
            email.send()

            # try to see if we have the IPv6 of the new vm and that if the ssh
            # keys can be configured
            vm_ipv6 = manager.get_ipv6(vm_id)
            logger.debug("New VM ID is {vm_id}".format(vm_id=vm_id))
            if vm_ipv6 is not None:
                custom_user = CustomUser.objects.get(email=user.get('email'))
                get_or_create_vm_detail(custom_user, manager, vm_id)
                if custom_user is not None:
                    public_keys = get_all_public_keys(custom_user)
                    keys = [{
                        'value': key,
                        'state': True
                    } for key in public_keys]
                    if len(keys) > 0:
                        logger.debug("Calling configure on {host} for "
                                     "{num_keys} keys".format(
                                         host=vm_ipv6, num_keys=len(keys)))
                        # Let's wait until the IP responds to ping before we
                        # run the cdist configure on the host
                        did_manage_public_key = False
                        for i in range(0, 15):
                            if ping_ok(vm_ipv6):
                                logger.debug(
                                    "{} is pingable. Doing a "
                                    "manage_public_key".format(vm_ipv6))
                                sleep(10)
                                manager.manage_public_key(keys,
                                                          hosts=[vm_ipv6])
                                did_manage_public_key = True
                                break
                            else:
                                logger.debug(
                                    "Can't ping {}. Wait 5 secs".format(
                                        vm_ipv6))
                                sleep(5)
                        if not did_manage_public_key:
                            emsg = ("Waited for over 75 seconds for {} to be "
                                    "pingable. But the VM was not reachable. "
                                    "So, gave up manage_public_key. Please do "
                                    "this manually".format(vm_ipv6))
                            logger.error(emsg)
                            email_data = {
                                'subject':
                                '{} CELERY TASK INCOMPLETE: {} not '
                                'pingable for 75 seconds'.format(
                                    settings.DCL_TEXT, vm_ipv6),
                                'from_email':
                                current_task.request.hostname,
                                'to':
                                settings.DCL_ERROR_EMAILS_TO_LIST,
                                'body':
                                emsg
                            }
                            email = EmailMessage(**email_data)
                            email.send()
    except Exception as e:
        logger.error(str(e))
        try:
            retry_task(self)
        except MaxRetriesExceededError:
            msg_text = 'Finished {} retries for create_vm_task'.format(
                self.request.retries)
            logger.error(msg_text)
            # Try sending email and stop
            email_data = {
                'subject':
                '{} CELERY TASK ERROR: {}'.format(settings.DCL_TEXT, msg_text),
                'from_email':
                current_task.request.hostname,
                'to':
                settings.DCL_ERROR_EMAILS_TO_LIST,
                'body':
                ',\n'.join(str(i) for i in self.request.args)
            }
            email = EmailMessage(**email_data)
            email.send()
            return

    return vm_id
Beispiel #34
0
class CeleryTaskTestCase(TestCase):
    @override_settings(
        task_eager_propagates=True,
        task_always_eager=True,
    )
    def setUp(self):
        self.customer_password = '******'
        self.customer_email = '*****@*****.**'
        self.customer_name = "Monty Python"
        self.user = {'email': self.customer_email, 'name': self.customer_name}
        self.customer = mommy.make('membership.CustomUser')
        self.customer.set_password(self.customer_password)
        self.customer.email = self.customer_email
        self.customer.save()
        self.stripe_utils = StripeUtils()
        stripe.api_key = settings.STRIPE_API_PRIVATE_KEY_TEST
        self.token = stripe.Token.create(card={
            "number": '4111111111111111',
            "exp_month": 12,
            "exp_year": 2022,
            "cvc": '123'
        }, )
        # Run fetchvmtemplates so that we have the VM templates from
        # OpenNebula
        call_command('fetchvmtemplates')

    @skipIf(
        settings.OPENNEBULA_DOMAIN is None
        or settings.OPENNEBULA_DOMAIN is "test_domain",
        """OpenNebula details unavailable, so skipping test_create_vm_task""")
    def test_create_vm_task(self):
        """Tests the create vm task for monthly subscription

        This test is supposed to validate the proper execution
        of celery create_vm_task on production, as we have no
        other way to do this.
        """

        # We create a VM from the first template available to DCL
        vm_template = VMTemplate.objects.all().first()
        template_data = VMTemplateSerializer(vm_template).data

        # The specs of VM that we want to create
        specs = {'cpu': 1, 'memory': 2, 'disk_size': 10, 'price': 15}

        stripe_customer = StripeCustomer.get_or_create(
            email=self.customer_email, token=self.token)
        card_details = self.stripe_utils.get_card_details(
            stripe_customer.stripe_id)
        card_details_dict = card_details.get('error')
        self.assertEquals(card_details_dict, None)
        billing_address_data = {
            'cardholder_name': self.customer_name,
            'postal_code': '1231',
            'country': 'CH',
            'token': self.token,
            'street_address': 'Monty\'s Street',
            'city': 'Hollywood'
        }
        vm_template_id = template_data.get('id', 1)

        cpu = specs.get('cpu')
        memory = specs.get('memory')
        disk_size = specs.get('disk_size')
        amount_to_be_charged = get_vm_price(cpu=cpu,
                                            memory=memory,
                                            disk_size=disk_size)
        plan_name = StripeUtils.get_stripe_plan_name(cpu=cpu,
                                                     memory=memory,
                                                     disk_size=disk_size)
        stripe_plan_id = StripeUtils.get_stripe_plan_id(cpu=cpu,
                                                        ram=memory,
                                                        ssd=disk_size,
                                                        version=1,
                                                        app='dcl')
        stripe_plan = self.stripe_utils.get_or_create_stripe_plan(
            amount=amount_to_be_charged,
            name=plan_name,
            stripe_plan_id=stripe_plan_id)
        subscription_result = self.stripe_utils.subscribe_customer_to_plan(
            stripe_customer.stripe_id,
            [{
                "plan": stripe_plan.get('response_object').stripe_plan_id
            }])
        stripe_subscription_obj = subscription_result.get('response_object')
        # Check if the subscription was approved and is active
        if stripe_subscription_obj is None \
                or stripe_subscription_obj.status != 'active':
            msg = subscription_result.get('error')
            raise Exception("Creating subscription failed: {}".format(msg))

        billing_address = BillingAddress(
            cardholder_name=billing_address_data['cardholder_name'],
            street_address=billing_address_data['street_address'],
            city=billing_address_data['city'],
            postal_code=billing_address_data['postal_code'],
            country=billing_address_data['country'])
        billing_address.save()

        order = HostingOrder.create(price=specs['price'],
                                    vm_id=0,
                                    customer=stripe_customer,
                                    billing_address=billing_address)

        async_task = create_vm_task.delay(vm_template_id, self.user, specs,
                                          template_data, order.id)
        new_vm_id = 0
        res = None
        for i in range(0, 10):
            sleep(5)
            res = AsyncResult(async_task.task_id)
            if res.result is not None and res.result > 0:
                new_vm_id = res.result
                break

        # We expect a VM to be created within 50 seconds
        self.assertGreater(
            new_vm_id, 0,
            "VM could not be created. res._get_task_meta() = {}".format(
                res._get_task_meta()))
Beispiel #35
0
    def handle(self, *args, **options):
        donators = DonatorStatus.objects.filter(status=DonatorStatus.ACTIVE)
        current_month = datetime.now().month
        current_year = datetime.now().year

        print("--------- STARTING DONATIONS SCRIPT  ---------")
        print("Donations date: %s-%s" % (current_month, current_year))

        for donator_status in donators:
            donator = donator_status.user.stripecustomer
            try:
                Donation.objects.get(created_at__month=current_month,
                                     created_at__year=current_year,
                                     donator=donator)
            except Donation.DoesNotExist:
                try:
                    # Get donator last donation amount
                    last_donation = Donation.objects.filter(
                        donator=donator).last()
                    donation_amount = last_donation.donation

                    # Make stripe charge to a customer
                    stripe_utils = StripeUtils()
                    stripe_utils.CURRENCY = self.CURRENCY
                    charge_response = stripe_utils.make_charge(
                        amount=donation_amount, customer=donator.stripe_id)
                    charge = charge_response.get('response_object')

                    # Check if the payment was approved
                    if not charge:
                        # There is an error trying to creating the stripe charge
                        context = {
                            'paymentError': charge_response.get('error'),
                        }
                        print("--------- STRIPE PAYMENT ERROR ---------")
                        print(context)
                        print("-------------------------")
                        continue
                    # Create a donation
                    charge = charge_response.get('response_object')
                    donation_data = {
                        'cc_brand': charge.source.brand,
                        'stripe_charge_id': charge.id,
                        'last4': charge.source.last4,
                        'billing_address': last_donation.billing_address.id,
                        'donator': donator.id,
                        'donation': donation_amount
                    }
                    donation_form = DonationForm(donation_data)
                    if donation_form.is_valid():
                        donation = donation_form.save()

                        context = {
                            'donation':
                            donation,
                            'base_url':
                            "{0}://{1}".format('https',
                                               'dynamicweb.ungleich.ch')
                        }
                        email_data = {
                            'subject': 'Your donation have been charged',
                            'to': donation.donator.user.email,
                            'context': context,
                            'template_name': 'donation_charge',
                            'template_path': 'nosystemd/emails/'
                        }
                        email = BaseEmail(**email_data)
                        email.send()

                        print(
                            "--------- PAYMENT DONATION SUCCESSFULL ---------")
                        print("Donator: %s" % donation.donator.user.email)
                        print("Amount: %s %s" %
                              (donation.donation, self.CURRENCY))
                        print(
                            "-----------------------------------------------")
                except Exception as e:
                    print("--------- ERROR ---------")
                    print(e)
                    print("-------------------------")
                    continue
Beispiel #36
0
    def test_create_vm_task(self):
        """Tests the create vm task for monthly subscription

        This test is supposed to validate the proper execution
        of celery create_vm_task on production, as we have no
        other way to do this.
        """

        # We create a VM from the first template available to DCL
        vm_template = VMTemplate.objects.all().first()
        template_data = VMTemplateSerializer(vm_template).data

        # The specs of VM that we want to create
        specs = {'cpu': 1, 'memory': 2, 'disk_size': 10, 'price': 15}

        stripe_customer = StripeCustomer.get_or_create(
            email=self.customer_email, token=self.token)
        card_details = self.stripe_utils.get_card_details(
            stripe_customer.stripe_id)
        card_details_dict = card_details.get('error')
        self.assertEquals(card_details_dict, None)
        billing_address_data = {
            'cardholder_name': self.customer_name,
            'postal_code': '1231',
            'country': 'CH',
            'token': self.token,
            'street_address': 'Monty\'s Street',
            'city': 'Hollywood'
        }
        vm_template_id = template_data.get('id', 1)

        cpu = specs.get('cpu')
        memory = specs.get('memory')
        disk_size = specs.get('disk_size')
        amount_to_be_charged = get_vm_price(cpu=cpu,
                                            memory=memory,
                                            disk_size=disk_size)
        plan_name = StripeUtils.get_stripe_plan_name(cpu=cpu,
                                                     memory=memory,
                                                     disk_size=disk_size)
        stripe_plan_id = StripeUtils.get_stripe_plan_id(cpu=cpu,
                                                        ram=memory,
                                                        ssd=disk_size,
                                                        version=1,
                                                        app='dcl')
        stripe_plan = self.stripe_utils.get_or_create_stripe_plan(
            amount=amount_to_be_charged,
            name=plan_name,
            stripe_plan_id=stripe_plan_id)
        subscription_result = self.stripe_utils.subscribe_customer_to_plan(
            stripe_customer.stripe_id,
            [{
                "plan": stripe_plan.get('response_object').stripe_plan_id
            }])
        stripe_subscription_obj = subscription_result.get('response_object')
        # Check if the subscription was approved and is active
        if stripe_subscription_obj is None \
                or stripe_subscription_obj.status != 'active':
            msg = subscription_result.get('error')
            raise Exception("Creating subscription failed: {}".format(msg))

        billing_address = BillingAddress(
            cardholder_name=billing_address_data['cardholder_name'],
            street_address=billing_address_data['street_address'],
            city=billing_address_data['city'],
            postal_code=billing_address_data['postal_code'],
            country=billing_address_data['country'])
        billing_address.save()

        order = HostingOrder.create(price=specs['price'],
                                    vm_id=0,
                                    customer=stripe_customer,
                                    billing_address=billing_address)

        async_task = create_vm_task.delay(vm_template_id, self.user, specs,
                                          template_data, order.id)
        new_vm_id = 0
        res = None
        for i in range(0, 10):
            sleep(5)
            res = AsyncResult(async_task.task_id)
            if res.result is not None and res.result > 0:
                new_vm_id = res.result
                break

        # We expect a VM to be created within 50 seconds
        self.assertGreater(
            new_vm_id, 0,
            "VM could not be created. res._get_task_meta() = {}".format(
                res._get_task_meta()))
Beispiel #37
0
    def post(self, request, *args, **kwargs):
        form = self.get_form()

        if form.is_valid():
            data = form.cleaned_data
            context = self.get_context_data()
            token = data.get('token')
            membership_type = data.get('membership_type')

            # Get or create stripe customer
            customer = StripeCustomer.get_or_create(
                email=self.request.user.email, token=token)
            if not customer:
                form.add_error("__all__", "Invalid credit card")
                return self.render_to_response(
                    self.get_context_data(form=form))

            # Make stripe charge to a customer
            stripe_utils = StripeUtils()
            charge_response = stripe_utils.make_charge(
                amount=membership_type.first_month_price,
                customer=customer.stripe_id)
            charge = charge_response.get('response_object')

            # Check if the payment was approved
            if not charge:
                context.update({
                    'paymentError': charge_response.get('error'),
                    'form': form
                })
                email_to_admin_data = {
                    'subject':
                    "Could not create charge for Digital Glarus "
                    "user: {user}".format(user=self.request.user.email),
                    'from_email':
                    '*****@*****.**',
                    'to': ['*****@*****.**'],
                    'body':
                    "\n".join([
                        "%s=%s" % (k, v) for (k, v) in charge_response.items()
                    ]),
                }
                send_plain_email_task.delay(email_to_admin_data)
                return render(request, self.template_name, context)

            # Subscribe the customer to dg plan from the next month onwards
            stripe_plan = stripe_utils.get_or_create_stripe_plan(
                amount=membership_type.price,
                name='Digital Glarus {sub_type_name} Subscription'.format(
                    sub_type_name=membership_type.name),
                stripe_plan_id='dg-{sub_type_name}'.format(
                    sub_type_name=membership_type.name))
            subscription_result = stripe_utils.subscribe_customer_to_plan(
                customer.stripe_id,
                [{
                    "plan": stripe_plan.get('response_object').stripe_plan_id
                }],
                trial_end=membership_type.next_month_in_sec_since_epoch)
            stripe_subscription_obj = subscription_result.get(
                'response_object')
            # Check if call to create subscription was ok
            if (stripe_subscription_obj is None
                    or (stripe_subscription_obj.status != 'active'
                        and stripe_subscription_obj.status != 'trialing')):
                context.update({
                    'paymentError': subscription_result.get('error'),
                    'form': form
                })
                email_to_admin_data = {
                    'subject':
                    "Could not create Stripe subscription for "
                    "Digital Glarus user: {user}".format(
                        user=self.request.user.email),
                    'from_email':
                    '*****@*****.**',
                    'to': ['*****@*****.**'],
                    'body':
                    "\n".join([
                        "%s=%s" % (k, v)
                        for (k, v) in subscription_result.items()
                    ]),
                }
                send_plain_email_task.delay(email_to_admin_data)
                return render(request, self.template_name, context)

            charge = charge_response.get('response_object')
            if 'source' in charge:
                cardholder_name = charge['source']['name']
            else:
                cardholder_name = customer.user.name

            # Create Billing Address
            billing_address = form.save()

            # Create Billing Address for User if he does not have one
            if not customer.user.billing_addresses.count():
                data.update({
                    'user': customer.user.id,
                    'cardholder_name': cardholder_name
                })
                billing_address_user_form = UserBillingAddressForm(data)
                billing_address_user_form.is_valid()
                billing_address_user_form.save()

            # Get membership dates
            membership_start_date, membership_end_date = membership_type.first_month_range

            # Create or update membership plan
            membership_data = {
                'type': membership_type,
                'active': True,
                'start_date': membership_start_date,
                'end_date': membership_end_date
            }
            membership = Membership.activate_or_crete(membership_data,
                                                      self.request.user)

            # Create membership order
            order_data = {
                'membership': membership,
                'customer': customer,
                'billing_address': billing_address,
                'stripe_charge': charge,
                'stripe_subscription_id': stripe_subscription_obj.id,
                'amount': membership_type.first_month_price,
                'start_date': membership_start_date,
                'end_date': membership_end_date
            }

            membership_order = MembershipOrder.create(order_data)

            request.session.update({
                'membership_price':
                membership.type.first_month_price,
                'membership_dates':
                membership.type.first_month_formated_range
            })

            email_to_admin_data = {
                'subject':
                "New Digital Glarus subscription: {user}".format(
                    user=self.request.user.email),
                'from_email':
                '*****@*****.**',
                'to': ['*****@*****.**'],
                'body':
                "\n".join(["%s=%s" % (k, v) for (k, v) in order_data.items()]),
            }
            send_plain_email_task.delay(email_to_admin_data)

            context = {
                'membership': membership,
                'order': membership_order,
                'membership_start_date': membership_start_date,
                'membership_end_date': membership_end_date,
                'base_url': "{0}://{1}".format(request.scheme,
                                               request.get_host())
            }
            email_data = {
                'subject': 'Your membership has been charged',
                'to': request.user.email,
                'context': context,
                'template_name': 'membership_charge',
                'template_path': 'digitalglarus/emails/'
            }
            email = BaseEmail(**email_data)
            email.send()

            return HttpResponseRedirect(
                reverse('digitalglarus:membership_activated'))

        else:
            return self.form_invalid(form)