Пример #1
0
    def pay():
        '''
        입금 정보 입력
        '''
        member_idx = request.args.get('member_idx', 0)
        amount = request.form.get('amount')
        complete = request.form.get('complete')
        claim = request.form.get('claim')
        paydate = request.form.get('paydate')
        staff_name = request.form.get('staff_name')

        try:
            payment = db.session.query(Payment).filter(Payment.member_idx == member_idx).one()
            payment.amount = amount
            payment.complete = complete
            payment.claim = claim
            payment.paydate = paydate
            payment.staff_name = staff_name
        except NoResultFound:
            payment = Payment()
            payment.member_idx = member_idx
            payment.amount = amount
            payment.complete = complete
            payment.claim = claim
            payment.paydate = paydate
            payment.staff_name = staff_name
            db.session.add(payment)
        db.session.commit()

        next_url = request.form.get('next', None)
        if next_url is not None and next_url != 'None':
            return redirect(next_url)

        return redirect(url_for('.member', member_idx=member_idx))
Пример #2
0
    def pay():
        '''
        입금 정보 입력
        '''
        member_idx = request.args.get('member_idx', 0)
        amount = request.form.get('amount')
        complete = request.form.get('complete')
        claim = request.form.get('claim')
        paydate = request.form.get('paydate')
        staff_name = request.form.get('staff_name')

        try:
            payment = db.session.query(Payment).filter(
                Payment.member_idx == member_idx).one()
            payment.amount = amount
            payment.complete = complete
            payment.claim = claim
            payment.paydate = paydate
            payment.staff_name = staff_name
        except NoResultFound:
            payment = Payment()
            payment.member_idx = member_idx
            payment.amount = amount
            payment.complete = complete
            payment.claim = claim
            payment.paydate = paydate
            payment.staff_name = staff_name
            db.session.add(payment)
        db.session.commit()

        next_url = request.form.get('next', None)
        if next_url is not None and next_url != 'None':
            return redirect(next_url)

        return redirect(url_for('.member', member_idx=member_idx))
Пример #3
0
    def post(self, request, *args, **kwargs):
        order = Order.objects.get(user=self.request.user, ordered=False)
        amount = int(order.total_price() * 100)
        token = request.data.get('stripeToken')

        billing_address_id = request.data.get('selectedBillingAddress')
        shipping_address_id = request.data.get('selectedShippingAddress')
        billing_address = Address.objects.get(id=billing_address_id)
        shipping_address = Address.objects.get(id=shipping_address_id)

        try:
            charge = stripe.Charge.create(
                amount=amount,  # cents
                currency="usd",
                source=token
            )
            # create the payment
            payment = Payment()
            payment.stripe_charge_id = charge['id']
            payment.user = self.request.user
            payment.amount = charge['amount']
            payment.save()

            # assign the payment to the order
            order_items = order.items.all()
            order_items.update(ordered=True)
            for item in order_items:
                item.save()

            order.ordered = True
            order.payment = payment
            order.ref_code = create_ref_code()
            order.billing_address = billing_address
            order.shipping_address = shipping_address
            order.save()

            return Response(status=HTTP_200_OK)
        except stripe.error.CardError as e:
            return Response({"message": f"{err.get('messages')}"}, status=HTTP_400_BAD_REQUEST)

        except stripe.error.RateLimitError as e:
            return Response({"message": "Rate limit error"}, status=HTTP_400_BAD_REQUEST)

        except stripe.error.InvalidRequestError as e:
            return Response({"message": "Invalid request error"}, status=HTTP_400_BAD_REQUEST)

        except stripe.error.AuthenticationError as e:
            print(e)
            return Response({"message": "Authentication error"}, status=HTTP_400_BAD_REQUEST)

        except stripe.error.APIConnectionError as e:
            return Response({"message": "Api connection error"}, status=HTTP_400_BAD_REQUEST)

        except stripe.error.StripeError as e:
            return Response({"message": "Stripe error"}, status=HTTP_400_BAD_REQUEST)

        except Exception as e:
            # send a email to ourselves
            return Response({"message": "Something wrong.Please try again.."}, status=HTTP_400_BAD_REQUEST)
Пример #4
0
def generate_payments(request, times):
    for i in range(0, times):
        p = Payment()
        idx = random.randint(0, 1)
        p.service = ['S', 'P'][idx]
        p.charge_id = random_text('n', 15)
        p.amount = random.randint(1000, 9999) / 100
        p.save()
    return HttpResponse(f'{times} Payments generated !')
Пример #5
0
def on_payment_verified(request, sender, ref, amount, **kwargs):
    order = Order.objects.get(user=request.user, ordered=False)

    user = request.user
    email = request.user.email
    name = request.user.first_name
    name_2 = request.user.last_name
    number = order.shipping_address.phone
    address = order.shipping_address.street_address
    country = order.shipping_address.country
    state = order.shipping_address.state

    context = {
        'order': order,
        'amount': amount,
        'email': email,
        'name': name,
        'user': user,
        'ref': ref,
        "name_2": name_2,
        "address": address,
        "country": country,
        'state': state,
        'number': number
    }

    payment = Payment()
    order.ordered = True
    order.ref_code = ref
    # order_item.ordered = True
    payment.user = user
    payment.amount = amount
    payment.reference = ref
    payment.save()
    # attach payment to order

    order_items = order.items.all()

    order_items.update(ordered=True)
    for item in order_items:
        item.save()

    order.payment = payment
    order.save()
    # send email to user
    template = render_to_string('email_template.html', context)
    sale = EmailMessage('Thank you for your order!!', template,
                        "*****@*****.**", [email])
    sale.fail_silently = False
    sale.send()
    template = render_to_string('sale_template.html', context)
    jane = EmailMessage('We have received an order!!', template,
                        "*****@*****.**",
                        ['*****@*****.**'])
    jane.fail_silently = False
    jane.send()
Пример #6
0
def on_payment_verified(request, sender, ref, amount, **kwargs):
    order = Order.objects.get(user=request.user, ordered=False)
    # order_item = OrderItem.objects.get(
    #     user=request.user,
    #     ordered=False
    # )
    user = request.user
    email = request.user.email
    # name = order.billing_address.name
    # number = order.billing_address.phone
    # address = order.billing_address.street_address
    # state = order.billing_address.state

    context = {
        'order': order,
        'amount': amount,
        'email': email,
        # 'name': name,
        'user': user,
        'ref': ref,
        # "address": address,
        # 'state': state,
        # 'number': number
    }

    payment = Payment()
    order.ordered = True
    order.ref_code = ref
    # order_item.ordered = True
    payment.user = user
    payment.amount = amount
    payment.reference = ref
    payment.save()
    # attach payment to order

    order_items = order.items.all()

    order_items.update(ordered=True)
    for item in order_items:
        item.save()

    order.payment = payment
    order.save()
    # send email to user
    template = render_to_string('email_template.html', context)
    sale = EmailMessage('Thank you for your order!!', template, email, [email])
    sale.fail_silently = False
    sale.send()
    template = render_to_string('jane_email.html', context)
    jane = EmailMessage('We have received an order!!', template, email,
                        ['*****@*****.**'])
    jane.fail_silently = False
    jane.send()
    print(user, sender, amount, ref, amount, email)
Пример #7
0
    def post(self, request, *args, **kwargs):

        order = Order.objects.get(user=self.request.user, ordered=False)
        userprofile = UserProfile.objects.get(user=self.request.user)
        token = request.data.get('stripeToken')
        billing_address_id = request.data.get('selectedBillingAddress')
        shipping_address_id = request.data.get('selectedShippingAddress')
        billing_address = Address.objects.get(id=billing_address_id)
        shipping_address = Address.objects.get(id=shipping_address_id)

        if userprofile.stripe_customer_id != '' and userprofile.stripe_customer_id is not None:
            customer = stripe.Customer.retrieve(userprofile.stripe_customer_id)
            customer.sources.create(source=token)

        else:
            customer = stripe.Customer.create(email=self.request.user.email, )
            customer.sources.create(source=token)
            userprofile.stripe_customer_id = customer['id']
            userprofile.one_click_purchasing = True
            userprofile.save()

        amount = int(order.get_total() * 100)

        try:

            # charge the customer because we cannot charge the token more than once
            charge = stripe.Charge.create(
                amount=amount,  # cents
                currency="usd",
                customer=userprofile.stripe_customer_id)
            # charge once off on the token
            # charge = stripe.Charge.create(
            #     amount=amount,  # cents
            #     currency="usd",
            #     source=token
            # )

            # create the payment
            payment = Payment()
            payment.stripe_charge_id = charge['id']
            payment.user = self.request.user
            payment.amount = order.get_total()
            payment.save()

            # assign the payment to the order

            order_items = order.items.all()
            for item in order_items:
                if item.quantity > item.item.stock_quantity:
                    print("this happend")
                    return Response(
                        {"message": "This product is now out of stock"},
                        status=HTTP_400_BAD_REQUEST)
                else:
                    pass
                subtract_item_quantity_from_stock(item)
            order_items.update(ordered=True)

            order.ordered = True
            order.payment = payment
            order.billing_address = billing_address
            order.shipping_address = shipping_address
            order.ordered_date = datetime.datetime.now()
            # order.ref_code = create_ref_code()
            try:
                for i in order_items:
                    old_item = ItemOrdered(
                        price=i.item.price,
                        title=i.item.title,
                        sku=i.item.sku,
                        upc=i.item.upc,
                        discount_price=i.item.discount_price,
                        category=i.item.category,
                        label=i.item.label,
                        slug=i.item.slug,
                        description=i.item.description,
                        image=i.item.image)
                    old_item.save()

                    i.ordered_item = old_item
                    i.save()

            except Exception as e:
                print(e)
                return Response("Dhappa")
            # for item in order_items:

            order.save()
            return Response(status=HTTP_200_OK)

        except stripe.error.CardError as e:
            body = e.json_body
            err = body.get('error', {})
            return Response({"message": f"{err.get('message')}"},
                            status=HTTP_400_BAD_REQUEST)

        except stripe.error.RateLimitError as e:
            # Too many requests made to the API too quickly
            messages.warning(self.request, "Rate limit error")
            return Response({"message": "Rate limit error"},
                            status=HTTP_400_BAD_REQUEST)

        except stripe.error.InvalidRequestError as e:
            print(e)
            # Invalid parameters were supplied to Stripe's API
            return Response({"message": "Invalid parameters"},
                            status=HTTP_400_BAD_REQUEST)

        except stripe.error.AuthenticationError as e:
            # Authentication with Stripe's API failed
            # (maybe you changed API keys recently)
            return Response({"message": "Not authenticated"},
                            status=HTTP_400_BAD_REQUEST)

        except stripe.error.APIConnectionError as e:
            # Network communication with Stripe failed
            return Response({"message": "Network error"},
                            status=HTTP_400_BAD_REQUEST)

        except stripe.error.StripeError as e:
            # Display a very generic error to the user, and maybe send
            # yourself an email
            return Response(
                {
                    "message":
                    "Something went wrong. You were not charged. Please try again."
                },
                status=HTTP_400_BAD_REQUEST)

        except Exception as e:
            # send an email to ourselves
            return Response(
                {"message": "A serious error occurred. We have been notifed."},
                status=HTTP_400_BAD_REQUEST)

        return Response({"message": "Invalid data received"},
                        status=HTTP_400_BAD_REQUEST)
Пример #8
0
    def post(self, request, *args, **kwargs):
        order = Order.objects.get(user=self.request.user, ordered=False)
        userprofile = UserProfile.objects.get(user=self.request.user)
        token = request.data.get('stripeToken')
        # save = form.cleaned_data.get('save')
        # use_default = form.cleaned_data.get('use_default')
        save = False
        use_default = False

        if save:
            if userprofile.stripe_customer_id != '' and userprofile.stripe_customer_id is not None:
                customer = stripe.Customer.retrieve(
                    userprofile.stripe_customer_id)
                customer.sources.create(source=token)

            else:
                customer = stripe.Customer.create(
                    email=self.request.user.email,
                )
                customer.sources.create(source=token)
                userprofile.stripe_customer_id = customer['id']
                userprofile.one_click_purchasing = True
                userprofile.save()

        amount = int(order.get_total() * 100)

        try:

            if use_default or save:
                # charge the customer because we cannot charge the token more than once
                charge = stripe.Charge.create(
                    amount=amount,  # cents
                    currency="usd",
                    customer=userprofile.stripe_customer_id
                )
            else:
                # charge once off on the token
                charge = stripe.Charge.create(
                    amount=amount,  # cents
                    currency="usd",
                    source=token
                )

            # create the payment
            payment = Payment()
            payment.stripe_charge_id = charge['id']
            payment.user = self.request.user
            payment.amount = order.get_total()
            payment.save()

            # assign the payment to the order

            order_items = order.items.all()
            order_items.update(ordered=True)
            for item in order_items:
                item.save()

            order.ordered = True
            order.payment = payment
            # order.ref_code = create_ref_code()
            order.save()

            return Response(status=HTTP_200_OK)

        except stripe.error.CardError as e:
            body = e.json_body
            err = body.get('error', {})
            return Response({"message": f"{err.get('message')}"}, status=HTTP_400_BAD_REQUEST)

        except stripe.error.RateLimitError as e:
            # Too many requests made to the API too quickly
            messages.warning(self.request, "Rate limit error")
            return Response({"message": "Rate limit error"}, status=HTTP_400_BAD_REQUEST)

        except stripe.error.InvalidRequestError as e:
            # Invalid parameters were supplied to Stripe's API
            return Response({"message": "Invalid parameters"}, status=HTTP_400_BAD_REQUEST)

        except stripe.error.AuthenticationError as e:
            # Authentication with Stripe's API failed
            # (maybe you changed API keys recently)
            return Response({"message": "Not authenticated"}, status=HTTP_400_BAD_REQUEST)

        except stripe.error.APIConnectionError as e:
            # Network communication with Stripe failed
            return Response({"message": "Network error"}, status=HTTP_400_BAD_REQUEST)

        except stripe.error.StripeError as e:
            # Display a very generic error to the user, and maybe send
            # yourself an email
            return Response({"message": "Something went wrong. You were not charged. Please try again."}, status=HTTP_400_BAD_REQUEST)

        except Exception as e:
            # send an email to ourselves
            print(e)
            return Response({"message": "A serious error occurred. We have been notifed."}, status=HTTP_400_BAD_REQUEST)

        return Response({"message": "Invalid data received"}, status=HTTP_400_BAD_REQUEST)
Пример #9
0
    def post(self, *args, **kwargs):
        order = Order.objects.get(user=self.request.user, ordered=False)
        token = self.request.POST.get('stripeToken')
        amount = int(order.get_total() * 100)

        # customer.sources.create(source=token)
        # userprofile.stripe_customer_id = customer['id']
        # userprofile.one_click_purchasing = True
        # userprofile.save()

        try:
            # if use_default or save:
            #     # charge the customer because we cannot charge the token more than once
            #     charge = stripe.Charge.create(
            #         amount=amount,  # cents
            #         currency="usd",
            #         customer=userprofile.stripe_customer_id
            #     )
            # else:
            # charge once off on the token
            charge = stripe.Charge.create(
                amount=amount,  # cents
                currency="usd",
                source=token)

            # create the payment
            payment = Payment()
            payment.stripe_charge_id = charge['id']
            payment.user = self.request.user
            payment.amount = order.get_total()
            payment.save()

            # assign the payment to the order
            # order_items = order.items.all()
            # order_items.update(ordered=True)
            # for item in order_items:
            #     item.save()

            order.ordered = True
            order.payment = payment
            # order.ref_code = create_ref_code()
            order.save()

            messages.success(self.request, "Your order was successful!")
            return redirect("/")

        except stripe.error.CardError as e:
            body = e.json_body
            err = body.get('error', {})
            messages.warning(self.request, f"{err.get('message')}")
            return redirect("/")

        except stripe.error.RateLimitError as e:
            # Too many requests made to the API too quickly
            messages.warning(self.request, "Rate limit error")
            return redirect("/")

        except stripe.error.InvalidRequestError as e:
            # Invalid parameters were supplied to Stripe's API
            print(e)
            messages.warning(self.request, "Invalid parameters")
            return redirect("/")

        except stripe.error.AuthenticationError as e:
            # Authentication with Stripe's API failed
            # (maybe you changed API keys recently)
            messages.warning(self.request, "Not authenticated")
            return redirect("/")

        except stripe.error.APIConnectionError as e:
            # Network communication with Stripe failed
            messages.warning(self.request, "Network error")
            return redirect("/")

        except stripe.error.StripeError as e:
            # Display a very generic error to the user, and maybe send
            # yourself an email
            messages.warning(
                self.request,
                "Something went wrong. You were not charged. Please try again."
            )
            return redirect("/")

        except Exception as e:
            # send an email to ourselves
            messages.warning(
                self.request,
                "A serious error occurred. We have been notifed.")
            return redirect("/")

        messages.warning(self.request, "Invalid data received")
        return redirect("/payment/stripe/")
Пример #10
0
    def post(self, request, *args, **kwargs):
        order = Order.objects.get(user=self.request.user, ordered=False)
        userprofile = UserProfile.objects.get(user=self.request.user)
        token = request.data.get("stripeToken")
        billing_address = ""
        shipping_address = ""
        if "selectedShippingAddress" in request.data.keys():
            shipping_address_id = request.data.get("selectedShippingAddress")
            shipping_address = Address.objects.get(id=shipping_address_id)
            print(shipping_address, shipping_address_id)
        if "selectedBillingAddress" in request.data.keys():
            billing_address_id = request.data.get("selectedBillingAddress")
            billing_address = Address.objects.get(id=billing_address_id)
            print(billing_address, billing_address_id)

        if (userprofile.stripe_customer_id != ""
                and userprofile.stripe_customer_id is not None):
            customer = stripe.Customer.retrieve(userprofile.stripe_customer_id)
            customer.sources.create(source=token)

        else:
            customer = stripe.Customer.create(email=self.request.user.email)
            customer.sources.create(source=token)
            userprofile.stripe_customer_id = customer["id"]
            userprofile.one_click_purchasing = True
            userprofile.save()

        amount = int(order.get_total() * 100)

        try:

            # charge the customer because we cannot charge the token more than once
            charge = stripe.Charge.create(
                amount=amount,  # cents
                currency="eur",
                customer=userprofile.stripe_customer_id,
            )
            # charge once off on the token
            # charge = stripe.Charge.create(
            #     amount=amount,  # cents
            #     currency="usd",
            #     source=token
            # )

            # create the payment
            payment = Payment()
            payment.stripe_charge_id = charge["id"]
            payment.user = self.request.user
            payment.amount = order.get_total()
            payment.save()

            # assign the payment to the order

            order_items = order.items.all()
            order_items.update(ordered=True)
            for item in order_items:
                item.save()

            order.ordered = True
            order.payment = payment
            if len(billing_address) > 0:
                order.billing_address = billing_address
            if len(shipping_address) > 0:
                order.shipping_address = shipping_address
            # order.ref_code = create_ref_code()
            order.save()

            return Response(status=HTTP_200_OK)

        except stripe.error.CardError as e:
            body = e.json_body
            err = body.get("error", {})
            return Response({"message": f"{err.get('message')}"},
                            status=HTTP_400_BAD_REQUEST)

        except stripe.error.RateLimitError as e:
            # Too many requests made to the API too quickly
            messages.warning(self.request, "Rate limit error")
            return Response({"message": "Rate limit error"},
                            status=HTTP_400_BAD_REQUEST)

        except stripe.error.InvalidRequestError as e:
            print(e)
            # Invalid parameters were supplied to Stripe's API
            return Response({"message": "Invalid parameters"},
                            status=HTTP_400_BAD_REQUEST)

        except stripe.error.AuthenticationError as e:
            # Authentication with Stripe's API failed
            # (maybe you changed API keys recently)
            return Response({"message": "Not authenticated"},
                            status=HTTP_400_BAD_REQUEST)

        except stripe.error.APIConnectionError as e:
            # Network communication with Stripe failed
            return Response({"message": "Network error"},
                            status=HTTP_400_BAD_REQUEST)

        except stripe.error.StripeError as e:
            # Display a very generic error to the user, and maybe send
            # yourself an email
            return Response(
                {
                    "message":
                    "Something went wrong. You were not charged. Please try again."
                },
                status=HTTP_400_BAD_REQUEST,
            )

        except Exception as e:
            # send an email to ourselves
            return Response(
                {
                    "message":
                    "A serious error occurred. We have been notifed." + str(e)
                },
                status=HTTP_400_BAD_REQUEST,
            )

        return Response({"message": "Invalid data received"},
                        status=HTTP_400_BAD_REQUEST)
Пример #11
0
    def post(self, request, *args, **kwargs):
        order = Order.objects.get(user=self.request.user, ordered=False)
        token = request.data.get('stripeToken')
        billing_address_id = request.data.get('selectedBillingAddress')
        shipping_address_id = request.data.get('selectedShippingAddress')
        amount = int(order.get_total() * 100)

        billing_address = Address.objects.get(id=billing_address_id)
        shipping_address = Address.objects.get(id=shipping_address_id)

        try:
            # charge once off on the token
            charge = stripe.Charge.create(
                amount=amount,  # cents
                currency="usd",
                source=token
            )

            # create the payment
            payment = Payment()
            payment.stripe_charge_id = charge['id']
            payment.user = self.request.user
            payment.amount = order.get_total()
            payment.save()

            # assign the payment to the order

            order_items = order.items.all()
            order_items.update(ordered=True)
            for item in order_items:
                item.save()

            order.ordered = True
            order.payment = payment
            order.billing_address = billing_address
            order.shipping_address = shipping_address
            order.ref_code = str(order.id) + create_ref_code()
            order.save()

            return Response(status=HTTP_200_OK)

        except stripe.error.CardError as e:
            body = e.json_body
            err = body.get('error', {})
            return Response({"message": f"{err.get('message')}"}, status=HTTP_400_BAD_REQUEST)

        except stripe.error.RateLimitError as e:
            # Too many requests made to the API too quickly
            return Response({"message": "Rate limit error"}, status=HTTP_400_BAD_REQUEST)

        except stripe.error.InvalidRequestError as e:
            print(e)
            # Invalid parameters were supplied to Stripe's API
            return Response({"message": "Invalid parameters"}, status=HTTP_400_BAD_REQUEST)

        except stripe.error.AuthenticationError as e:
            # Authentication with Stripe's API failed
            # (maybe you changed API keys recently)
            return Response({"message": "Not authenticated"}, status=HTTP_400_BAD_REQUEST)

        except stripe.error.APIConnectionError as e:
            # Network communication with Stripe failed
            return Response({"message": "Network error"}, status=HTTP_400_BAD_REQUEST)

        except stripe.error.StripeError as e:
            # Display a very generic error to the user, and maybe send
            # yourself an email
            return Response({"message": "Something went wrong. You were not charged. Please try again."}, status=HTTP_400_BAD_REQUEST)

        except Exception as e:
            # send an email to ourselves
            return Response({"message": "A serious error occurred. We have been notifed."}, status=HTTP_400_BAD_REQUEST)

        return Response({"message": "Invalid data received"}, status=HTTP_400_BAD_REQUEST)
Пример #12
0
    def post(self, *args, **kwargs):
        order = Order.objects.get(user=self.request.user, ordered=False)
        token = self.request.POST.get('stripeToken')
        amount = int(order.get_total() * 100)
        try:
            charge = stripe.Charge.create(
                amount=amount,  # cents
                currency="usd",
                source=token)
            # create the payment
            payment = Payment()
            payment.stripe_charge_id = charge['id']
            payment.user = self.request.user
            payment.amount = order.get_total()
            payment.save()

            # assign the payment to the order
            order.ordered = True
            order.payment = payment
            # TODO : assign ref code
            order.ref_code = create_ref_code()
            order.save()

            messages.success(self.request, "Order was successful")
            return redirect("/")

        except stripe.error.CardError as e:
            # Since it's a decline, stripe.error.CardError will be caught
            body = e.json_body
            err = body.get('error', {})
            messages.error(self.request, f"{err.get('message')}")
            return redirect("/")

        except stripe.error.RateLimitError as e:
            # Too many requests made to the API too quickly
            messages.error(self.request, "RateLimitError")
            return redirect("/")

        except stripe.error.InvalidRequestError as e:
            # Invalid parameters were supplied to Stripe's API
            messages.error(self.request, "Invalid parameters")
            return redirect("/")

        except stripe.error.AuthenticationError as e:
            # Authentication with Stripe's API failed
            # (maybe you changed API keys recently)
            messages.error(self.request, "Not Authentication")
            return redirect("/")

        except stripe.error.APIConnectionError as e:
            # Network communication with Stripe failed
            messages.error(self.request, "Network Error")
            return redirect("/")

        except stripe.error.StripeError as e:
            # Display a very generic error to the user, and maybe send
            # yourself an email
            messages.error(self.request, "Something went wrong")
            return redirect("/")

        except Exception as e:
            # send an email to ourselves
            messages.error(self.request, "Serious Error occured")
            return redirect("/")
Пример #13
0
    def post(self, request, *args, **kwargs):
        order_qs = Order.objects.filter(user=self.request.user, ordered=False)
        userprofile = UserProfile.objects.get(user=self.request.user)
        token = request.data.get('stripeToken')
        print("token", token)
        billing_address_id = request.data.get('selectedBillingAddress')
        shipping_address_id = request.data.get('selectedShippingAddress')

        addresses = list(
            Address.objects.filter(user=request.user).values_list('id',
                                                                  flat=True))
        # change tis to accomadate empty id's
        if not is_valid(billing_address_id) or not is_valid(
                shipping_address_id) or int(
                    billing_address_id) not in addresses or int(
                        shipping_address_id) not in addresses:
            return Response(
                {"message": "Please fill in your appropiate addresses."},
                status=HTTP_400_BAD_REQUEST)

        billing_address = Address.objects.get(id=billing_address_id)
        shipping_address = Address.objects.get(id=shipping_address_id)
        if not order_qs.exists():
            return Response(
                {
                    "message":
                    "Order not found, you've probably checked out already."
                },
                status=HTTP_400_BAD_REQUEST)

        order = order_qs[0]

        # if is_valid(userprofile.stripe_customer_id):
        #     customer = stripe.Customer.retrieve(
        #         userprofile.stripe_customer_id)
        #     # customer.sources.create(source=token)

        # else:
        #     customer = stripe.Customer.create(
        #         email=self.request.user.email,
        #     )
        #     # customer.sources.create(source=token)
        #     userprofile.stripe_customer_id = customer['id']
        #     userprofile.one_click_purchasing = True
        #     userprofile.save()

        amount = int(order.get_total() * 100)

        try:
            # if is_valid(userprofile.stripe_customer_id):
            #     # charge the customer because we cannot charge the token more than once
            #     charge = stripe.Charge.create(
            #         amount=amount,  # cents
            #         currency="usd",
            #         customer=userprofile.stripe_customer_id
            #     )
            # else:
            # charge once off on the token
            print(amount)
            charge = stripe.Charge.create(
                amount=amount,  # cents
                currency="usd",
                source=token)

            # create the payment
            payment = Payment()
            payment.stripe_charge_id = charge['id']
            payment.user = self.request.user
            payment.amount = order.get_total()
            payment.save()

            # assign the payment to the order

            order_items = order.items.all()
            order_items.update(ordered=True)
            for item in order_items:
                item.save()

            order.ordered = True
            order.payment = payment
            order.billing_address = billing_address
            order.shipping_address = shipping_address
            order.ref_code = create_ref_code()
            order.save()

            return Response(
                status=HTTP_200_OK,
                data={"message": "Payment Successful and captured."})

        except stripe.error.CardError as e:
            body = e.json_body
            err = body.get('error', {})
            print(e)
            return Response({"message": f"{err.get('message')}"},
                            status=HTTP_400_BAD_REQUEST)

        except stripe.error.RateLimitError as e:
            # Too many requests made to the API too quickly
            print(e)
            messages.warning(self.request, "Rate limit error")
            return Response({"message": "Rate limit error."},
                            status=HTTP_400_BAD_REQUEST)

        except stripe.error.InvalidRequestError as e:
            print(e)
            # Invalid parameters were supplied to Stripe's API
            return Response({"message": "Invalid parameters."},
                            status=HTTP_400_BAD_REQUEST)

        except stripe.error.AuthenticationError as e:
            # Authentication with Stripe's API failed
            # (maybe you changed API keys recently)
            print(e)
            return Response({"message": "Not authenticated."},
                            status=HTTP_400_BAD_REQUEST)

        except stripe.error.APIConnectionError as e:
            # Network communication with Stripe failed
            print(e)
            return Response({"message": "Network error."},
                            status=HTTP_400_BAD_REQUEST)

        except stripe.error.StripeError as e:
            # Display a very generic error to the user, and maybe send
            # yourself an email
            print(e)
            return Response(
                {
                    "message":
                    "Something went wrong. You were not charged. Please try again."
                },
                status=HTTP_400_BAD_REQUEST)

        except Exception as e:
            # send an email to ourselves
            print(e)
            return Response(
                {"message": "A serious error occurred. We have been notifed."},
                status=HTTP_400_BAD_REQUEST)

        return Response({"message": "Invalid data received."},
                        status=HTTP_400_BAD_REQUEST)
Пример #14
0
    def post(self, request, *args, **kwargs):
        order = Order.objects.get(user=self.request.user, ordered=False)
        userprofile = UserProfile.objects.get(user=self.request.user)
        billing_address_id = request.data.get('selectedBillingAddress')
        shipping_address_id = request.data.get('selectedShippingAddress')
        print(billing_address_id, shipping_address_id)
        billing_address = Address.objects.get(id=billing_address_id)
        shipping_address = Address.objects.get(id=shipping_address_id)
        token = request.data.get('stripeToken')

        if userprofile.stripe_customer_id != '' and userprofile.stripe_customer_id is not None:
            customer = stripe.Customer.retrieve(userprofile.stripe_customer_id)

        else:
            customer = stripe.Customer.create(email=self.request.user.email,
                                              source=token)
            userprofile.stripe_customer_id = customer['id']
            userprofile.one_click_purchasing = True
            userprofile.save()

        amount = int(order.get_total() * 100)

        try:
            try:
                # charge once off on the token for first time purchases
                charge = stripe.Charge.create(
                    amount=amount,  # cents
                    currency="usd",
                    source=token)
            except Exception as e:
                print("CANT CHARGE TOKEN TWICE ERROR: " + e)
            else:
                # charge the customer because we cannot charge the token more than once
                charge = stripe.Charge.create(
                    amount=amount,  # cents
                    currency="usd",
                    customer=userprofile.stripe_customer_id)

            # create the payment
            payment = Payment()
            payment.stripe_charge_id = charge['id']
            payment.user = self.request.user
            payment.amount = order.get_total()
            payment.save()

            # assign the payment to the order

            order_items = order.items.all()
            order_items.update(ordered=True)
            for item in order_items:
                item.save()

            order.ordered = True
            order.payment = payment
            order.billing_address = billing_address
            order.shipping_address = shipping_address
            # order.ref_code = create_ref_code()
            order.save()

            return Response(status=HTTP_200_OK)

        except stripe.error.CardError as e:
            body = e.json_body
            err = body.get('error', {})
            return Response({"message": f"{err.get('message')}"},
                            status=HTTP_400_BAD_REQUEST)

        except stripe.error.RateLimitError as e:
            # Too many requests made to the API too quickly
            return Response({"message": "RATE_LIMIT_ERROR"},
                            status=HTTP_400_BAD_REQUEST)

        except stripe.error.InvalidRequestError as e:
            # Invalid parameters were supplied to Stripe's API
            return Response({"message": "INVALID_PARAMETERS"},
                            status=HTTP_400_BAD_REQUEST)
        except stripe.error.AuthenticationError as e:
            # Authentication with Stripe's API failed
            # (maybe you changed API keys recently)
            return Response({"message": "NOT_AUTHENTICATED"},
                            status=HTTP_400_BAD_REQUEST)

        except stripe.error.APIConnectionError as e:
            # Network communication with Stripe failed
            return Response({"message": "NETWORK_ERROR"},
                            status=HTTP_400_BAD_REQUEST)

        except stripe.error.StripeError as e:
            # Display a very generic error to the user, and maybe send
            # yourself an email
            return Response({"message": "STRIPE_ERROR"},
                            status=HTTP_400_BAD_REQUEST)

        except Exception as e:
            # send an email to ourselves
            print(e)
            return Response(
                {
                    "message":
                    "SERIOUS_PYTHON_ERORR_OCCURRED, DEV_TEAM_NOTIFIED"
                },
                status=HTTP_400_BAD_REQUEST)

        return Response({"message": "INVALID_DATA"},
                        status=HTTP_400_BAD_REQUEST)
Пример #15
0
    def post(self, request, *args, **kwargs):
        print(self.request.user)
        order = get_object_or_404(Order, user=self.request.user, ordered=False)
        user_profile = get_object_or_404(UserProfile, user=self.request.user)
        # doesn't work on test visa card with the number 4242 4242 4242 4242
        token = self.request.data.get('stripeToken')
        # https://stripe.com/docs/testing#cards
        # token = 'tok_visa'
        billing_address_id = self.request.data.get('selectedBillingAddress')
        shipping_address_id = self.request.data.get('selectedShippingAddress')
        billing_address = Address.objects.get(id=billing_address_id)
        shipping_address = Address.objects.get(id=shipping_address_id)

        if user_profile.stripe_customer_id != '' and user_profile.stripe_customer_id is not None:
            customer = stripe.Customer.retrieve(
                user_profile.stripe_customer_id)
            customer.sources.create(source=token)

        else:
            customer = stripe.Customer.create(email=self.request.user.email, )
            customer.sources.create(source=token)
            user_profile.stripe_customer_id = customer['id']
            user_profile.one_click_purchasing = True
            user_profile.save()

        amount = int(order.get_total() * 100)

        try:
            # create a charge (https://stripe.com/docs/api/charges/create?lang=python)
            # charge the customer because we cannot charge the token more than once
            charge = stripe.Charge.create(
                amount=amount,  # cents
                currency="usd",
                customer=user_profile.stripe_customer_id)

            # charge once off on the token
            # charge = stripe.Charge.create(
            #     amount=amount,  # cents
            #     currency="usd",
            #     source=token  # obtained with Stripe.js
            # )

            # create the payment
            payment = Payment()
            payment.stripe_charge_id = charge['id']
            payment.user = self.request.user
            payment.amount = order.get_total()
            payment.save()

            # assign the payment to the order

            order_items = order.items.all()
            order_items.update(ordered=True)
            for item in order_items:
                item.save()

            order.ordered = True
            order.payment = payment
            order.billing_address = billing_address
            order.shipping_address = shipping_address
            # order.ref_code = generate_ref_code()
            order.save()

            return Response({'message': 'Your order was successful!'},
                            status=status.HTTP_200_OK)

        # stripe error handling (https://stripe.com/docs/api/errors/handling?lang=python)
        except stripe.error.CardError as e:
            # Since it's a decline, stripe.error.CardError will be caught
            body = e.json_body
            err = body.get('error', {})
            return Response({'message': f"{err.get('message')}"},
                            status=status.HTTP_400_BAD_REQUEST)

        except stripe.error.RateLimitError as e:
            # Too many requests made to the API too quickly
            return Response(
                {'message': 'Too many requests made to the API too quickly'},
                status=status.HTTP_400_BAD_REQUEST)

        except stripe.error.InvalidRequestError as e:
            # Invalid parameters were supplied to Stripe's API
            return Response(
                {
                    'message':
                    "Invalid parameters were supplied to Stripe's API"
                },
                status=status.HTTP_400_BAD_REQUEST)

        except stripe.error.AuthenticationError as e:
            # Authentication with Stripe's API failed
            # (maybe you changed API keys recently)
            return Response(
                {'message': "Authentication with Stripe's API failed"},
                status=status.HTTP_400_BAD_REQUEST)

        except stripe.error.APIConnectionError as e:
            # Network communication with Stripe failed
            return Response(
                {'message': 'Network communication with Stripe failed'},
                status=status.HTTP_400_BAD_REQUEST)

        except stripe.error.StripeError as e:
            # Display a very generic error to the user, and maybe send
            # yourself an email
            return Response(
                {
                    'message':
                    'Something went wrong. You were not charged. Please try again'
                },
                status=status.HTTP_400_BAD_REQUEST)

        except Exception as e:
            # send an email to myself because there's something wrong with my code
            return Response(
                {'message': 'Serious error occurred. We have been notified'},
                status=status.HTTP_400_BAD_REQUEST)
    def post(self, request, *args, **kwargs):
        #get user form token
        user = get_user_from_token(request)

        #get the user membership
        membership = user.membership

        try:
            #get the stripe customer from stripe_customer_id(created when a user create an account)
            customer = stripe.Customer.retrieve(user.stripe_customer_id)
            #create test token using strip o backend
            # https://stripe.com/docs/api/tokens/create_card?lang=python

            serializer = SubscribeSerializer(
                data=request.data
            )  #it will receive stripeToken (Token generated on frontend by stripe form)
            print(
                "request.data", request.data
            )  #stripe token.id will be passed in serializer (it will done by REACT stripe documentation)

            #serialize post data (stripeToken)
            if serializer.is_valid():
                #get stripeToken from serializer data
                stripe_token = serializer.data.get('stripeToken')
                # stripe_token = serializer.data.get('stripeToken')
                print("stripe_token", stripe_token)

                #create the stripe subscription
                subscription = stripe.Subscription.create(
                    customer=customer.id,
                    items=[{
                        "plan": settings.STRIPE_PLAN_ID
                    }])
                #update the membership
                membership.stripe_subscription_id = subscription.id
                membership.stripe_subscription_item_id = subscription['items'][
                    'data'][0]['id']
                membership.type = 'M'
                membership.start_date = datetime.datetime.now()
                membership.end_date = datetime.datetime.fromtimestamp(
                    subscription.
                    current_period_end  #subscription.current_period_end from STRIPE
                )
                membership.save()

                #update the user
                user.is_member = True
                user.on_free_trial = False
                user.save()

                #create the payment
                payment = Payment()
                # / 100 for converting Cents into dollars
                payment.amount = subscription.plan.amount / 100  #from stripe
                payment.user = user
                payment.save()

                return Response({'message': 'sucess'})

            else:
                return Response({'message': 'Incorrect data was received'},
                                status=HTTP_200_OK)

        except stripe.error.CardError as e:
            return Response({'message': 'Your card has been declined'},
                            status=HTTP_400_BAD_REQUEST)
        except stripe.error.StripeError as e:
            print(e)
            return Response(
                {
                    'message':
                    'There was an error. You have not been billed. If this persists please contact us.'
                },
                status=HTTP_400_BAD_REQUEST)
        except Exception as e:
            print(e)
            return Response(
                {
                    'message':
                    'We apologize for the error. We have been informed and are working on th problem'
                },
                status=HTTP_400_BAD_REQUEST)
Пример #17
0
    def post(self, *args, **kwargs):
        form = CheckoutForm(self.request.POST or None)
        try:
            order = Order.objects.get(user=self.request.user, is_ordered=False)
            if form.is_valid():
                # print(form.cleaned_data)
                # print("form valido")
                form.use_default_shipping = form.cleaned_data.get(
                    'use_default_shipping')
                #form.save_info = form.cleaned_data.get('save_info')
                if form.use_default_shipping:
                    print('uso indirizzo di default')
                    address_qs = ShoppingAddress.objects.filter(
                        user=self.request.user, default=True)
                    if address_qs.exists():
                        shopping_address = address_qs[0]
                        order_items = order.items.all()
                        order_items.update(is_ordered=True)
                        order.shopping_address = shopping_address
                        for item in order_items:
                            item.product.ordered = True
                            item.product.compratore = order.get_username()
                            item.product.address = order.get_address()
                            item.product.data = timezone.now()
                            item.product.save()
                            item.save()

                        order.shopping_address = shopping_address
                        order.is_ordered = True
                        order.ordered_date = timezone.now()
                        order.save()
                        payment = Payment()
                        payment.user = self.request.user
                        payment.amount = order.get_total()
                        payment.order = order
                        payment.save()
                    else:
                        messages.info(self.request,
                                      "Nessun indirizzo di default")
                        return redirect('checkout')
                else:
                    form.stato = form.cleaned_data.get('stato')
                    form.città = form.cleaned_data.get('città')
                    form.via = form.cleaned_data.get('via')
                    form.cap = form.cleaned_data.get('cap')
                    form.interno = form.cleaned_data.get('interno')
                    form.note = form.cleaned_data.get('note')

                    #form.save_info = form.cleaned_data.get('save_info')
                    form.opzioni_pagamento = form.cleaned_data.get(
                        'opzioni_pagamento')
                    if is_valid_form(
                        [form.stato, form.città, form.via, form.cap]):
                        shopping_address = ShoppingAddress(
                            user=self.request.user,
                            stato=form.stato,
                            città=form.città,
                            cap=form.cap,
                            via=form.via,
                            interno=form.interno,
                            note=form.note)
                        shopping_address.save()
                        order_items = order.items.all()
                        order_items.update(is_ordered=True)
                        order.shopping_address = shopping_address
                        for item in order_items:
                            item.product.ordered = True
                            item.product.compratore = order.get_username()
                            item.product.data = timezone.now()
                            item.product.address = order.get_address()
                            item.product.save()
                            item.save()

                        order.shopping_address = shopping_address
                        order.is_ordered = True
                        order.ordered_date = timezone.now()
                        order.save()
                        payment = Payment()
                        payment.user = self.request.user
                        payment.amount = order.get_total()
                        payment.order = order
                        payment.save()

                        form.save_info = form.cleaned_data.get('save_info')
                        if form.save_info:
                            shopping_address.default = True
                            shopping_address.save()
                    else:
                        messages.info(
                            self.request,
                            "Compila i campi obbligatori per continuare")
                        return redirect('checkout')

            messages.info(self.request,
                          "l'ordine è stato ricevuto con successo")
            return redirect('home')

            messages.warning(self.request,
                             "il checkout non è andato a buon fine ")
            return redirect('checkout')
            return render(self.request, 'core/ordine/order_summary.html',
                          context)
        except ObjectDoesNotExist:
            messages.warning(self.request, "Non hai nessun ordine in corso")
            return redirect('order-summary')