Beispiel #1
0
def add_session_items_to_db(request):
    """Function that adds users session cart to database"""
    cart = request.session.get('cart', {})
    user = User.objects.get(id=request.user.id)
    comp = Competition.objects.get(is_active=True)
    for key, value in cart.items():
        product = Product.objects.get(id=int(key))
        order_item, created = OrderItem.objects.get_or_create(
            defaults={'quantity': int(value)},
            user=user,
            product=product,
            is_paid=False)
        order_qs = Order.objects.filter(user=user, ordered=False)

        if order_qs.exists():
            order = order_qs[0]
            if order.items.filter(pk=order_item.id).exists():
                order_item.quantity = int(value)
                order_item.save()
            else:
                order.items.add(order_item)
        else:
            order = Order.objects.create(user=user,
                                         related_competition=comp,
                                         order_date=timezone.now())
            order.items.add(order_item)
            order.save()

    request.session['cart'] = cart
    cart_contents(request)
def add_session_items_to_db(request):
    """Function that adds users session cart to database"""
    cart = request.session.get('cart', {})
    user = User.objects.get(id=request.user.id)
    for key, value in cart.items():
        product = Product.objects.get(id=int(key))
        comp = Competition.objects.get(is_active=True)
        new_order = Orders.objects.create(user=user,
                                          related_competition=comp,
                                          product=product,
                                          quantity=int(value))
        new_order.save()
    request.session['cart'] = cart
    cart_contents(request)
Beispiel #3
0
def product_info(request, product_id):
    """ A view to show a products details """

    try:
        product = Product.objects.get(pk=product_id)
    except Product.DoesNotExist:
        messages.error(request,
                       'Sorry that product cannot be found',
                       extra_tags='product error')

        return redirect('products')

    else:
        context = {
                'product': product,
                'rating_html': create_review_stars(product.average_rating),
                'opts': Product.ProductAdminOpts(),
        }

        current_shopping_cart = cart_contents(request)
        original_cart = current_shopping_cart['cart_items']
        if check_product_in(original_cart, product_id):
            context['exists_in_cart'] = True

        if product.customizable:
            invite_data = list(product.customlines.all().values(
                'name', 'text', 'y_pos', 'font',
                'raw_size', 'color', 'stroke_fill', 'stroke_width'))
            context['invite_data'] = json.dumps(invite_data)

        return render(request, 'products/product_info.html', context)
Beispiel #4
0
def save_order_record(request):
    """
    Creates the order_line_record that will be
    displayed in user profile.
    It utilizes the data stored in cart_items created
    via cart.contexts.py when adding items to the cart.
    """

    cart_items = cart_contents(request)['cart_items']

    for cart_item in cart_items:
        article_id = cart_item['article_id']
        product = get_object_or_404(Product, pk=article_id)
        qty = cart_item['qty']
        size = cart_item['size']
        total = cart_item['qty'] * cart_item['price']

        order_line_detail = OrderLineDetail(
            order_shipping=OrderShippingDetails.objects.filter(
                customer=request.user).last(),
            product=product,
            quantity=qty,
            total=total,
            size=size,
        )
        order_line_detail.save()
Beispiel #5
0
def checkout(request):
    cart = request.session.get('cart', {})
    if not cart:
        messages.error(request, "There's nothing in your cart at the moment")
        return redirect(reverse('products'))

    current_cart = cart_contents(request)
    total = current_cart['grand_total']
    stripe_total = round(total * 100)
    stripe.api_key = stripe_secret_key
    intent = stripe.PaymentIntent.create(
    amount=stripe_total,
    currency=settings.STRIPE_CURRENCY,
    )

    if not stripe_public_key:
        messages.warning(request, 'Stripe public key is missing. \
            Did you forget to set it in your environment?')

    template = 'checkout/checkout.html'
    context = {
        'order_form': order_form,
        'stripe_public_key': stripe_public_key,
        'client_secret': intent.client_secret,
    }

    return render(request, template, context)
Beispiel #6
0
def cache_checkout_data(request):
    try:
        pid = request.POST.get('client_secret').split('_secret')[0]
        stripe.api_key = settings.STRIPE_SECRET_KEY
        cart = request.session.get('cart', {})
        current_cart = cart_contents(request)
        if current_cart['subscription']:
            subscription = True
        else:
            subscription = False

        stripe.PaymentIntent.modify(pid,
                                    metadata={
                                        'cart': json.dumps(cart),
                                        'save_info':
                                        request.POST.get('save_info'),
                                        'username': request.user,
                                        'subscription': subscription,
                                    })
        return HttpResponse(status=200)
    except Exception as e:
        messages.error(
            request, 'Sorry, your payment cannot be \
            processed right now. Please try again later.')
        return HttpResponse(content=e, status=400)
Beispiel #7
0
def checkout_payment(request):
    """Conducts a test Stripe charge.

    If payment is successful the order creation is triggered and
    the user's cart is cleared.
    """
    if request.method == "POST":
        payment_form = PaymentForm(request.POST)
        if payment_form.is_valid():
            cart = request.session.get("cart", {})
            cart_total = cart_contents(request)["total"]
            try:
                stripe.Charge.create(
                    amount=int(cart_total * 100),
                    currency="GBP",
                    description=request.user.email,
                    card=payment_form.cleaned_data["stripe_id"])
            except stripe.error.CardError:
                sweetify.error(
                    request,
                    title=
                    "Payment error occurred, please retry with valid credentials.",
                    text="If error persists, contact site owner.",
                    icon="error")
            except stripe.error.InvalidRequestError:
                sweetify.error(
                    request,
                    title="A payment error has occurred.",
                    text="An item may have gone out of stock during checkout.",
                    icon="error")
                return redirect("profile")
            except stripe.error.APIConnectionError:
                sweetify.error(
                    request,
                    title="A payment error has occurred.",
                    text=
                    "Connection to payment handler has failed, please retry later.",
                    icon="error")
                return redirect("profile")
            else:
                sweetify.success(
                    request,
                    title="Payment successful, thank you for your purchase.",
                    icon="success")
                create_order_product_records(request, cart)
                del request.session["cart"]
                return redirect(reverse("profile"))
    else:
        payment_form = PaymentForm()
    return render(
        request, "checkout_payment.html", {
            "page_title": "Payment | PrintCrate",
            "payment_form": payment_form,
            "publishable": settings.STRIPE_PUBLISHABLE
        })
def payment_success(request, order_number):
    """
    Handle successful payments
    """
    save_info = request.session.get('save_info')
    order = get_object_or_404(Order, order_number=order_number)

    messages.success(
        request, f'Order successfully processed! \
        Your order number is {order_number}. A confirmation \
        email will be sent to {order.email}.')

    if request.user.is_authenticated:
        profile = UserProfile.objects.get(user=request.user)
        current_cart = cart_contents(request)
        order.user_profile = profile

        points_earned = order.order_total * 100
        order.points_earned = points_earned
        profile_points = profile.points
        profile.points = profile_points + points_earned

        total_savings = current_cart['savings_total']
        order.savings_total = current_cart['savings_total']
        profile_savings = profile.total_savings
        profile.total_savings += total_savings

        order.save()
        profile.save()
        # Save the user's info
        if save_info:
            profile_data = {
                'default_phone_number': order.phone_number,
                'default_country': order.country,
                'default_zip_or_post': order.zip_or_post,
                'default_town_or_city': order.town_or_city,
                'default_street_address1': order.street_address1,
                'default_street_address2': order.street_address2,
                'default_county': order.county,
            }
            user_profile_form = UserProfileForm(profile_data, instance=profile)
            if user_profile_form.is_valid():
                user_profile_form.save()

    if 'cart' in request.session:
        del request.session['cart']

    template = 'payment/payment_success.html'
    context = {
        'order': order,
    }

    return render(request, template, context)
def profile(request):
    """A view that displays the profile page of a logged in user"""
    # alpha_list = ProductType.objects.get_user_alphas(request.user.id)

    consumed_alpha_list = Product.objects.filter(
        consumed_by=request.user.id).filter(status='consumed')
    consumed_alpha_price_list = []
    incart_alpha_price_list = []
    for alpha in consumed_alpha_list:
        consumed_alpha_price_list.append(alpha.type.price)

    cart_contents = contexts.cart_contents(request)
    for cart_item in cart_contents['subscription_cart_items']:
        incart_alpha_price_list.append(cart_item['product'].price)

    alpha_types_list = ProductType.objects.filter(base__name='alpha')

    beta_products_all = Product.objects.filter(type__base__name='beta')
    charlie_products_all = Product.objects.filter(type__base__name='charlie')

    for alpha in alpha_types_list:
        if (alpha.price in consumed_alpha_price_list):
            alpha.status = 'consumed'
            alpha.image = alpha.image_consumed
            alpha.children = Product.objects.filter(parent=consumed_alpha_list[
                consumed_alpha_price_list.index(alpha.price)].id)
        elif (alpha.price in incart_alpha_price_list):
            alpha.status = 'incart'
            alpha.beta_spawned = beta_products_all.filter(
                type__price=alpha.price).count()
            alpha.beta_consumed = beta_products_all.filter(
                type__price=alpha.price).filter(status='consumed').count()
            alpha.charlie_spawned = charlie_products_all.filter(
                type__price=alpha.price).count()
            alpha.charlie_consumed = charlie_products_all.filter(
                type__price=alpha.price).filter(status='consumed').count()
            alpha.image = alpha.image_available
        else:
            alpha.status = 'available'
            alpha.beta_spawned = beta_products_all.filter(
                type__price=alpha.price).count()
            alpha.beta_consumed = beta_products_all.filter(
                type__price=alpha.price).filter(status='consumed').count()
            alpha.charlie_spawned = charlie_products_all.filter(
                type__price=alpha.price).count()
            alpha.charlie_consumed = charlie_products_all.filter(
                type__price=alpha.price).filter(status='consumed').count()
            alpha.image = alpha.image_available
    print("HERE now rendering")
    print(request)
    print(alpha_types_list)
    return render(request, 'profile.html', {"alpha_list": alpha_types_list})
def checkout_success(request):
    if request.session['cart'] == []:
        return HttpResponseRedirect('/menu')

    template = 'checkout/checkout_success.html'
    cart_items = cart_contents(request)
    context = {
        'cart_items': cart_items['cart_items'],
        'total': cart_items['grand_total']
    }
    request.session['cart'] = []

    return render(request, template, context)
Beispiel #11
0
def checkout_success(request, order_number):
    """ Handle successful checkouts """

    save_info = request.session.get('save_info')
    order = get_object_or_404(Order, order_number=order_number)

    if request.user.is_authenticated:
        #link user to order:
        profile = UserProfile.objects.get(user=request.user)
        order.user_profile = profile
        order.save()

        # Save the user's info
        if save_info:
            profile_data = {
                'default_phone_number': order.phone_number,
                'default_country': order.country,
                'default_postcode': order.postcode,
                'default_town_or_city': order.town_or_city,
                'default_street_address1': order.street_address1,
                'default_street_address2': order.street_address2,
                'default_county': order.county,
            }
            user_profile_form = UserProfileForm(profile_data, instance=profile)
            if user_profile_form.is_valid():
                user_profile_form.save()

    messages.success(request, f'Order successfully processed! \
        Your order number is {order_number}. A confirmation \
        email will be sent to {order.email}.')
    
    current_cart = cart_contents(request)
    total = current_cart['total_price_after_discount']
    discount = current_cart['discount']

    if 'cart' in request.session:
        del request.session['cart']

    template = 'checkout/checkout_success.html'
    context = {
        'order': order,
        'total': total, 
        'discount': discount,
    }

    return render(request, template, context)
Beispiel #12
0
def cache_checkout_data(request):
    try:
        pid = request.POST.get('client_secret').split('_secret')[0]
        stripe.api_key = settings.STRIPE_SECRET_KEY
        ca = request.COOKIES.get('ca')
        print("---ca:", ca)
        current_cart = cart_contents(request)
        ca_tax = current_cart['ca_tax']
        grand_total_ca = current_cart['grand_total_ca']
        stripe_total_ca = round(grand_total_ca * 100)
        # if ship to ca true, modify payment intent for revised order total
        if ca == "true":
            stripe.PaymentIntent.modify(
                pid,
                amount=stripe_total_ca,
                currency=settings.STRIPE_CURRENCY,
                metadata={
                    'cart': json.dumps(request.session.get('cart', {})),
                    'save_info': request.POST.get('save_info'),
                    'username': request.user,
                    'marketing': request.POST.get('marketing'),
                    'ca_tax': ca_tax,
                })
        # if ship anywhere but ca modify intent to include metadata
        stripe.PaymentIntent.modify(pid,
                                    metadata={
                                        'cart':
                                        json.dumps(
                                            request.session.get('cart', {})),
                                        'save_info':
                                        request.POST.get('save_info'),
                                        'username':
                                        request.user,
                                        'marketing':
                                        request.POST.get('marketing'),
                                    })
        return HttpResponse(status=200)
    except Exception as e:
        messages.error(
            request, 'Sorry, your payment cannot be \
            processed right now. Please try again later.')
        return HttpResponse(content=e, status=400)
def create_payment_intent(request):
    """ Create stripe payment intent and pass back to client """

    current_shopping_cart = cart_contents(request)
    ordered_by = request.user
    try:
        intent = stripe.PaymentIntent.create(
            amount=int(current_shopping_cart['cart_grand_total'] * 100),
            currency='gbp',
            metadata=shopping_cart_items(ordered_by,
                                         current_shopping_cart['cart_items']),
        )
        return JsonResponse({
          'clientSecret': intent['client_secret']
        })
    except Exception as e:
        messages.error(request, 'Problem contacting the Stripe payment  \
                                system, please retry your payment later.',
                                extra_tags='payment processing')
        return JsonResponse({'error': str(e)}, status=400)
Beispiel #14
0
 def form_valid(self, form):
     form = self.form_class(self.request.POST)
     cart = self.request.session.get("cart", {})
     cart_total = cart_contents(self.request)["total"]
     try:
         stripe.Charge.create(amount=int(cart_total * 100),
                              currency="GBP",
                              description=self.request.user.email,
                              card=form.cleaned_data["stripe_id"])
     except stripe.error.CardError:
         sweetify.error(
             self.request,
             title=
             "Payment error occurred, please retry with valid credentials.",
             text="If error persists, contact site owner.",
             icon="error")
     except stripe.error.InvalidRequestError:
         sweetify.error(
             self.request,
             title="A payment error has occurred.",
             text="An item may have gone out of stock during checkout.",
             icon="error")
         return redirect("profile")
     except stripe.error.APIConnectionError:
         sweetify.error(
             self.request,
             title="A payment error has occurred.",
             text=
             "Connection to payment handler has failed, please retry later.",
             icon="error")
         return redirect("profile")
     else:
         sweetify.success(
             self.request,
             title="Payment successful, thank you for your purchase.",
             icon="success")
         create_order_product_records(self.request, cart)
         del self.request.session["cart"]
         return redirect(reverse("profile"))
     return JsonResponse({"success": True}, status=200)
Beispiel #15
0
def checkout(request):
    """
    Take the order and user details from the checkout form
    and create the order in the dataabase
    """
    stripe_public_key = settings.STRIPE_PUBLIC_KEY
    stripe_secret_key = settings.STRIPE_SECRET_KEY

    if request.method == 'POST':
        cart = request.session.get('cart', {})

        form_data = {
            'first_name': request.POST['first_name'],
            'last_name': request.POST['last_name'],
            'email': request.POST['email'],
            'telephone': request.POST['telephone'],
            'address_line1': request.POST['address_line1'],
            'address_line2': request.POST['address_line2'],
            'town_or_city': request.POST['town_or_city'],
            'county': request.POST['county'],
            'postcode': request.POST['postcode'],
            'country': request.POST['country'],
        }

        order_form = OrderForm(form_data)
        """
        For each item in the cart, create an order line item
        checking whether the product has a size or not.
        On the rare occassion that the product doesn't exist in the database
        delete the order and return the user to the shopping cart page
        """
        if order_form.is_valid():
            order = order_form.save(commit=False)
            pid = []
            if not request.POST.get('client_secret') is None:
                pid = request.POST.get('client_secret').split('_secret')[0]
            order.stripe_pid = pid
            order.original_cart = json.dumps(cart)
            order.save()
            for item_id, item_data in cart.items():
                try:
                    product = Product.objects.get(id=item_id)
                    if isinstance(item_data, int):
                        order_line_item = OrderLineItem(
                            order=order,
                            product=product,
                            quantity=item_data,
                        )
                        order_line_item.save()
                    else:
                        for size, quantity in item_data['items_by_size'].items(
                        ):
                            order_line_item = OrderLineItem(
                                order=order,
                                product=product,
                                quantity=quantity,
                                product_size=size,
                            )
                            order_line_item.save()
                except Product.DoesNotExist:
                    messages.error(request,
                                   ("One of the products in your cart wasn't "
                                    "found in our database. "
                                    "Please call us for assistance!"))
                    order.delete()
                    return redirect(reverse('view_cart'))

            # Save the info to the user's profile if all is well
            request.session['save_info'] = 'save-info' in request.POST
            return redirect(
                reverse('checkout_success', args=[order.order_number]))
        else:
            messages.error(request, ('There was an error with your form. '
                                     'Please double check your information.'))

    else:
        cart = request.session.get('cart', {})
        if not cart:
            messages.error(
                request,
                "There's nothing in your shopping cart at the moment!")
            return redirect(reverse('products'))

        current_cart = cart_contents(request)
        total = current_cart['grand_total']
        """
        stripe requires the value as an integer as it's a zero-decimal currency
        e.g. £4.99 = 499p
        """
        stripe_total = round(total * 100)
        stripe.api_key = stripe_secret_key
        intent = stripe.PaymentIntent.create(amount=stripe_total,
                                             currency=settings.STRIPE_CURRENCY)
        """
        Attempt to prefill the form with any info
        the user maintains in their profile
        """
        if request.user.is_authenticated:
            try:
                profile = UserProfile.objects.get(user=request.user)
                order_form = OrderForm(
                    initial={
                        'first_name': profile.user.get_full_name().split(
                            ' ')[0],
                        'last_name': profile.user.get_full_name().split(' ')
                        [1],
                        'email': profile.user.email,
                        'telephone': profile.default_telephone,
                        'address_line1': profile.default_address_line1,
                        'address_line2': profile.default_address_line2,
                        'town_or_city': profile.default_town_or_city,
                        'county': profile.default_county,
                        'postcode': profile.default_postcode,
                        'country': profile.default_country,
                    })
            except UserProfile.DoesNotExist:
                order_form = OrderForm()
        else:
            order_form = OrderForm()

    if not stripe_public_key:
        messages.warning(
            request,
            'Stripe public key missing. Please set it in your environment.')

    template = 'checkout/checkout.html'
    context = {
        'order_form': order_form,
        'stripe_public_key': stripe_public_key,
        'client_secret': intent.client_secret,
    }

    return render(request, template, context)
Beispiel #16
0
def change_shipping_method(request):
    """
    A view to take posted information from shipping.js and update Stripe
    payment intent with new shipping selection cost
    Reutns new total, shipping method, and cost to the frontend

    """
    shipping_method = ""
    current_cart = cart_contents(request)
    stripe_secret_key = settings.STRIPE_SECRET_KEY
    intent_id = request.POST.get('intent_id')
    selected_method = request.POST.get('selected')

    # Get standard shipping costs from database
    free_shipping_setting = get_object_or_404(Sitesettings,
                                              name="Free Shipping Threshold")
    shipping = get_object_or_404(Sitesettings, name="Standard Shipping")
    std_shipping = shipping.value
    threshold = free_shipping_setting.value
    shipping_cost = shipping.value

    # Use Selected variable posted
    if selected_method == "1":
        shipping_method = "standard"
        stripe_ship = "Standard Delivery"
        if current_cart['total'] < threshold:
            shipping_cost = std_shipping
        else:
            shipping_cost = 0
    elif selected_method == "2":
        shipping_method = "collect"
        stripe_ship = "Click & Collect"
        shipping_cost = 0
    else:
        shipping_method = "standard"
        stripe_ship = "Standard Delivery"
        shipping_cost = std_shipping

    # Calculate the total based on shipping method selected and shipping cost
    total = Decimal(shipping_cost) + current_cart['total']

    # Check to see if any discount is applied
    if 'discount_total' in request.session:
        total = Decimal(shipping_cost) + Decimal(
            request.session['discount_subtotal'])
        total = round(total, 2)

    # Modify Stripe payment intent to reflect new total
    # based on shipping selection
    stripe_total = round(total * 100)
    stripe.api_key = stripe_secret_key
    stripe.PaymentIntent.modify(
        intent_id,
        amount=stripe_total,
        currency=settings.STRIPE_CURRENCY,
        description=stripe_ship,
    )

    request.session['shipping_cost'] = int(shipping_cost)
    # Update session variable with shipping method selected
    request.session['shipping_method'] = stripe_ship
    data = {
        'total': total,
        'shipping_method': shipping_method,
        'shipping_cost': shipping_cost,
    }

    return JsonResponse(data)
Beispiel #17
0
def checkout(request):
    """ A view that renders the checkout form and validates """

    stripe_public_key = settings.STRIPE_PUBLIC_KEY
    stripe_secret_key = settings.STRIPE_SECRET_KEY

    if request.method == 'POST':
        cart = request.session.get('cart', {})

        form_data = {
            'full_name': request.POST['full_name'],
            'email': request.POST['email'],
            'phone_number': request.POST['phone_number'],
            'country': request.POST['country'],
            'postcode': request.POST['postcode'],
            'town_city': request.POST['town_city'],
            'address': request.POST['address'],
            'address2': request.POST['address2'],
            'county': request.POST['county'],
        }
        order_form = OrderForm(form_data)
        if order_form.is_valid():
            order = order_form.save()
            for item_id, item_data in cart.items():
                try:
                    comp = Comp.objects.get(id=item_id)
                    if isinstance(item_data, int):
                        order_line_item = OrderLineItem(
                            order=order,
                            comp=comp,
                            quantity=item_data,
                        )
                        order_line_item.save()
                except Comp.DoesNotExist:
                    messages.error(request, (
                        "One of the competitions in your cart wasn't found in our database. "
                        "Please call us for assistance!"))
                    order.delete()
                    return redirect(reverse('view_cart'))

            request.session['save_info'] = 'save-info' in request.POST
            return redirect(
                reverse('checkout_success', args=[order.order_number]))
        else:
            messages.error(
                request, 'There was an error with your form. \
                Please double check your information.')
            return redirect(reverse('view_cart'))
    else:
        cart = request.session.get('cart', {})
        if not cart:
            messages.error(request, "You haven't added to your shoebox yet!")
            return redirect(reverse('comps'))

        current_cart = cart_contents(request)
        total = current_cart['total']
        stripe_total = round(total * 100)
        stripe.api_key = stripe_secret_key
        intent = stripe.PaymentIntent.create(
            amount=stripe_total,
            currency=settings.STRIPE_CURRENCY,
        )

        if request.user.is_authenticated:
            try:
                profile = UserProfile.objects.get(user=request.user)
                order_form = OrderForm(
                    initial={
                        'full_name': profile.user.get_full_name(),
                        'email': profile.user.email,
                        'phone_number': profile.default_phone_number,
                        'country': profile.default_country,
                        'postcode': profile.default_postcode,
                        'town_city': profile.default_town_city,
                        'address': profile.default_address,
                        'address2': profile.default_address2,
                        'county': profile.default_county,
                    })
            except UserProfile.DoesNotExist:
                order_form = OrderForm()
        else:
            order_form = OrderForm()

    if not stripe_public_key:
        messages.warning(
            request, 'Stripe public key is missing. \
            Did you forget to set it in your environment?')

    template = 'checkout/checkout.html'
    context = {
        'order_form': order_form,
        'stripe_public_key': stripe_public_key,
        'client_secret': intent.client_secret,
    }

    return render(request, template, context)
Beispiel #18
0
def checkout(request):
    stripe_public_key = settings.STRIPE_PUBLIC_KEY
    stripe_secret_key = settings.STRIPE_SECRET_KEY
    # Obtain contents of cart.context.py
    current_cart = cart_contents(request)
    ca = request.COOKIES.get('ca')
    if request.method == 'POST':
        cart = request.session.get('cart', {})
        form_data = {
            'ship_full_name': request.POST['ship_full_name'],
            'email': request.POST['email'],
            'ship_comp_name': request.POST['ship_comp_name'],
            'ship_phone_number': request.POST['ship_phone_number'],
            'ship_street_address1': request.POST['ship_street_address1'],
            'ship_street_address2': request.POST['ship_street_address2'],
            'ship_city': request.POST['ship_city'],
            'ship_state': request.POST['ship_state'],
            'ship_zipcode': request.POST['ship_zipcode'],
            'bill_full_name': request.POST['bill_full_name'],
            'bill_phone_number': request.POST['bill_phone_number'],
            'bill_street_address1': request.POST['bill_street_address1'],
            'bill_street_address2': request.POST['bill_street_address2'],
            'bill_city': request.POST['bill_city'],
            'bill_state': request.POST['bill_state'],
            'bill_zipcode': request.POST['bill_zipcode'],
        }

        order_form = OrderForm(form_data)
        if order_form.is_valid():
            order = order_form.save(commit=False)
            pid = request.POST.get('client_secret').split('_secret')[0]
            order.stripe_pid = pid
            order.original_cart = json.dumps(cart)
            if ca == "true":
                order.ca_sales_tax = current_cart['ca_tax']
                order.grand_total = current_cart['grand_total_ca']
            order.save()
            for product_id, item_data in cart.items():
                try:
                    product = Product.objects.get(id=product_id)
                    if isinstance(item_data, int):
                        order_line_item = OrderLineItem(
                            order=order,
                            product=product,
                            quantity=item_data,
                        )
                        order_line_item.save()
                except Product.DoesNotExist:
                    messages.error(request, (
                        "One of the products in your bag wasn't found in our database. \
                        Please call us for assistance!"))
                    order.delete()
                    return redirect(reverse('view_bag'))

            request.session['save_info'] = 'save-info' in request.POST
            request.session['marketing'] = 'marketing' in request.POST
            return redirect(
                reverse('checkout_success', args=[order.order_number]))

        else:
            messages.error(
                request, 'There was an error with your form. \
                Please double check your information.')

    cart = request.session.get('cart', {})
    if not cart:
        messages.error(request, "There's nothing in your bag at the moment")
        return redirect(reverse('products'))

    # Reset ca to default false when first load checkout page
    ca = request.COOKIES.get('ca')
    response = HttpResponse()
    response.set_cookie('ca', 'false')
    print("ca_set", request.COOKIES.get('ca'))
    current_cart = cart_contents(request)
    total = current_cart['grand_total']
    stripe_total = round(total * 100)
    stripe.api_key = stripe_secret_key
    intent = stripe.PaymentIntent.create(
        amount=stripe_total,
        currency=settings.STRIPE_CURRENCY,
    )

    # Attempt to prefill the form with any info
    # the user maintains in their profile
    if request.user.is_authenticated:
        try:
            profile = UserProfile.objects.get(user=request.user)
            marketing_value = profile.marketing
            full_name = profile.defaultship_full_name
            order_form = OrderForm(
                initial={
                    'ship_full_name': profile.defaultship_full_name,
                    'email': profile.user.email,
                    'ship_street_address1':
                    profile.defaultship_street_address1,
                    'ship_street_address2':
                    profile.defaultship_street_address2,
                    'ship_city': profile.defaultship_city,
                    'ship_state': profile.defaultship_state,
                    'ship_zipcode': profile.defaultship_zipcode,
                    'ship_phone_number': profile.defaultship_phone_number,
                })
        except UserProfile.DoesNotExist:
            order_form = OrderForm()
    else:
        order_form = OrderForm()
        marketing_value = "false"
        full_name = ""

    ship_state = USStateSelect()
    bill_state = USStateSelect()
    ship_zipcode = USZipCodeField()
    bill_zipcode = USZipCodeField()

    if not stripe_public_key:
        messages.warning(
            request, 'Stripe public key is missing. \
            Did you forget to set it in your environment?')

    template = 'checkout/checkout.html'
    context = {
        'order_form': order_form,
        'stripe_public_key': stripe_public_key,
        'client_secret': intent.client_secret,
        'ship_state': ship_state,
        'bill_state': bill_state,
        'ship_zipcode': ship_zipcode,
        'bill_zipcode': bill_zipcode,
        'marketing': marketing_value,
        'full_name': full_name,
    }

    return render(request, template, context)
def checkout(request):
    """ a view to process customer order details and stripe payment """
    stripe_public_key = settings.STRIPE_PUBLIC_KEY
    if not stripe_public_key:
        print("Error fetching stripe public key \
        - is it definitely exported to settings?")

    stripe_secret_key = settings.STRIPE_SECRET_KEY
    if not stripe_secret_key:
        print("Error fetching stripe secret key \
        - is it definitely exported to settings?")

    cart = request.session.get('cart', {})
    current_cart = cart_contents(request)
    total = current_cart['total']
    if request.method == 'POST':
        form = request.POST
        form_data = {
            'full_name': form['full_name'],
            'email': form['email'],
            'phone_number': form['phone_number'],
            'country': form['country'],
            'postcode': form['postcode'],
            'town_or_city': form['town_or_city'],
            'street_address1': form['street_address1'],
            'street_address2': form['street_address2'],
            'county': form['county'],
            'paid': True,
            'order_total': total,
        }
        order_form = OrderForm(form_data)
        if order_form.is_valid():
            order = order_form.save(commit=False)
            pid = request.POST.get('client_secret').split('_secret')[0]
            order.stripe_pid = pid
            order.original_cart = json.dumps(cart)
            order.save()
            for product_id, quantity in cart.items():
                try:
                    product = get_object_or_404(Product, pk=product_id)
                    order_line_item = OrderLineItem(
                        order=order,
                        product=product,
                        quantity=quantity,
                        lineitem_price_per_unit=product.price,
                        lineitem_total=quantity * product.price)
                    order_line_item.save()

                    # update product stock and sold quantities
                    product.sold_qty = \
                        product.sold_qty + order_line_item.quantity
                    product.stock_qty = \
                        product.stock_qty - order_line_item.quantity
                    product.save()

                except Product.DoesNotExist:
                    messages.error(
                        request,
                        "One of the products your trying to order has been discontinuted \
                        Please call for assistance!")
                    order.delete()
                    return redirect(reverse('cart'))
            request.session['view_confirmation_authorised'] = True
            return redirect(
                reverse('checkout_success', args=[order.order_reference]))
        else:
            messages.error(
                request, "There was an error processing your order. \
            Please double-check your information")
    else:
        if not cart:
            """ prevent users manually accessing checkout url """
            messages.error(request,
                           "There's nothing in your cart at the moment")
            return redirect(reverse('products'))

        stripe_total = round(total * 100)
        stripe.api_key = stripe_secret_key
        intent = stripe.PaymentIntent.create(
            amount=stripe_total,
            currency=settings.STRIPE_CURRENCY,
        )

        if request.user.is_authenticated:
            try:
                profile = UserProfile.objects.get(user=request.user)
                order_form = OrderForm(
                    initial={
                        'full_name': profile.user.first_name + " " +
                        profile.user.last_name,
                        'email': profile.user.email,
                        'phone_number': profile.profile_phone_number,
                        'country': profile.profile_country,
                        'postcode': profile.profile_postcode,
                        'town_or_city': profile.profile_town_or_city,
                        'street_address1': profile.profile_street_address1,
                        'street_address2': profile.profile_street_address2,
                        'county': profile.profile_county,
                    })
            except UserProfile.DoesNotExist:
                order_form = OrderForm()
        else:
            order_form = OrderForm()
        context = {
            'order_form': order_form,
            'stripe_public_key': stripe_public_key,
            'stripe_client_secret': intent.client_secret
        }
        return render(request, 'cart/checkout.html', context)
def checkout(request):
    """
    A view that handles checkout process
    """
    stripe_public_key = settings.STRIPE_PUBLIC_KEY
    stripe_secret_key = settings.STRIPE_SECRET_KEY

    if request.method == 'POST':
        cart = request.session.get('cart', {})

        form_data = {
            'first_name': request.POST['first_name'],
            'last_name': request.POST['last_name'],
            'email': request.POST['email'],
            'address_line_1': request.POST['address_line_1'],
            'address_line_2': request.POST['address_line_2'],
            'town_or_city': request.POST['town_or_city'],
            'county': request.POST['county'],
            'postcode': request.POST['postcode'],
        }

        order_form = OrderForm(form_data)
        if order_form.is_valid():
            order = order_form.save(commit=False)
            pid = request.POST.get('client_secret').split('_secret')[0]
            order.stripe_pid = pid
            order.original_cart = json.dumps(cart)
            order.save()
            for item_id, item_data in cart.items():
                try:
                    product = Product.objects.get(id=item_id)
                    if isinstance(item_data, int):
                        order_line_item = OrderLineItem(
                            order=order,
                            product=product,
                            quantity=item_data,
                        )
                        order_line_item.save()
                    else:
                        items = item_data['items_by_color'].items()
                        for color, quantity in items:
                            order_line_item = OrderLineItem(
                                order=order,
                                product=product,
                                quantity=quantity,
                                product_color=color,
                            )
                            order_line_item.save()
                except Product.DoesNotExist:
                    messages.error(request, (
                        "One of the products in your cart wasn't found in our \
                        database. Please contact us for further assisctance")
                    )
                    order.delete()
                    return redirect(reverse('view_cart'))

            # Save the information to the user profile
            request.session['save_info'] = 'save_info' in request.POST
            return redirect(reverse('checkout_success',
                                    args=[order.order_number]))
        else:
            messages.error(request, 'There was an error with your form. \
                Please double check your information.')

    else:
        cart = request.session.get('cart', {})
        if not cart:
            messages.error(request, "There is no item in your cart.")
            redirect(reverse('onlineshop'))

        current_cart = cart_contents(request)
        total = current_cart['grand_total']
        stripe_total = round(total * 100)
        stripe.api_key = stripe_secret_key
        intent = stripe.PaymentIntent.create(
            amount=stripe_total,
            currency=settings.STRIPE_CURRENCY,
        )

        # Autofill the delivery form
        if request.user.is_authenticated:
            try:
                profile = UserProfile.objects.get(user=request.user)
                order_form = OrderForm(initial={
                    'first_name': profile.user.first_name,
                    'last_name': profile.user.last_name,
                    'email': profile.user.email,
                    'address_line_1': profile.default_address_line_1,
                    'address_line_2': profile.default_address_line_2,
                    'town_or_city': profile.default_town_or_city,
                    'county': profile.default_county,
                    'postcode': profile.default_postcode,
                })
            except UserProfile.DoesNotExist:
                order_form = OrderForm()
        else:
            order_form = OrderForm()

    if not stripe_public_key:
        messages.warning(request, 'Stripe public key was not found. \
            Did you forget to set it in your environment?')

    template = 'checkout/checkout.html'
    context = {
        'order_form': order_form,
        'stripe_public_key': stripe_public_key,
        'client_secret': intent.client_secret
    }

    return render(request, template, context)
Beispiel #21
0
def checkout(request):
    """
    Payment page
    """
    if request.user.is_authenticated:
        if request.method == "POST":
            context = cart_contents(request)["cart_context"]
            user = User.objects.get(id=request.user.id)

            for product in context:
                quiz = product["product"]
                Order.objects.create(quiz=quiz.quiz, customer=request.user)

            subject = "Quizim Receipt"
            html_message = render_to_string("checkout/receipt-email.html",
                                            {"context": context})
            plain_message = strip_tags(html_message)
            from_email = settings.DEFAULT_FROM_EMAIL
            to = user.email
            mail.send_mail(subject,
                           plain_message,
                           from_email, [
                               to,
                           ],
                           html_message=html_message)

            del request.session["cart"]
            return redirect(reverse("checkout:payment_success"))

        else:
            user = User.objects.get(id=request.user.id)

            profile = Profile.objects.get(user=request.user)
            profile_dict = model_to_dict(profile)

            # form will result in unnecessary data
            # retrieved from Profile model remove these
            # fields before passing to
            # PaymentDetailsForm. Also add card holder
            keys_to_remove = [
                "id", "user", "profile_pic", "email_confirmed", "receive_email"
            ]
            for key in keys_to_remove:
                del profile_dict[key]

            default_cardholder = f'{profile.user.first_name} {profile.user.last_name}'
            profile_dict["cardholder"] = default_cardholder

            payment_details_form = PaymentDetailsForm(data=profile_dict)

            contents = cart_contents(request)
            amount = int(contents["total_price"] * 100)

            intent = stripe.PaymentIntent.create(amount=amount,
                                                 currency="eur",
                                                 payment_method_types=["card"])
            stripe_context = {
                "amount": intent.amount,
                "client_secret": intent.client_secret,
                "publishable": settings.STRIPE_PUBLISHABLE
            }

        return render(
            request, "checkout/checkout.html", {
                "stripe_context": stripe_context,
                "payment_details_form": payment_details_form
            })

    else:
        messages.info(request, "You need to log in to checkout of the store")
        return redirect(reverse("cart:view_cart"))
def checkout(request):
    """ A view for the checkout """

    stripe_public_key = settings.STRIPE_PUBLIC_KEY
    stripe_secret_key = settings.STRIPE_SECRET_KEY

    if request.method == 'POST':
        cart = request.session.get('cart', {})

        order = Order(
            username=request.user.username,
            email=request.user.email,
        )
        pid = request.POST.get('client_secret').split('_secret')[0]
        order.stripe_pid = pid
        order.original_cart = json.dumps(cart)
        order.save()

        for item_id, quantity in cart.items():
            try:
                product = Product.objects.get(id=item_id)
                order_line_item = OrderLineItem(
                    order=order,
                    product=product,
                    quantity=quantity,
                )
                order_line_item.save()
            except Product.DoesNotExist:
                messages.error(request, ("One of the products in your cart \
                        was not found in the database. "
                                         "We apologise. Please contact us for \
                        assistance via the contact page!"))
                order.delete()
                return redirect(reverse('view_cart'))

        return redirect(reverse('checkout_success', args=[order.order_number]))
    else:
        cart = request.session.get('cart', {})
        if not cart:
            messages.error(
                request, "There's nothing in your \
                cart at the moment")
            return redirect(reverse('products'))

        current_cart = cart_contents(request)
        total = current_cart['grand_total']
        stripe_total = round(total * 100)
        stripe.api_key = stripe_secret_key
        intent = stripe.PaymentIntent.create(
            amount=stripe_total,
            currency=settings.STRIPE_CURRENCY,
        )

    if not stripe_public_key:
        messages.warning(
            request, 'Stripe public key missing. \
            Did you forget to set it in your environment?')

    template = 'checkout/checkout.html'
    context = {
        'stripe_public_key': stripe_public_key,
        'client_secret': intent.client_secret,
    }

    return render(request, template, context)
def checkout(request):
    context_cart = cart_contents(request)
    if context_cart['cart_items'] == []:
        return HttpResponseRedirect('/menu')

    stripe_public_key = settings.STRIPE_PUBLIC_KEY
    stripe_secret_key = settings.STRIPE_SECRET_KEY
    session_cart = request.session.get('cart', [])
    store_id = request.session['store']
    store = get_object_or_404(Store, pk=store_id)

    if request.user.is_anonymous:
        user = None
    else:
        user = request.user
    print('User: '******'grand_total'])
    delivery = request.session['delivery']

    if request.method == 'POST':
        form_data = {
            'name': request.POST['name'],
            'email': request.POST['email'],
            'phone_number': request.POST['phone_number'],
            'street_address1': request.POST['street_address1'],
            'street_address2': request.POST['street_address2'],
            'county': request.POST['county'],
        }

        order_form = OrderForm(form_data)
        if order_form.is_valid():
            order = order_form.save(commit=False)
            order.store = store
            order.delivery = delivery
            order.order_total = context_cart['grand_total']
            order.stripe_pid = request.POST['pid']
            order.user = user
            order.save()
            for item in context_cart['cart_items']:
                order_line_item = OrderLineItem(
                    order=order,
                    product=item['product'],
                    size=item['size'],
                    quantity=item['quantity'],
                    lineitem_total=item['sub_total'],
                    customizations=item['customizations'])
                order_line_item.save()
            request.session['order_number'] = order.order_number
            return redirect(reverse('checkout_success'))

        else:
            print('invalid form')

    else:
        stripe_total = round(grand_total * 100)
        stripe.api_key = stripe_secret_key
        cart = json.dumps(session_cart)
        #Check if cart size exceeds the stripe metadata limit of 500 chars. If yes, set cart as 'empty'
        if len(cart) > 500:
            cart = 'Empty'
        intent = stripe.PaymentIntent.create(amount=stripe_total,
                                             currency=settings.STRIPE_CURRENCY,
                                             metadata={
                                                 'cart': cart,
                                                 'delivery': delivery,
                                                 'store_id': store_id,
                                             })
        pid = intent.id
        customer_address = request.session['customer_address']
        customer_details = request.session.get('customer_details')
        if customer_details:
            order_form = OrderForm(
                initial={
                    'name': customer_details['name'],
                    'email': customer_details['email'],
                    'phone_number': customer_details['contact_number'],
                    'street_address1': customer_address['street_address1'],
                    'street_address2': customer_address['street_address2'],
                    'county': customer_address['county'],
                })
        else:
            order_form = OrderForm(
                initial={
                    'street_address1': customer_address['street_address1'],
                    'street_address2': customer_address['street_address2'],
                    'county': customer_address['county'],
                })
        context = {
            'stripe_public_key': stripe_public_key,
            'client_secret': intent.client_secret,
            'pid': pid,
            'order_form': order_form,
        }
        return render(request, 'checkout/checkout.html', context)
def view_checkout(request):
    """ A view to show the checkout form and save the order """

    current_shopping_cart = cart_contents(request)
    if request.POST:
        form_data = {
            'full_name': request.POST['full_name'],
            'email': request.POST['email'],
            'phone_number': request.POST['phone_number'],
            'street_address1': request.POST['street_address1'],
            'street_address2': request.POST['street_address2'],
            'town_or_city': request.POST['town_or_city'],
            'postcode': request.POST['postcode'],
            'county': request.POST['county'],
            'country': request.POST['country'],
            'stripe_pid': request.POST['stripe_pid'],
        }

        form = OrderForm(form_data)

        if form.is_valid():
            order = form.save(commit=False)
            original_cart = current_shopping_cart['cart_items']
            json_cart = []
            for item in original_cart:
                json_item = {}
                json_item['product_id'] = item['product_id']
                json_item['quantity'] = item['quantity']
                json_item['name'] = item['name']
                json_item['price'] = str(item['price'])
                json_item['invite_data'] = item['invite_data']
                json_cart.append(json_item)

            order.original_cart = json.dumps(json_cart)

            if request.user.is_authenticated:
                profile = User.objects.get(username=request.user)
                order.user = profile

            order.save()
            for item in original_cart:
                product = get_object_or_404(Product, pk=item['product_id'])
                order_line_item = OrderLineItem(
                    order=order,
                    product=product,
                    quantity=Decimal(item['quantity']),
                    invite_data=item['invite_data'],
                )
                order_line_item.save()

            messages.success(request,
                             f'Thank you, payment of £{order.grand_total:.2f} \
                             successfully received. Your order number is \
                             [{order.pk:010}]. Full order confirmation details\
                             are displayed below.',
                             extra_tags='Order confirmation')
            return redirect(reverse('checkout_success', args=[order.pk]))

        else:
            messages.error(request, 'There was an error with your form entry, \
                 please contact our sales team to check your order details, \
                 as payment may have already been processed. Thank you')
    else:
        grand_total = current_shopping_cart['cart_grand_total']
        if grand_total > 0:
            form_data = {}
            if request.user.is_authenticated:
                if len(request.user.first_name) > 0:
                    fullname = (f'{request.user.first_name.title()} '
                                f'{request.user.last_name.title()}')
                    form_data['full_name'] = fullname

                form_data['email'] = request.user.email

            form = OrderForm(initial=form_data)
            context = {
                'form': form,
            }
            return render(request, 'checkout/checkout.html', context)

        else:
            return redirect('view_cart')
Beispiel #25
0
def checkout(request):
    if request.method == "POST":
        order_form = OrderForm(request.POST)
        payment_form = MakePaymentForm(request.POST)
        print("order form is valid:" + str(order_form.is_valid()))
        print("payment form is valid:" + str(payment_form.is_valid()))
        if order_form.is_valid() and payment_form.is_valid():
            order = order_form.save(commit=False)
            order.date = timezone.now()
            order.save()

            cart_contents(request)
            cartDict = request.session.get('cart', {})
            cart_items = []
            total = 0
            product_count = 0
            if cartDict:
                cart = Cart.objects.get(id=cartDict['id'])
                for cart_line_item in cart.cartlineitem_set.all():
                    product = cart_line_item.product
                    total += cart_line_item.quantity * product.price
                    line_total = cart_line_item.quantity * product.price
                    product_count += cart_line_item.quantity
                    cart_items.append({
                        'id': cart_line_item.id,
                        'quantity': cart_line_item.quantity,
                        'product': product,
                        'line_total': line_total
                    })
                    order_line_item = OrderLineItem(order=order,
                                                    product=product,
                                                    quantity=product_count)
                    order_line_item.save()

            try:
                customer = stripe.Charge.create(
                    amount=int(total * 100),
                    currency="NZD",
                    description=order_form.cleaned_data['email'],
                    card=payment_form.cleaned_data['stripe_id'])

            except stripe.error.CardError:
                messages.error(request, "Your card was declined!")

            if customer.paid:

                messages.error(request, "You have successfully paid")
                request.session['cart'] = {}
                if request.user.is_authenticated:
                    try:
                        cart_model = Cart.objects.get(  #trys to get cart by user id if it exists
                            user=User(id=request.user.id))
                        cart_model.delete()  #if cart exists it will delete it

                        cart_get = Cart(user=request.user)
                        cart_get.save()  #creates a new cart
                        request.session['cart'] = model_to_dict(cart_get)

                    except Cart.DoesNotExist:
                        cart_model = None  #if cart doesn't exist does nothing

                return redirect(reverse('products'))
            else:
                messages.error(request, "Unable to take payment")
        else:
            print(payment_form.errors)
            messages.error(request,
                           "We were unable to take a payment with that card!")
    else:
        payment_form = MakePaymentForm()
        order_form = OrderForm(
            initial={
                'email':
                request.user.email if request.user.is_authenticated else
                ''  #will prepopulate if user is authenticated otherwise will leave blank
            })

    return render(
        request, "checkout.html", {
            "order_form": order_form,
            "payment_form": payment_form,
            "publishable": settings.STRIPE_PUBLISHABLE
        })
def checkout(request):
    stripe_public_key = settings.STRIPE_PUBLIC_KEY
    stripe_secret_key = settings.STRIPE_SECRET_KEY

    if request.method == 'POST':
        cart = request.session.get('cart', {})

        form_data = {
            'full_name': request.POST['full_name'],
            'email': request.POST['email'],
            'table_number': request.POST['table_number'],
        }
        order_form = OrderForm(form_data)

        if order_form.is_valid():
            order = order_form.save(commit=False)
            pid = request.POST.get('client_secret').split('_secret')[0]
            order.stripe_pid = pid
            order.original_cart = json.dumps(cart)
            order.save()
            for item_id, item_data in cart.items():
                try:
                    product = Product.objects.get(id=item_id)
                    if isinstance(item_data, int):
                        order_line_item = OrderLineItem(
                            order=order,
                            product=product,
                            quantity=item_data,
                        )
                        order_line_item.save()

                except Product.DoesNotExist:
                    messages.error(request, (
                        "One of the products in your cart wasn't found in our database. "
                        "Please call us for assistance!"))
                    order.delete()
                    return redirect(reverse('view_cart'))

            request.session['save_info'] = 'save-info' in request.POST
            return redirect(
                reverse('checkout_success', args=[order.order_number]))
        else:
            messages.error(
                request, 'There was an error with your form. \
                                    Please double check your information.')

    else:
        cart = request.session.get('cart', {})
        if not cart:
            messages.error(request, "You haven't ordered anything yet.")
            return redirect(reverse('products'))

        current_cart = cart_contents(request)
        total = current_cart['total']
        stripe_total = round(total * 100)
        stripe.api_key = stripe_secret_key
        intent = stripe.PaymentIntent.create(
            amount=stripe_total,
            currency=settings.STRIPE_CURRENCY,
        )

        order_form = OrderForm()

    if not stripe_public_key:
        messages.warning(
            request,
            f"Didn't find Stripe public key. Check environment variables.")

    template = 'checkout/checkout.html'
    context = {
        'order_form': order_form,
        'stripe_public_key': stripe_public_key,
        'client_secret': intent.client_secret,
    }

    return render(request, template, context)
Beispiel #27
0
def checkout(request):
    stripe_public_key = settings.STRIPE_PUBLIC_KEY
    stripe_secret_key = settings.STRIPE_SECRET_KEY

    if request.method == 'POST':
        cart = request.session.get('cart', {})

        form_data = {
            'full_name': request.POST['full_name'],
            'email': request.POST['email'],
            'phone_number': request.POST['phone_number'],
            'country': request.POST['country'],
            'postcode': request.POST['postcode'],
            'town_or_city': request.POST['town_or_city'],
            'street_address1': request.POST['street_address1'],
            'street_address2': request.POST['street_address2'],
            'county': request.POST['county'],
        }

        order_form = OrderForm(form_data)
        if order_form.is_valid():
            order = order_form.save(commit=False)
            pid = request.POST.get('client_secret').split('_secret')[0]
            order.stripe_pid = pid
            order.original_cart = json.dumps(cart)
            order.save()
            for item_id, item_data in cart.items():
                try:
                    product = Product.objects.get(id=item_id)
                    if isinstance(item_data, int):
                        order_line_item = OrderLineItem(
                            order=order,
                            product=product,
                            quantity=item_data,
                        )
                        order_line_item.save()
                    else:
                        for size, quantity in item_data['items_by_size'].items(
                        ):
                            order_line_item = OrderLineItem(
                                order=order,
                                product=product,
                                quantity=quantity,
                                product_size=size,
                            )
                            order_line_item.save()
                except Product.DoesNotExist:
                    messages.error(request,
                                   ("One of the products in your cart wasn't "
                                    "found in our database. "
                                    "Please call us for assistance!"))
                    order.delete()
                    return redirect(reverse('view_cart'))

            # Save the info to the user's profile if all is well
            request.session['save_info'] = 'save-info' in request.POST
            return redirect(
                reverse('checkout_success', args=[order.order_number]))
        else:
            messages.error(request, ('There was an error with your form. '
                                     'Please double check your information.'))
    else:
        cart = request.session.get('cart', {})
        if not cart:
            messages.error(request,
                           "There's nothing in your cart at the moment")
            return redirect(reverse('products'))

        current_cart = cart_contents(request)
        total = current_cart['grand_total']
        stripe_total = round(total * 100)
        stripe.api_key = stripe_secret_key
        intent = stripe.PaymentIntent.create(
            amount=stripe_total,
            currency=settings.STRIPE_CURRENCY,
        )

        # Attempt to prefill the form with any info
        # the user maintains in their profile

        if request.user.is_authenticated:
            try:
                profile = UserProfile.objects.get(user=request.user)
                order_form = OrderForm(
                    initial={
                        'full_name': profile.user.get_full_name(),
                        'email': profile.user.email,
                        'phone_number': profile.default_phone_number,
                        'country': profile.default_country,
                        'postcode': profile.default_postcode,
                        'town_or_city': profile.default_town_or_city,
                        'street_address1': profile.default_street_address1,
                        'street_address2': profile.default_street_address2,
                        'county': profile.default_county,
                    })
            except UserProfile.DoesNotExist:
                order_form = OrderForm()
        else:
            order_form = OrderForm()

    if not stripe_public_key:
        messages.warning(request, ('Stripe public key is missing.'))

    template = 'checkout/checkout.html'
    context = {
        'order_form': order_form,
        'stripe_public_key': stripe_public_key,
        'client_secret': intent.client_secret,
    }

    return render(request, template, context)
Beispiel #28
0
def checkout(request):
    """
    Display a view to purchase items in cart. Checks user has no duplicate products
    and processes Stripe payment.
    """
    stripe_public_key = settings.STRIPE_PUBLISHABLE
    stripe_secret_key = settings.STRIPE_SECRET

    if request.method == 'POST':
        cart = request.session.get('cart', {})

        form_data = {
            'full_name': request.POST['full_name'],
            'email': request.POST['email'],
            'phone_number': request.POST['phone_number'],
        }
        order_form = OrderForm(form_data)

        if order_form.is_valid():
            order = order_form.save(commit=False)
            pid = request.POST.get('client_secret').split('_secret')[0]
            order.stripe_pid = pid
            order.original_cart = json.dumps(cart)
            order.save()
            for item_id, item_data in cart.items():
                try:
                    product = Product.objects.get(id=item_id)
                    if isinstance(item_data, int):
                        order_line_item = OrderLineItem(
                            order=order,
                            product=product,
                            quantity=item_data,
                        )
                        order_line_item.save()
                except Product.DoesNotExist:
                    messages.error(request, (
                        "One of the products in your bag wasn't found in our database. "
                        "Please call us for assistance!"))
                    order.delete()
                    return redirect(reverse('view_bag'))

            request.session['save_info'] = 'save-info' in request.POST
            return redirect(
                reverse('checkout_success', args=[order.order_number]))
        else:
            messages.error(
                request, 'There was an error with your form. \
                Please double check your information.')
    else:
        cart = request.session.get('cart', {})
        if not cart:
            messages.error(request,
                           "There's nothing in your cart at the moment")
            return redirect(reverse('products'))

        current_cart = cart_contents(request)
        total = current_cart['grand_total']
        stripe_total = round(total * 100)
        stripe.api_key = stripe_secret_key
        intent = stripe.PaymentIntent.create(
            amount=stripe_total,
            currency=settings.STRIPE_CURRENCY,
        )

        if request.user.is_authenticated:
            try:
                profile = UserProfile.objects.get(user=request.user)
                order_form = OrderForm(
                    initial={
                        'full_name': profile.user.get_full_name(),
                        'email': profile.user.email,
                        'phone_number': profile.default_phone_number,
                    })
            except UserProfile.DoesNotExist:
                order_form = OrderForm()
        else:
            order_form = OrderForm()

    if not stripe_public_key:
        messages.warning(
            request, 'Stripe public key is missing. \
            Did you forget to set it in your environment?')

    template = 'checkout/checkout.html'
    context = {
        'order_form': order_form,
        'stripe_public_key': stripe_public_key,
        'client_secret': intent.client_secret,
    }

    return render(request, template, context)
def checkout(request):
    stripe_secret_key = settings.STRIPE_SECRET_KEY
    stripe_public_key = settings.STRIPE_PUBLIC_KEY

    if request.method == 'POST':
        cart = request.session.get('cart', {})

        form_data = {
            'name': request.POST['name'],
            'email': request.POST['email'],
            'phone_number': request.POST['phone_number'],
            'country': request.POST['country'],
            'postcode': request.POST['postcode'],
            'city': request.POST['city'],
            'street_address1': request.POST['street_address1'],
            'street_address2': request.POST['street_address2'],
        }
        booking_form = BookingForm(form_data)

        if booking_form.is_valid:
            booking = booking_form.save()
            for item_id, data in cart.items():
                try:
                    tasker = Tasker.objects.get(id=item_id)
                    date = data[0]
                    time = data[1]
                    hours = data[2]
                    cost = hours * tasker.price
                    service_charge = Decimal(cost * settings.STANDARD_SERVICE_CHARGE/100)
                    sub_total = cost + service_charge

                    Booking_line_item = BookingLineItem(
                        booking=booking,
                        tasker=tasker,
                        booked_date=date,
                        booked_time=time,
                        hours=hours,
                        cost=cost,
                        lineitem_total=sub_total,
                    )
                    Booking_line_item.save()

                except Tasker.DoesNotExist:
                    messages.error(request, (
                        "Sorry we do not have any date avilable!")
                    )
                    booking.delete()
                    return redirect(reverse('view_cart'))

            request.session['save_info'] = 'save-info' in request.POST
            return redirect(reverse('checkout_success', args=[booking.booking_number]))
        else:
            messages.error(request, 'There was an error with your form. \
                Please double check your information.')
    else:
        cart = request.session.get('cart', {})
        if not cart:
            messages.error(request, 'you have no bookings')
            return redirect(reverse('tasker'))

        current_cart = cart_contents(request)
        total = current_cart['grand_total']
        stripe_total = round(total*100)
        stripe.api_key = stripe_secret_key
        intent = stripe.PaymentIntent.create(
            amount=stripe_total,
            currency=settings.STRIPE_CURRENCY,
        )

        booking_form = BookingForm()

    if not stripe_public_key:
        messages.warning(
            request, 'stripe publick key missing */ set it in your enviroment')

    template = 'checkout/checkout.html'
    context = {
        'booking_form': booking_form,
        'stripe_public_key': stripe_public_key,
        'client_secret': intent.client_secret,
    }

    return render(request, template, context)
Beispiel #30
0
def checkout(request):
    stripe_public_key = settings.STRIPE_PUBLIC_KEY
    stripe_secret_key = settings.STRIPE_SECRET_KEY

    if request.method == 'POST':
        cart = request.session.get('cart', {})
        form_data = {
            'full_name': request.POST['full_name'],
            'email': request.POST['email'],
            'phone_number': request.POST['phone_number'],
            'country': request.POST['country'],
            'postcode': request.POST['postcode'],
            'town_or_city': request.POST['town_or_city'],
            'street_address1': request.POST['street_address1'],
            'street_address2': request.POST['street_address2'],
            'county': request.POST['county'],
        }
        order_form = OrderForm(form_data)
        if order_form.is_valid():
            order = order_form.save(commit=False)
            pid = request.POST.get('client_secret').split('_secret')[0]
            order.stripe_pid = pid
            order.original_cart = json.dumps(cart)
            order.save()
            for item_id, quantity in cart.items():
                try:
                    product = Album.objects.get(id=item_id)
                    order_line_item = OrderLineItem(order=order,
                                                    product=product,
                                                    quantity=quantity)
                    order_line_item.save()
                except Album.DoesNotExist:
                    messages.error(
                        request,
                        (f'Album with title {product.title} could'
                         ' not be processed. Please contact us for details.'))
                    order.delete()
                    return redirect(reverse('view_cart'))

            request.session['save_info'] = 'save-info' in request.POST
            return redirect(
                reverse('checkout_success', args=[order.order_number]))

    else:
        cart = request.session.get('cart', {})
        if not cart:
            messages.error(request, 'Your cart is empty')
            return redirect(reverse('products'))

        current_cart = cart_contents(request)
        total = current_cart['grand_total']
        stripe_total = round(total * 100)
        stripe.api_key = stripe_secret_key
        intent = stripe.PaymentIntent.create(
            amount=stripe_total,
            currency=settings.STRIPE_CURRENCY,
        )

        if request.user.is_authenticated:
            try:
                profile = UserProfile.objects.get(user=request.user)
                order_form = OrderForm(
                    initial={
                        'full_name': profile.default_full_name,
                        'email': profile.user.email,
                        'phone_number': profile.default_phone_number,
                        'country': profile.default_country,
                        'postcode': profile.default_postcode,
                        'town_or_city': profile.default_town_or_city,
                        'street_address1': profile.default_street_address1,
                        'street_address2': profile.default_street_address2,
                        'county': profile.default_county,
                    })
            except UserProfile.DoesNotExist:
                order_form = OrderForm()
        else:
            order_form = OrderForm()

    template = 'checkout/checkout.html'
    context = {
        'order_form': order_form,
        'stripe_public_key': stripe_public_key,
        'client_secret': intent.client_secret
    }

    return render(request, template, context)