Exemplo n.º 1
0
    def test_balance_loan_two_payments(self):
        client_data = {
            "name": "Felicity",
            "surname": "Jones",
            "email": "*****@*****.**",
            "telephone": "11984345678",
            "cpf": "34598712376",
        }
        self.client.post("/clients/", client_data, format="json")

        loan = {"client": 1, "amount": 1000, "term": 12, "rate": 0.05}
        self.client.post("/loans/", loan, format="json")

        payment1 = Payment(
            loan=Loan.objects.get(pk=1),
            user=self.user,
            payment="made",
            date=datetime.strptime("10042019", "%d%m%Y"),
            amount=Loan.objects.get(pk=1).installment,
        )
        payment1.save()

        payment2 = Payment(
            loan=Loan.objects.get(pk=1),
            user=self.user,
            payment="made",
            date=datetime.strptime("10052019", "%d%m%Y"),
            amount=Loan.objects.get(pk=1).installment,
        )
        payment2.save()

        response = self.client.get("/loans/1/balance/")
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertContains(response, 856.07)
Exemplo n.º 2
0
def pay(request):
    errors = ""
    if request.method == 'POST':
        form = PayForm(request.POST)
        if form.is_valid():

            # validate existing member
            member_email = form.cleaned_data['member_email']
            payment_amount = form.cleaned_data['payment_amount']
            member = Member.objects.filter(email=member_email)

            if not member:
                errors = "Invalid Member."
            else:
                payment = Payment(
                    member=member[0],
                    amount=payment_amount,
                )
                payment.save()

                return render(request, 'pay.html',
                              {'message': 'Payment added!'})
    else:
        form = PayForm()

    return render(request, 'pay.html', {'form': form, 'errors': errors})
Exemplo n.º 3
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))
Exemplo n.º 4
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)
Exemplo n.º 5
0
    def post(self, request):
        amount = request.POST["amount"]
        credit = request.POST["credit"]
        date = request.POST["date"]

        data = Payment(amount=amount, credit_no=credit, date=date)
        data.save()

        return render(request, 'core/payment.html')
Exemplo n.º 6
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 !')
Exemplo n.º 7
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()
Exemplo n.º 8
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)
        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]
        amount = int(order.get_total() * EXCHANGE_RATE) * 100
        serializer = PaystackSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        info = serializer.data
        if info['status'] == "success" and info['message'] == "Approved":
            payment = Payment(user=request.user,
                              amount=order.get_total() * EXCHANGE_RATE,
                              stripe_charge_id=str(info['reference']) +
                              "-paystack",
                              timestamp=datetime.datetime.now()).save()
            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 = info['reference']
            order.save()
            return Response({'message': "Payment Successful."},
                            status=HTTP_200_OK)
        return Response({'message': "Payment Error."},
                        status=HTTP_400_BAD_REQUEST)
Exemplo n.º 9
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)
Exemplo n.º 10
0
 def post(self, request, *args, **kwargs):
     serializer = self.get_serializer(data=request.data)
     serializer.is_valid(raise_exception=True)
     payment = Payment()
     try:
         payment.contract = Contract.objects.get(
             id=serializer.data['contract'])
     except:
         return Response("Contract don't exists.")
     payment.payment_amount = serializer.data['payment_amount']
     payment.save()
     headers = self.get_success_headers(serializer.data)
     return Response(serializer.data,
                     status=status.HTTP_201_CREATED,
                     headers=headers)
Exemplo n.º 11
0
def import_reservations(reservation_file, payment_file, location_id,
                        room_offset):
    json_file = open(reservation_file)
    reservation_data = json.load(json_file)
    json_file.close()

    json_file = open(payment_file)
    payment_data = json.load(json_file)
    json_file.close()

    location = Location.objects.get(pk=location_id)
    print "location=%s" % location.name
    '''
	{
	    "pk": 3,
	    "model": "core.payment",
	    "fields": {
	        "automatic_invoice": false,
	        "payment_date": "2014-04-20T01:45:29.635Z",
	        "paid_amount": "225",
	        "payment_method": "Visa",
	        "reservation": 3,
	        "payment_service": "Stripe",
	        "transaction_id": "ch_103svy24GAclB9sbIZjFL5LY"
	    }
	}
	'''
    payments_by_reservation = {}
    for p in payment_data:
        payment = p['fields']
        payment_id = p['pk']
        if 'reservation' in payment:
            reservation_id = payment['reservation']
            payments_by_reservation[reservation_id] = payment
        else:
            print "payment %s has no reservation!" % payment_id
    #print payments_by_reservation
    '''
	{
	    "pk": 1,
	    "model": "core.reservation",
	    "fields": {
	        "status": "canceled",
	        "updated": "2014-08-26T22:46:47.303Z",
	        "depart": "2014-04-05",
	        "room": 1,
	        "last_msg": "2014-04-02T20:40:06.221Z",
	        "created": "2014-04-02T20:34:16.979Z",
	        "purpose": "kdjkj",
	        "tags": "",
	        "comments": "",
	        "arrival_time": "",
	        "rate": 75,
	        "user": [
	            "meganlipsett"
	        ],
	        "arrive": "2014-04-02",
	        "location": 1
	    }
	},
	'''
    for r in reservation_data:
        old_reservation = r['fields']
        old_reservation_id = r['pk']

        old_room_id = old_reservation['room']
        new_room_id = int(old_room_id) + room_offset
        print "old_reservation_id = %s, old_room_id = %s, new_room_id = %s" % (
            old_reservation_id, old_room_id, new_room_id)
        new_room = Room.objects.get(id=new_room_id)
        #print "room = %s" % new_room.name
        username = r['fields']['user'][0]
        user = User.objects.filter(username=username).first()

        new_reservation = Reservation(
            status=old_reservation['status'],
            updated=old_reservation['updated'],
            depart=old_reservation['depart'],
            last_msg=old_reservation['last_msg'],
            created=old_reservation['created'],
            purpose=old_reservation['purpose'],
            tags=old_reservation['tags'],
            comments=old_reservation['comments'],
            rate=old_reservation['rate'],
            arrive=old_reservation['arrive'],
            user=user,
            location=location,
            room=new_room,
        )
        new_reservation.save()
        #print new_reservation

        # Now create the payment for this new reservation
        if old_reservation_id in payments_by_reservation:
            old_payment = payments_by_reservation[old_reservation_id]
            print "reservation %s has payment of $%s" % (
                old_reservation_id, old_payment['paid_amount'])
            new_payment = Payment(
                payment_method=old_payment['payment_method'],
                payment_service=old_payment['payment_service'],
                transaction_id=old_payment['transaction_id'],
                paid_amount=old_payment['paid_amount'],
                reservation=new_reservation,
            )
            new_payment.save()
            new_payment.payment_date = old_payment['payment_date']
            new_payment.save()

        # Pull the reservation back out of the DB and recalculate the bill
        pulled_reservation = Reservation.objects.get(id=new_reservation.id)
        pulled_reservation.generate_bill()
Exemplo n.º 12
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)
Exemplo n.º 13
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)
Exemplo n.º 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)
        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)
Exemplo n.º 15
0
 def setUp(self):
     self.obj = Payment(stripe_charge_id="123123123", amount="1500")
Exemplo n.º 16
0
                  color=fake.color_name(),
                  engineer=engineer,
                  park=park,
                  car_plate=2)
    p = random_date(d1, d2)
    z = p + timedelta(hours=randint(1, 9))
    order = Order(
        customer=customer,
        car=car,
        time_begin=p,
        time_end=z,
        location_begin=str(randint(0, 1000)) + ' ' + str(randint(0, 1000)),
        location_end=str(randint(0, 1000)) + ' ' + str(randint(0, 1000)),
        location_car=str(randint(0, 1000)) + ' ' + str(randint(0, 1000)))
    order.save()
    payment = Payment(order=order, time_of_payment=z, price=randint(25, 500))
    payment.save()

for i in range(0, 110):
    try:
        operator = Operator.objects.get(info=Employee.objects.get(
            username='******'))
    except Operator.DoesNotExist:
        employee = Employee(username=fake.user_name(),
                            first_name=fake.first_name(),
                            last_name=fake.last_name(),
                            email=fake.free_email(),
                            phone_number=fake.phone_number())
        employee.save()
        operator = Operator(info=employee, park=park, car=None)
    try:
Exemplo n.º 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')
Exemplo n.º 18
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/")
    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)
Exemplo n.º 20
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)
Exemplo n.º 21
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)
        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]
        amount = int(order.get_total() * EXCHANGE_RATE) * 100

        serializer = CardSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        info = serializer.data
        payload = {
            'email': info['email'],
            # 'amount': (int(info['amount'] * EXCHANGE_RATE) * 100),  # to dollars
            'amount': amount,
            'card': {
                'cvv': info['cvv'],
                'number': info['number'],
                'expiry_month': info['expiry_month'],
                'expiry_year': info['expiry_year']
            },
            'pin': info['pin']
        }
        # print(json.dumps(request.data, sort_keys=True, indent=4))
        # print(json.dumps(info, sort_keys=True, indent=4), serializer.is_valid())
        # print(json.dumps(payload, sort_keys=True, indent=4))
        url = "https://api.paystack.co/charge"
        headers = {
            'Authorization': f'Bearer {PAYSTACK_SECRET_KEY}',
        }
        r = requests.request("POST",
                             url,
                             headers=headers,
                             data=(json.dumps(payload)))
        res = r.json()
        print(json.dumps(res, sort_keys=True, indent=4))
        if res['status']:
            payment = Payment(
                stripe_charge_id=str(res['data']['id']) + "-" +
                str(res['data']['reference']) + "-paystack-id-ref",
                user=User.objects.get(is_superuser=True),
                amount=(order.get_total() * EXCHANGE_RATE),
                timestamp=datetime.datetime.fromisoformat(
                    res['data']['paid_at'][:-1] + "+00:00")).save()

            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 = res['data']['reference']
            order.save()

            del res['data']['id']
            del res['data']['authorization']
            del res['data']['customer']
            return Response({
                'message': "Payment Successful.",
                "response": res
            },
                            status=HTTP_200_OK)
        return Response({
            'message': "Payment Error.",
            "response": res
        },
                        status=HTTP_400_BAD_REQUEST)
Exemplo n.º 22
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)
Exemplo n.º 23
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)
Exemplo n.º 24
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("/")
Exemplo n.º 25
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)