def clean(self): """ The clean method will effectively charge the card and create a new Sale instance. If it fails, it simply raises the error given from Stripe's library as a standard ValidationError for proper feedback. """ cleaned = super(SalePaymentForm, self).clean() if not self.errors: number = self.cleaned_data["number"] exp_month = self.cleaned_data["expiration"].month exp_year = self.cleaned_data["expiration"].year cvc = self.cleaned_data["cvc"] sale = Payment() # let's charge $10.00 for this particular item success, instance = sale.charge(1000, number, exp_month, exp_year, cvc) if not success: raise forms.ValidationError("Error: %s" % instance.message) else: instance.save() # we were successful! do whatever you will here... # perhaps you'd like to send an email... pass return cleaned
def make_payment(self, order): if order.owner.edit_balance(order.total_price, "-"): p = Payment(amount=order.total_price, order=order, sold_after=order.owner.balance) p.save() return True return False
def generate_payments(order): people = set() for p in order.team.person_set.all(): people.add(p) for oi in order.orderitem_set.filter(personal=True): if oi.person.team != order.team: people.add(oi.person) for p in people: # determine if there is any back-payment/credit previous_payments = Payment.objects.filter(person=p) old_amount = decimal.Decimal(0) for pp in previous_payments: old_amount -= (pp.owed - pp.paid) owed = p.amount_owed_for_order(order) - old_amount payment = Payment(person=p, order=order, owed=owed) payment.save()
def analysis_view(request): date_range = request.GET.get('daterange') orders = Order.filters_data(request, Order.objects.all()) payments = Payment.filters_data(request, Payment.objects.all()) costumers_orders = orders.values('customer__first_name', 'customer__last_name').annotate(total=Sum('value')).order_by('-total') costumers_payments = payments.values('customer__first_name', 'customer__last_name').annotate(total=Sum('value')).order_by('-total') total_value = orders.aggregate(Sum('value'))['value__sum'] if orders else 0 total_payment = payments.aggregate(Sum('value'))['value__sum'] if payments else 0 difference = total_value - total_payment currency = CURRENCY context = locals() return render(request, 'analysis.html', context)
def ajax_analysis_view(request): date_range = request.GET.get('date_range') orders = Order.filters_data(request, Order.objects.all()) payments = Payment.filters_data(request, Payment.objects.all()) costumers_orders = orders.values( 'customer__first_name', 'customer__last_name').annotate(total=Sum('value')).order_by('-total') costumers_payments = payments.values( 'customer__first_name', 'customer__last_name').annotate(total=Sum('value')).order_by('-total') total_value = orders.aggregate(Sum('value'))['value__sum'] if orders else 0 total_payment = payments.aggregate( Sum('value'))['value__sum'] if payments else 0 difference = total_value - total_payment data = dict() data['result'] = render_to_string( template_name='ajax_views/ajax_analysis_view.html', request=request, context=locals()) return JsonResponse(data)
def place_order(request, total=0, quantity=0): current_user = request.user cart_items = CartItem.objects.filter(user=current_user) cart_count = cart_items.count() if cart_count <= 0: return redirect('store') delivery = 2000 for cart_item in cart_items: total += (cart_item.product.price * cart_item.quantity) quantity += cart_item.quantity if total > 50000: delivery = 0 grand_total = delivery + total if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): data = Order() data.user = current_user data.first_name = form.cleaned_data['first_name'] data.last_name = form.cleaned_data['last_name'] data.phone = form.cleaned_data['phone'] data.email = form.cleaned_data['email'] data.address = form.cleaned_data['address'] data.country = form.cleaned_data['country'] data.state = form.cleaned_data['state'] data.city = form.cleaned_data['city'] data.order_note = form.cleaned_data['order_note'] data.order_total = grand_total data.delivery = delivery data.ip = request.META.get('REMOTE_ADDR') data.save() yr = int(datetime.date.today().strftime('%Y')) dt = int(datetime.date.today().strftime('%d')) mt = int(datetime.date.today().strftime('%m')) d = datetime.date(yr, mt, dt) current_date = d.strftime('%Y%m%d') order_number = current_date + str(data.id) data.order_number = order_number data.save() # Код без оплаты, оформление заказа order = Order.objects.get(user=request.user, is_ordered=False, order_number=order_number) payment = Payment( user=request.user, payment_id=order.id, payment_method='Оплата курьеру', amount_paid=grand_total, status='В заказе', ) payment.save() order.payment = payment order.is_ordered = True order.save() cart_items = CartItem.objects.filter(user=request.user) for item in cart_items: order_product = OrderProduct() order_product.order_id = order.id order.payment = payment order_product.user_id = request.user.id order_product.size = item.size order_product.product_id = item.product_id order_product.quantity = item.quantity order_product.product_price = item.product.price order_product.ordered = True order_product.save() # уменьшение колличества товара size = Size.objects.get(product=item.product_id, size=item.size) size.stock -= item.quantity size.save() # очистка корзины CartItem.objects.filter(user=request.user).delete() # отправка письма mail_subject = 'Спасибо за покупку!' message = render_to_string('orders/order_received_email.html', { 'user': current_user, 'order': order, }) to_email = request.user.email send_email = EmailMessage(mail_subject, message, to=[to_email]) send_email.send() order_email(order.id) return redirect('order_complete') else: return redirect('checkout')
def execute(request): """ MyApp > Paypal > Execute a Payment """ if 'payment_id' in request.session: payment_id = request.session['payment_id'] payer_id = request.GET['PayerID'] else: error = '<p>We are sorry but something went wrong.</p>' return render(request, 'paypal/errors.html', { 'error': error, }) paypalrestsdk.configure({ "mode": settings.PAYPAL_MODE, "client_id": settings.PAYPAL_CLIENT_ID, "client_secret": settings.PAYPAL_CLIENT_SECRET }) payment = paypalrestsdk.Payment.find(payment_id) payment_name = payment.transactions[0].description # Get payment from DB paypal_payment = PayPalPayment.objects.get(ref=payment_id) # get related order order = paypal_payment.related_order if payment.execute({"payer_id": payer_id}): # the payment has been accepted # Create order payment order_payment = Payment( order=order, type=PaymentType.objects.get(pk=1), payed=True, payment_ref=payment_id, value_inc=paypal_payment.value, ) order_payment.save() order.open = False order.waiting_payment = False order.save() paypal_payment.successful = timezone.now() paypal_payment.save() if request.session['payment_id']: del request.session['payment_id'] if request.session['order_id']: del request.session['order_id'] html = "<p>Thank you for your payment. A confirmation email has been sent containing your order details</p>" return render(request, 'paypal/success.html', { 'html': html, }) else: # the payment is not valid # Re-open order as payment was not taken order.open = True order.waiting_payment = False order.save() del request.session['payment_id'] error = '<p>We are sorry but something went wrong.</p>' \ '<p>'+str(payment.error)+'</p>' return render(request, 'paypal/errors.html', { 'error': error, })
def post(self, *args, **kwargs): order_qs = Order.objects.filter(user=self.request.user, ordered=False) form = PaymentForm(self.request.POST or None) userprofile = UserProfile.objects.get(user=self.request.user) token_b = self.request.POST.get("stripeToken") print(token_b) if form.is_valid(): print(form.cleaned_data) token = form.cleaned_data.get("stripeToken") save = form.cleaned_data.get("save") use_default = form.cleaned_data.get("use_default") if order_qs.exists(): order = order_qs.first() amount = int(order.get_total() * 100) 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() # create the payment try: # Use Stripe's library to make requests... 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) payment = Payment() payment.amount = amount / 100 payment.stripe_charge_id = charge.id payment.user = self.request.user payment.save() order_item_qs = order.items.all() order_item_qs.update(ordered=True) for order_item in order_item_qs: order_item.save() order.ordered = True order.payment = payment # creating the ref code order.ref_code = create_ref_code() order.save() messages.success(self.request, "Your Order was successfull") return redirect("orders:item_list") except stripe.error.CardError as e: # Since it's a decline, stripe.error.CardError will be caught messages.warning(self.request, f"{e.error.get('message')}") return redirect("orders:payment-stripe") except stripe.error.RateLimitError as e: # Too many requests made to the API too quickly messages.warning(self.request, f"{e.error.get('message')}") return redirect("orders:payment-stripe") except stripe.error.InvalidRequestError as e: # Invalid parameters were supplied to Stripe's API messages.warning(self.request, f"{e.error.get('message')}") return redirect("orders:payment-stripe") except stripe.error.AuthenticationError as e: # Authentication with Stripe's API failed # (maybe you changed API keys recently) messages.warning(self.request, f"{e.error.get('message')}") return redirect("orders:payment-stripe") except stripe.error.APIConnectionError as e: messages.warning(self.request, f"{e.error.get('message')}") return redirect("orders:payment-stripe") except stripe.error.StripeError as e: # Display a very generic error to the user, and maybe send # yourself an email messages.warning(self.request, f"{e.error.get('message')}") return redirect("orders:payment-stripe") except Exception as e: # Something else happened, completely unrelated to Stripe messages.warning( self.request, "Something happned please contact administrator") return redirect("orders:payment-stripe") return redirect('orders:payment-stripe')