Example #1
0
 def post(self, request):
     form = UserAddressForm(request=request, data=request.POST)
     if form.is_valid():
         user = request.user
         addr = UserAddress()
         is_default = form.cleaned_data.get('chkAgree')
         print(is_default)
         if is_default:
             UserAddress.objects.filter(
                 user=user, is_valid=True,
                 is_default=True).update(is_default=False)
         else:
             is_default = 0
         addr.user = user
         addr.is_default = int(is_default)
         addr.province = form.cleaned_data['txtProvince']
         addr.city = form.cleaned_data['txtCity']
         addr.area = form.cleaned_data['txtArea']
         addr.address = form.cleaned_data['txtAddress']
         addr.username = form.cleaned_data['txtAcceptName']
         addr.phone = form.cleaned_data['txtMobile']
         addr.email = form.cleaned_data['txtEmail']
         addr.post_code = form.cleaned_data['txtPostCode']
         addr.save()
         data = {'status': 1, 'msg': '添加成功'}
     else:
         data = {'status': 0, 'msg': '添加失败,请检查输入内容'}
         for e in form.errors:
             err = form.errors[e][0]
             data = {'status': 0, 'msg': '添加失败' + err}
     return JsonResponse(data)
Example #2
0
def address(request):
    try:
        user_address = UserAddres.objects.filter(user=request.user).last() # grab stored address
        initial = {
                    'address': user_address.address,
                    'address2': user_address.address2,
                    'city': user_address.city,
                    'country': user_address.country,
                    'zipcode': user_address.zipcode,
                    'phone': user_address.phone
        }
        
        address_form = UserAddressForm(request.POST or initial) # display stored address

    except:
        address_form = UserAddressForm(request.POST or None) # assign new address
        
    if request.method == 'POST':
        # try:
        #     user_address = UserAddres.objects.filter(user=request.user).first()
        #     user_address.delete()
        # except:
        #     user_address = None

        if address_form.is_valid:
            new_address = address_form.save(commit=False)
            new_address.user = request.user
            new_address.save()
            return redirect(reverse('checkout'))

    context = {
        'address_form':address_form,
    }

    return render(request, 'orders/address.html', context)
Example #3
0
def editAddress(request, addressId):
    instance = get_object_or_404(UserAddress, pk=addressId)
    if request.method == 'POST':
        upForm = UserAddressForm(request.POST, instance)
        if upForm.is_valid():
            shippingAddress1 = upForm.cleaned_data['shippingAddress1']
            shippingAddress2 = upForm.cleaned_data['shippingAddress2']
            shippingCity = upForm.cleaned_data['shippingCity']
            shippingState = upForm.cleaned_data['shippingState']
            phone1 = upForm.cleaned_data['phone1']
            phone2 = upForm.cleaned_data['phone2']
            firstName = upForm.cleaned_data['firstName']
            lastName = upForm.cleaned_data['lastName']
            user = request.user
            u = UserAddress(shippingAddress1=shippingAddress1,
                            shippingAddress2=shippingAddress2,
                            shippingCity=shippingCity,
                            shippingState=shippingState,
                            firstName=firstName,
                            lastName=lastName,
                            phone1=phone1,
                            phone2=phone2,
                            user=user,
                            pk=addressId)
            u.save()
            return redirect('myAccount')
    else:
        upForm = UserAddressForm(instance=instance)
    return render(request, 'profile.html', {'pform': upForm})
Example #4
0
def userAddress(request):

    print(UserAddress.objects.all())
    if request.method == 'POST':
        upForm = UserAddressForm(request.POST)
        if upForm.is_valid():
            shippingAddress1 = upForm.cleaned_data['shippingAddress1']
            shippingAddress2 = upForm.cleaned_data['shippingAddress2']
            shippingCity = upForm.cleaned_data['shippingCity']
            shippingState = upForm.cleaned_data['shippingState']
            phone1 = upForm.cleaned_data['phone1']
            phone2 = upForm.cleaned_data['phone2']
            user = request.user
            u = UserAddress(shippingAddress1=shippingAddress1,
                            shippingAddress2=shippingAddress2,
                            shippingCity=shippingCity,
                            shippingState=shippingState,
                            phone1=phone1,
                            phone2=phone2,
                            user=user)
            u.save()
            return redirect('myAccount')
    else:
        upForm = UserAddressForm
    return render(request, 'profile.html', {'pform': upForm})
Example #5
0
def add_user_address(request):
    print(request.GET)
    try:
        next_page = request.GET.get("next")
    except:
        next_page = None
    form = UserAddressForm(request.POST or None)
    if request.method == "POST":
        if form.is_valid():
            new_address = form.save(commit=False)
            new_address.user = request.user
            new_address.save()
            is_default = form.cleaned_data["default"]
            if is_default:
                default_address, created = UserDefaultAddress.objects.get_or_create(
                    user=request.user)
                default_address.shipping = new_address
                default_address.save()
            if next_page is not None:
                return HttpResponseRedirect(
                    reverse(str(next_page)) + "?address_added=true")

    btn = "Save Address"
    form_title = "Add New Address"
    return render(request, "form.html", {
        "form": form,
        "btn": btn,
        "form_title": form_title
    })
Example #6
0
def address_edit(request, pk):
    """地址新增或者编辑"""
    # 用request.user取到user,传给form表单类的实例对象
    user = request.user
    addr = None
    # 前端代码中所在地区为什么没有显示,是因为赋值,在form表单上自己定义的地址,可以
    # 初始化的进行赋值
    initial = {}
    # 如果pk是数字,则表示修改
    if pk.isdigit():
        # 查询相关的地址信息
        addr = get_object_or_404(UserAddress, pk=pk, user=user, is_valid=True)
        # 得到省市区赋值给初始化的地址,这个get_regin_format是在view中写好的
        initial['region'] = addr.get_regin_format()
    if request.method == 'POST':
        form = UserAddressForm(
            request=request,
            data=request.POST,
            # 之前是只在get第一次请求的时候加上了下面这两个参数,但是保存的
            # 时候是新增了一个地址,加上这两个参数后就是修改原来的地址了
            instance=addr,
            initial=initial)
        if form.is_valid():
            form.save()
            return redirect('accounts:address_list')
    else:
        # 在是get请求的时候把这个地址传过去,因为post是需要提交表单的,get就是第一次请求的时候有
        # 一个默认地址,这样不会有省市区的默认值,加上initial=initial就有了
        # instance=addr传递到form中
        form = UserAddressForm(request=request, instance=addr, initial=initial)
    return render(request, 'address_edit.html', {'form': form})
Example #7
0
def checkout(request):
    try:
        the_id = request.session['cart_id']
        cart = Cart.objects.get(id=the_id)
    except:
        the_id = None
        #return HttpResponseRedirect("/cart/")
        return HttpResponseRedirect(reverse("cart"))

    try:
        new_order = Order.objects.get(cart=cart)
    except Order.DoesNotExist:
        new_order = Order()
        new_order.cart = cart
        new_order.user = request.user
        new_order.order_id = id_generator()
        new_order.save()
    except:
        # work on some error message
        return HttpResponseRedirect(reverse("cart"))

    address_form = UserAddressForm(request.POST or None)
    if address_form.is_valid():
        new_address = address_form.save(commit=False)
        new_address.user = request.user
        new_address.save()

    #assign address
    #run credit card
    if new_order.status == "Đã giao hàng":
        #cart.delete()
        del request.session['cart_id']
        del request.session['items_total']
        return HttpResponseRedirect(reverse("cart"))

    context = {"address_form": address_form}
    template = "orders/checkout.html"

    return render(request, template, context)
Example #8
0
def checkout(request):
	try:
		the_id = request.session['cart_id']
		cart = Cart.objects.get(id=the_id)
	except:
		the_id = None
		#return HttpResponseRedirect("/cart/")
		return HttpResponseRedirect(reverse("cart"))
	
	try:
		new_order = Order.objects.get(cart=cart)
	except Order.DoesNotExist:
		new_order = Order()
		new_order.cart = cart
		new_order.user = request.user
		new_order.order_id = id_generator()
		new_order.save()
	except:
		# work on some error message
		return HttpResponseRedirect(reverse("cart"))

	address_form = UserAddressForm(request.POST or None)
	if address_form.is_valid():
		new_address = address_form.save(commit=False)
		new_address.user = request.user
		new_address.save()
	##1 add shipping address
	##2 add billing address
	#3 add and run credit card 
	if new_order.status == "Finished":
		#cart.delete()
		del request.session['cart_id']
		del request.session['items_total']
		return HttpResponseRedirect(reverse("cart"))

	context = {"address_form": address_form}
	template = "orders/checkout.html"
	return render(request, template, context)
Example #9
0
def checkout(request):

    try:
        the_id = request.session['cart_id']
        cart = Cart.objects.get(id=the_id)

    except:
        the_id = None
        return HttpResponseRedirect(reverse("cart"))

    try:
        new_order = Order.objects.get(cart=cart)
    except Order.DoesNotExist:
        new_order = Order()
        new_order.cart = cart
        new_order.user = request.user
        new_order.order_id = id_generator()
        new_order.save()
    except:
        return HttpResponseRedirect(reverse("cart"))

    try:
        address_added = request.Get.get("address_added")
        print(address_added)
    except:
        address_added = None
    if address_added is None:
        address_form = UserAddressForm()
    else:
        address_form = None

    current_addresses = UserAddress.objects.filter(user=request.user)
    billing_addresses = UserAddress.objects.get_billing_addresses(
        user=request.user)

    if request.method == "POST":
        print(request.POST.get('stripeToken'))

    if new_order.status == "Finished":
        del request.session['cart_id']
        del request.session['items_total']

    context = {
        'address_form': address_form,
        'current_addresses': current_addresses,
        'billing_addresses': billing_addresses,
        'stripe_pub': stripe_pub,
    }
    template = "orders/checkout.html"
    return render(request, template, context)
Example #10
0
def address_edit(request, pk):
    user = request.user
    addr = None
    initial = {}
    if pk.isdigit():
        addr = get_object_or_404(UserAddress, pk=pk, user=user, is_valid=True)
        initial['region'] = addr.get_region_format()
    if request.method == 'POST':
        form = UserAddressForm(request=request, data=request.POST, initial=initial, instance=addr)
        if form.is_valid():
            form.save()
            return redirect('accounts:address_list')
    else:
        form = UserAddressForm(request=request, instance=addr, initial=initial)
    return render(request, 'address_edit.html', {
        'form': form
    })
Example #11
0
def address_edit(request, pk):
    """ Add address or edit """
    user = request.user
    addr = None
    initial = {}
    # If PK is a number, it means modification
    if pk.isdigit():
        # Query related address information
        addr = get_object_or_404(UserAddress, pk=pk, user=user, is_valid=True)
        initial['region'] = addr.get_region_format()
    if request.method == 'POST':
        form = UserAddressForm(request=request,
                               data=request.POST,
                               initial=initial,
                               instance=addr)
        if form.is_valid():
            form.save()
            return redirect('accounts:address_list')
    else:
        form = UserAddressForm(request=request, instance=addr, initial=initial)
    return render(request, 'address_edit.html', {'form': form})
Example #12
0
def address_edit(request, pk):
    """地址新增及修改"""
    user = request.user
    addr = None
    initial = {}
    # 如果 pk 是数字, 则表示修改
    if pk.isdigit():
        # 查询相关的地址信息
        addr = get_object_or_404(UserAddress, pk=pk, user=user, is_valid=True)
        initial["region"] = addr.get_region_format()
    if request.method == "POST":
        form = UserAddressForm(request=request,
                               data=request.POST,
                               instance=addr,
                               initial=initial)
        if form.is_valid():
            form.save()
            return redirect("accounts:address_list")
    else:
        form = UserAddressForm(request=request, instance=addr, initial=initial)
    return render(request, "address_edit.html", {
        "form": form,
    })
Example #13
0
def order_payment(request, cart_id, order_id):
    if request.user.is_authenticated:
        cart = get_object_or_404(Cart, id=cart_id, user=request.user)
        order = get_object_or_404(Order, order_id=order_id)
        cart_products = CartProduct.objects.filter(cart=cart)
        ud_address = UserAddress.objects.filter(user=request.user,
                                                default_address=True).last()
        if request.method == "POST":
            address_form = UserAddressForm(request.POST)
            if address_form.is_valid():
                for adres in UserAddress.objects.filter(user=request.user):
                    adres.default_address = False
                    adres.save()
                instance = address_form.save(commit=False)
                instance.default_address = True
                instance.user = request.user
                instance.save()
                return redirect('payment:order_payment', cart.id,
                                order.order_id)
        else:
            address_form = UserAddressForm()
        total_address = UserAddress.objects.filter(
            user=request.user).order_by('-default_address')
        if total_address.count() >= 4:
            address_form = None
        return render(
            request, 'order_payment.html', {
                'cart': cart,
                'cart_products': cart_products,
                'ud_address': ud_address,
                'address_form': address_form,
                'total_address': total_address,
                'order': order,
                'auth_key': settings.RAZORPAY_KEY_ID,
            })
    else:
        return redirect('main:homepage')
Example #14
0
def checkout(request):
    try:
        the_id = request.session['cart_id']
        cart = Cart.objects.get(id=the_id)
    except:
        the_id = None
        return HttpResponsePermanentRedirect(reverse('cart'))
    try:
        new_order = Order.objects.get(cart=cart)

    except Order.DoesNotExist:
        new_order = Order()
        new_order.cart = cart
        new_order.user = request.user
        new_order.order_id = id_generator()
        new_order.save()
    except:
        new_order = None
        return HttpResponsePermanentRedirect(reverse('cart'))
    final_amount = 0
    if new_order is not None:
        new_order.sub_total = cart.total
        new_order.save()
        final_amount = new_order.get_final_amount()

    try:
        address_added = request.GRT.get('address_added')
    except:
        address_added = None
    if address_added is None:
        address_form = UserAddressForm()
    else:
        address_form = None
    current_addresses = UserAddress.objects.filter(user=request.user)
    billing_addresses = UserAddress.objects.get_billing_address(user=request.user)

    if request.method == 'POST':

        try:
            user_stripe = request.user.userstripe.stripe_id
            customer = stripe.Customer.retrieve(user_stripe)
            print(customer)
        except:
            customer = None
            pass

        if customer is not None:
            billing_a = request.POST['billing_address']
            shipping_a = request.POST['shipping_address']
            token = request.POST['stripeToken']
            try:
                billing_address_instance = UserAddress.objects.get(id=billing_a)
            except:
                billing_address_instance = None
            try:
                shipping_address_instance = UserAddress.objects.get(id=shipping_a)
            except:
                shipping_address_instance = None

            card = customer.sources.create(card=token)
            card.address_city = billing_address_instance.city or None
            card.address_line1 = billing_address_instance.address or None
            card.address_line2 = billing_address_instance.address2 or None
            card.address_country = billing_address_instance.country or None
            card.address_zip = billing_address_instance.zipcode or None
            card.save()

            charge = stripe.Charge.create(
                amount=int(final_amount * 100),
                currency="usd",
                card=card,
                customer=customer,
                description="Charge for %s" % request.user.username,
            )
            if charge['captured']:
                new_order.status = 'Finished'
                new_order.shipping_address = shipping_address_instance
                new_order.billing_address = billing_address_instance
                new_order.save()
                del request.session['cart_id']
                del request.session['items_total']
                messages.success(request, 'Thanks for your order. It has been completed')
                return HttpResponsePermanentRedirect(reverse('user_orders'))

    context = {'address_form': address_form,
               'order': new_order,
               'current_addresses': current_addresses,
               'billing_addresses': billing_addresses,
               'stripe_pub': stripe_pub,
               }
    template = 'orders/checkout.html'
    return render(request, template, context)
Example #15
0
def Checkout(request):
    try:
        the_id = request.session['cart_id']
        cart = Cart.objects.get(id=the_id)
    except:
        the_id = None
        return HttpResponseRedirect(reverse('cart'))
    try:
        new_order = Order.objects.get(cart=cart)
    except Order.DoesNotExist:
        new_order = Order()
        new_order.cart = cart
        new_order.user = request.user
        new_order.order_id = id_generator()

        new_order.save()
    except:
        new_order = None
        return HttpResponseRedirect(reverse('cart'))
    final_amount = 0
    if new_order is not None:
        new_order.sub_total = cart.total
        new_order.save()
        final_amount = new_order.get_final_amount()
    try:
        address_added = request.GET.get('address_added')
    except:
        address_added = None
    if address_added is None:
        address_form = UserAddressForm()
    else:
        address_form = None

    current_addresses = UserAddress.objects.filter(user=request.user)
    billing_addresses = UserAddress.objects.get_billing_addresses(
        user=request.user)

    if request.method == 'POST':
        try:
            user_stripe = request.user.userstripe.stripe_id
            customer = stripe.Customer.retrieve(user_stripe)
        except:
            customer = None
            pass
        if customer is not None:
            card = stripe.Customer.create_source(user_stripe,
                                                 source="tok_mastercard")
            card.save()
            charge = stripe.Charge.create(amount=int( final_amount * 100),currency="usd",card=card,\
             customer=customer)

            if charge['captured']:
                new_order.status = 'Finished'
                new_order.save()
                del request.session['cart_id']
                del request.session['total_items']
                messages.success(
                    request, 'Your order has been successfully completed,\
					thank you for shopping with us')
                return HttpResponseRedirect(reverse('user-orders'))

    context = {
        'order': new_order,
        'address_form': address_form,
        'current_addresses': current_addresses,
        'billing_addresses': billing_addresses,
        'stripe_pub': stripe_pub,
    }
    return render(request, 'checkout.html', context)
Example #16
0
def checkout(request):

    try:
        the_id = request.session['cart_id']
        cart = Cart.objects.get(id=the_id)
    except:
        the_id = None
        return HttpResponseRedirect(reverse("cart"))

    try:
        new_order = Order.objects.get(cart=cart)
        # print("try")
    except Order.DoesNotExist:
        new_order = Order(cart=cart)
        new_order.user = request.user
        new_order.order_id = id_generator()
        new_order.save()
        print(new_order.sub_total)
    except:
        new_order = None
        return HttpResponseRedirect(reverse("cart"))

    final_amount = 0
    if new_order is not None:
        new_order.sub_total = cart.total
        new_order.save()
        final_amount = new_order.get_final_amount()

    try:
        address_added = request.GET.get("address_added")
    except:
        address_added = None

    if address_added is None:
        address_form = UserAddressForm()
    else:
        address_form = None

    current_addresses = UserAddress.objects.filter(user=request.user)
    billing_addresses = UserAddress.objects.get_billing_addresses(
        user=request.user)

    if request.method == "POST":
        try:
            print("hello try")
            user_stripe = request.user.userstripe.stripe_id
            customer = stripe.Customer.retrieve(user_stripe)
            # print(customer)
        except:
            print("hello except")
            customer = None
        if customer is not None:
            billing_a = request.POST['billing_address']
            shipping_a = request.POST['shipping_address']
            token = request.POST['stripeToken']

            try:
                billing_address_instance = UserAddress.objects.get(
                    id=billing_a)
            except:
                billing_address_instance = None

            try:
                shipping_address_instance = UserAddress.objects.get(
                    id=shipping_a)
            except:
                shipping_address_instance = None

            # card = customer.cards.create(card=token)
            # customer.source = token
            card = stripe.Customer.create_source(
                customer.stripe_id,
                source=token,
            )
            card.address_city = billing_address_instance.city or None
            card.address_line1 = billing_address_instance.address or None
            card.address_line2 = billing_address_instance.address2 or None
            card.address_state = billing_address_instance.state or None
            card.address_zip = billing_address_instance.zipcode or None
            card.address_country = billing_address_instance.country or None
            card.save()

            token = request.POST['stripeToken']
            charge = stripe.Charge.create(
                amount=int(final_amount * 100),
                currency="inr",
                card=card,
                customer=customer,
                description="Charge is %s" % (request.user.username),
            )
            print(charge)
            print(card)

            if charge["captured"]:
                new_order.status = "Finished"
                new_order.shipping_address = shipping_address_instance
                new_order.billing_addresses = billing_address_instance
                new_order.save()
                del request.session['cart_id']
                del request.session['items_total']
                messages.success(request, "Your has been completed!")
                return HttpResponseRedirect(reverse("user_orders"))

    #add shipping address
    #add billing address
    #add and return credit card
    # cart.delete()

    context = {
        "current_addresses": current_addresses,
        "billing_addresses": billing_addresses,
        "address_form": address_form,
        "stripe_pub": stripe_pub,
        "order": new_order
    }
    template = 'orders/checkout.html'
    return render(request, template, context)
Example #17
0
def checkout(request):
    """
    Prepares and creates payment details for stripe. Creates OrderLineItems
    and User address entries in database.
    """
    cart = request.session.get('cart', {})
    if cart == {}:
        return redirect(reverse('view_cart'))
    user_address_current = None
    shippingfee = 8
    try:
        user_address_current = UserAddress.objects.get(user=request.user.id)
    except:
        user_address_current = UserAddress.objects.create(user=request.user)

    user_addressform = UserAddressForm(instance=user_address_current)

    if request.method == "POST":
        order_form = OrderForm(request.POST)
        payment_form = MakePaymentForm(request.POST)
        if order_form.is_valid() and payment_form.is_valid():
            order = order_form.save(commit=False)
            order.date = timezone.now()
            order.save()
            cart = request.session.get('cart', {})
            total = 0
            for id, quantity in cart.items():
                product = get_object_or_404(Product, pk=id)
                total += quantity * product.price
                order_line_item = OrderLineItem(
                    user=request.user,
                    order=order,
                    product=product,
                    quantity=quantity
                    )
                order_line_item.save()
            if total < 50:
                total += shippingfee
            try:
                customer = stripe.Charge.create(
                    amount=int(total * 100),
                    currency="EUR",
                    description=request.user.email,
                    card=payment_form.cleaned_data['stripe_id'],
                )
            except stripe.error.CardError:
                messages.error(request, "Your card was declined!")

            if customer.paid:
                order.order_paid = True
                order.save()
                messages.error(request, "You have successfully paid")
                update_ordered_pcs(request)
                request.session['cart'] = {}
                user_cart = Cart.objects.get(user=request.user.id)
                user_cart.product_list = ""
                user_cart.save()
                user_addressform = UserAddressForm(
                                   request.POST, instance=user_address_current)
                user_address_new = user_addressform.save(commit=False)
                user_address_new.user = request.user
                user_address_new.save()

                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:
        if user_address_current:
            order_form = OrderForm(instance=user_address_current)
        else:
            order_form = OrderForm()
        payment_form = MakePaymentForm()

    return render(request, "checkout.html",
                  {'order_form': order_form, 'payment_form': payment_form,
                   'publishable': settings.STRIPE_PUBLISHABLE})
Example #18
0
def show_checkout(request, template_name='checkout/checkout.html'):
    try:
        stripe_pub = settings.STRIPE_PUBLISHABLE_KEY
        stripe_key = settings.STRIPE_SECRET_KEY
    except Exception as e:
        raise NotImplementedError(str(e))

    new_order = Order()
    if request.user.is_authenticated:
        new_order.user = request.user
    else:
        new_order.user = None
    new_order.ip_address = request.META.get('REMOTE_ADDR')
    new_order.order_id = id_generator()
    new_order.save()

    if new_order.pk:
        """ if the order save succeeded """
        cart_items = get_cart_items(request)
        for ci in cart_items:
            """ create order item for each cart item """
            oi = OrderItem()
            oi.order = new_order
            oi.quantity = ci.quantity
            oi.price = ci.price  # now using @property
            oi.product = ci.product
            oi.save()

    final_amount = new_order.final_total

    try:
        user_address = UserAddressForm()
        current_addresses = UserAddress.objects.filter(user=request.user)
        billing_addresses = UserAddress.objects.get_billing_addresses(
            user=request.user)
    except:
        user = None
        user_address = UserAddressForm()
    """retrieving the customer when he submits the payment form"""
    if request.method == 'POST':
        try:
            user_stripe = request.user.userstripe.stripe_id
            customer = stripe.Customer.retrieve(user_stripe)
        except:
            customer = None
            pass
        """if customer actually exists we create a card for the customer
            with our already created stripe_id and 
            the token we obtain when he/she submits the payment form """
        if customer is not None:
            token = request.POST['stripeToken']
            """add the billing address and shipping to the customer, first getting the respective id's """
            billing_ad = request.POST['billing-address']
            shipping_ad = request.POST['shipping-address']

            try:
                billing_address_instance = UserAddress.objects.get(
                    id=billing_ad)
            except:
                billing_ad = None
            try:
                shipping_address_instance = UserAddress.objects.get(
                    id=shipping_ad)
            except:
                shipping_ad = None

            card = stripe.Customer.create_source(
                user_stripe,
                source=token,
            )
            """ updating customer's card with shipping address"""
            card.address_city = billing_address_instance.shipping_city or None
            card.address_country = billing_address_instance.shipping_country or None
            card.address_line1 = billing_address_instance.shipping_address_1 or None
            card.address_line2 = billing_address_instance.shipping_address_2 or None
            card.address_state = billing_address_instance.shipping_state or None
            card.address_zip = billing_address_instance.shipping_zip or None
            card.name = billing_address_instance.user.username or None
            card.save()

            charge = stripe.Charge.create(amount=int(final_amount * 100),
                                          currency="usd",
                                          source=card,
                                          customer=customer,
                                          description="Charge for %s" %
                                          {request.user.username})

            # all set, clear the cart
            cart.empty_cart(request)

            if charge['captured']:

                new_order.status = 'SUBMITTED'
                new_order.transaction_id = id_generator(15)
                new_order.shipping_address = shipping_address_instance
                new_order.billing_address = billing_address_instance
                new_order.save()
                return redirect('receipt', pk=new_order.pk)

            if (charge['status'] == 'pending'):
                messages.warning('Processing your order.')
                return redirect('show-cart')

            if (charge['status'] == 'failed'):
                messages.error('There is a problem with your credit card.')
                return redirect('show-cart')

    page_title = 'Checkout'
    return render(request, template_name, locals())
Example #19
0
def checkout(request):
    try:
        the_id = request.session['cart_id']
        cart = Cart.objects.get(id=the_id)
    except:
        the_id = None
        return HttpResponseRedirect(reverse("cart_app:cart", kwargs={}))

    new_order = Order(cart=cart)
    new_order.cart = cart
    new_order.user = request.user
    new_order.save()
    new_order.products.add(*cart.products.all())
    final_amount = 0
    if new_order is not None:
        new_order.total = cart.total
        new_order.save()
        final_amount = new_order.get_final_amount()
    try:
        address_added = request.GET.get("address_added")
    except:
        address_added = None
    if address_added is None:
        address_form = UserAddressForm()
    else:
        address_form = UserAddressForm()
    current_address = UserAddress.objects.filter(user=request.user)
    billing_address = UserAddress.objects.get_billing_address(
        user=request.user)

    if request.method == "POST":
        try:
            user_stripe = request.user.userstripe.stripe_id
            customer = stripe.Customer.retrieve(user_stripe)
        except:
            customer = None
            pass
        if customer is not None:
            try:
                billing_a = request.POST['billing_address']
                shipping_a = request.POST['shipping_address']
            except:
                return HttpResponseRedirect(
                    reverse("orders:checkout", kwargs={}))
            try:
                billing_address_instance = UserAddress.objects.get(
                    id=billing_a)
            except:
                billing_address_instance = None
            try:
                shipping_address_instance = UserAddress.objects.get(
                    id=shipping_a)
            except:
                shipping_address_instance = None
            token = request.POST['stripeToken']
            # card = stripe.Customer.create_source(
            #         user_stripe,
            #         source=token,
            #         )
            charge = stripe.Charge.create(
                amount=int(final_amount * 100),
                currency="inr",
                source=token,
                description="Charge for %s" % (request.user.username),
            )
            # print(charge)
            if charge["captured"]:
                new_order.status = "paid"
                new_order.shipping_address = shipping_address_instance or None
                new_order.billing_address = billing_address_instance or None
                new_order.save()
                del request.session['cart_id']
                # messages.success(request, "Thank you for your order!")
                return HttpResponseRedirect(
                    reverse("orders:user-orders", kwargs={}))

    context = {
        "order": new_order,
        "final_amount": final_amount,
        "current_address": current_address,
        "address_form": address_form,
        "billing_address": billing_address,
        "stripe_pub": stripe_pub,
    }
    template = "orders/checkout.html"
    return render(request, template, context)
Example #20
0
def checkout(request):
    try:
        the_id = request.session['cart_id']
        cart = Cart.objects.get(id=the_id)
    except:
        the_id = None
        #return HttpResponseRedirect("/cart/")
        return HttpResponseRedirect(reverse("cart"))

    try:
        new_order = Order.objects.get(cart=cart)
    except Order.DoesNotExist:
        new_order = Order()
        new_order.cart = cart
        new_order.user = request.user
        new_order.order_id = id_generator()
        new_order.save()
    except:
        new_order = None
        # work on some error message
        return HttpResponseRedirect(reverse("cart"))
    final_amount = 0
    if new_order is not None:
        new_order.sub_total = cart.total
        new_order.save()
        final_amount = new_order.get_final_amount()

    try:
        address_added = request.GET.get("address_added")
    except:
        address_added = None

    if address_added is None:
        address_form = UserAddressForm()
    else:
        address_form = None

    current_addresses = UserAddress.objects.filter(user=request.user)
    billing_addresses = UserAddress.objects.get_billing_addresses(
        user=request.user)
    print billing_addresses
    ##1 add shipping address
    ##2 add billing address
    #3 add and run credit card

    if request.method == "POST":
        try:
            user_stripe = request.user.userstripe.stripe_id
            customer = stripe.Customer.retrieve(user_stripe)
            #print customer
        except:
            customer = None
            pass
        if customer is not None:
            billing_a = request.POST['billing_address']
            shipping_a = request.POST['shipping_address']
            token = request.POST['stripeToken']

            try:
                billing_address_instance = UserAddress.objects.get(
                    id=billing_a)
            except:
                billing_address_instance = None

            try:
                shipping_address_instance = UserAddress.objects.get(
                    id=shipping_a)
            except:
                shipping_address_instance = None

            card = customer.cards.create(card=token)
            card.address_city = billing_address_instance.city or None
            card.address_line1 = billing_address_instance.address or None
            card.address_line2 = billing_address_instance.address2 or None
            card.address_state = billing_address_instance.state or None
            card.address_country = billing_address_instance.country or None
            card.address_zip = billing_address_instance.zipcode or None
            card.save()

            charge = stripe.Charge.create(
                amount=int(final_amount * 100),
                currency="usd",
                card=card,  # obtained with Stripe.js
                customer=customer,
                description="Charge for %s" % (request.user.username))
            if charge["captured"]:
                new_order.status = "Finished"
                new_order.shipping_address = shipping_address_instance
                new_order.billing_addresses = billing_address_instance
                new_order.save()
                del request.session['cart_id']
                del request.session['items_total']
                messages.success(request,
                                 "Thank your order. It has been completed!")
                return HttpResponseRedirect(reverse("orders"))

    context = {
        "order": new_order,
        "address_form": address_form,
        "current_addresses": current_addresses,
        "billing_addresses": billing_addresses,
        "stripe_pub": stripe_pub,
    }
    template = "orders/checkout.html"
    return render(request, template, context)
Example #21
0
def checkout(request):
    """Checkout."""
    # import ipdb; ipdb.set_trace()
    try:
        the_id = request.session['cart_id']
        cart = Cart.objects.get(id=the_id)
    except:
        the_id = None
        return HttpResponseRedirect(reverse("cart"))

    try:
        cart_items = CartItem.objects.filter(cart=cart, active=True)
        if cart_items.count() < 1:
            return HttpResponseRedirect(reverse("cart"))

        for item in cart_items:
            variant = Variation.objects.get(id=item.variation.id)
            if item.quantity > variant.quantity:
                return HttpResponseRedirect(reverse("cart"))
    except:
        pass

    for item in cart_items:
        if item.variation.quantity <= 0:
            return HttpResponseRedirect(reverse("cart"))

    # Getting or creating new Order
    try:
        new_order = Order.objects.get(cart=cart)
    except Order.DoesNotExist:
        new_order = Order()
        new_order.cart = cart
        new_order.user = request.user
        new_order.order_id = id_generator()
        new_order.save()

    except:
        new_order = None
        # work on some error message
        return HttpResponseRedirect(reverse("cart"))

    # Saving Order in CartItem.
    try:
        cart_order = Order.objects.get(order_id=new_order.order_id)
        cart_items = CartItem.objects.filter(cart=cart, active=True)
        for cart_item in cart_items:
            if not cart_item.order:
                cart_item.order = cart_order
                cart_item.save()
    except:
        print "Failed to save Order in CartItem. Please Check the checkout view in Orders."

    # Calculating final amount
    final_amount = 0
    if new_order is not None:
        new_order.sub_total = cart.total
        new_order.save()
        final_amount = new_order.get_final_amount()

    # Adding address
    try:
        address_added = request.GET.get("address_added")
    except:
        address_added = None

    if address_added is None:
        address_form = UserAddressForm()
    else:
        address_form = None

    current_addresses = UserAddress.objects.filter(user=request.user)
    billing_addresses = UserAddress.objects.get_billing_addresses(
        user=request.user)
    print billing_addresses

    # Saving nessary info at Stripe

    if request.method == "POST":
        shipping_a = request.POST['shipping_address']

        try:
            shipping_address_instance = UserAddress.objects.get(id=shipping_a)
        except:
            shipping_address_instance = None

        try:
            razor_payment_id = request.POST['razorpay_payment_id']
            url = 'https://api.razorpay.com/v1/payments/%s' % razor_payment_id
            resp = requests.get(url,
                                data={},
                                auth=(razor_key_id, razor_secret))
            response = json.loads(resp.content)
            if response['error_code'] == "" or response['error_code'] == None:
                for x in new_order.cartitem_set.all():
                    x.status = "Placed"
                    x.save()
                new_order.razor_payment_id = response['id']
                new_order.payment = "Paid"
                new_order.shipping_address = shipping_address_instance
                new_order.save()
                del request.session['cart_id']
                del request.session['items_total']
                import ipdb
                ipdb.set_trace()
                for item in cart_items:
                    variant = Variation.objects.get(id=item.variation.id)
                    variant.quantity -= item.quantity
                messages.success(request,
                                 "Thank your order. It has been completed!")
                return HttpResponseRedirect(reverse("user_orders"))

        except:
            messages.error(request, 'Payment Failed. Please try again later!')
            return HttpResponseRedirect(reverse("checkout"))

    context = {
        "order": new_order,
        "address_form": address_form,
        "current_addresses": current_addresses,
        "billing_addresses": billing_addresses,
        "final_amount": final_amount,
        "stripe_pub": stripe_pub,
        "razor_key_id": razor_key_id
    }

    template = "orders/checkout.html"
    return render(request, template, context)