def membership(request, slug): slugs = [slug, 'membership/%s' % slug] the_category = None for categ in Category.objects.all(): if categ.slug in slugs: the_category = categ break if not the_category: log.debug('Sorry, could not find membership types matching "%s"' % slug) return HttpResponseRedirect('/') if request.method == 'POST': variation_id = int(request.POST.get('variation_id')) variation = ProductVariation.objects.get(id=variation_id) request.cart.add_item(variation, 1) recalculate_cart(request) messages.success(request, "Your membership has been added to cart") request.session['aftercheckout'] = request.GET.get('next', '/') if request.cart.total_price(): return redirect("shop_checkout") else: # For free membership, just fake the purchase process order = Order.objects.create() order.setup(request) order.complete(request) request.user.profile.set_membership_order(order) request.user.profile.save() checkout.send_order_email(request, order) return redirect("shop_complete") context = RequestContext(request, locals()) return render_to_response('bccf/membership/membership.html', {}, context_instance=context)
def finalize_order(request): '''Helper function that actually complete the order when the payment provider tells us so. ''' order_id = provider.get_order_id(request) order = Order.objects.get(pk=order_id) #Order is already completed if order.payment_done: return #Simulate the cart for the order.complete, and order_handler that needs it try: cart_id = provider.get_cart_id(request) request.cart = Cart.objects.get(id=cart_id) except (NotImplementedError, Cart.DoesNotExist, TypeError): pass #Recreate an order form for the order handler data = checkout.initial_order_data(request) data["step"] = checkout.CHECKOUT_STEP_LAST order_form_class = get_callable(settings.SHOP_CHECKOUT_FORM_CLASS) form = order_form_class(request, step=checkout.CHECKOUT_STEP_LAST, data=data) form.instance = order form.full_clean() request.session["order"] = dict(form.cleaned_data) order.transaction_id = provider.get_transaction_id(request) order.payment_done = True order.complete(request) order_handler(request, form, order) checkout.send_order_email(request, order)
def order_handler(request: Optional[HttpRequest], order_form, order: Order, payment: Optional[QuickpayPayment] = None): """Order paid in Quickpay payment window. Do not use for Quickpay API mode. request and order_form unused. Safe to call multiple times for same order (IS CALLED in payment process and in payment handler callback) NB: order.complete() is done here! With standard Cartridge credit card flow, order.complete() is called there! This is because we want complete() to be called within the atomic transaction! """ completed_now = False with transaction.atomic(): transaction_id = order.transaction_id # Re-read the order from the database to make sure it locked for atomicity. # This is important when calling order_handler from success() order: Order = Order.objects.filter(pk=order.pk).select_for_update()[0] status_authorized = getattr(settings, 'QUICKPAY_ORDER_STATUS_AUTHORIZED', None) if status_authorized and order.status < status_authorized or not order.transaction_id: logging.debug("payment_quickpay: order_handler(), order = %s" % order) if status_authorized: order.status = status_authorized if transaction_id: logging.debug("order_handler() - save transaction_id {}".format(transaction_id)) order.transaction_id = transaction_id order.save() if order.transaction_id: if payment and payment.is_captured: order_captured.send(sender=Order, instance=order, payment=payment) else: order_authorized.send(sender=Order, instance=order, payment=payment) else: logging.debug("order_handler() - order {} already being processed".format(order.id)) # Complete Order (delete basket, etc.). Not guaranteed to happen, e.g if user closes the browser too early # Possible problem: stock and discount usages not counted down if success URL not reached if request is not None: logging.debug("order_handler() - calling order.complete()") status_waiting = getattr(settings, 'QUICKPAY_ORDER_STATUS_WAITING', None) if status_waiting and order.status < status_waiting: completed_now = True order.status = status_waiting order.complete(request) # Saves, deletes basket order_completed.send(sender=Order, instance=order) if request is not None and completed_now: # Send mail to customer on success # Mail isn't sent if success page isn't reached. Shop admin can see that - the order will be in # ORDER_STATUS_AUTHORIZED whereas if the success page was reached, it's in _WAITING. # Outside transaction to shorten transaction time and to prevent transaction rollback if mail fails send_order_email(request, order)
def submit_order(self, context): order_form = context['order_form'] # Double check that order still has things if self.request.cart.has_items() is False: warning(self.request, _("Cart is empty")) return redirect('salesbro:portal_cart') if order_form.is_valid(): order = order_form.save(commit=False) order.setup(self.request) # TODO: Make transaction_id link to payment type somehow order.transaction_id = self.request.POST.get('payment_type') order.complete(self.request) salesbro_order_handler(request=self.request, order_form=order, order=order) checkout.send_order_email(request=self.request, order=order) return redirect('salesbro:portal_complete') else: return self.render_to_response(context=context)
def resend_email(request,order_id): """ Display a list of the currently logged-in user's past orders. """ ########### #send email according to order ############ order = Order.objects.filter(id=order_id) checkout.send_order_email(request, order[0]) ################# #redirect and add message ################# message= _("email has been sent.") info(request, message) url="home" response = redirect(url) return response
def invoice_resend_email(request, order_id): """ Re-sends the order complete email for the given order and redirects to the previous page. """ try: order = Order.objects.get_for_user(order_id, request) except Order.DoesNotExist: raise Http404 if request.method == "POST": checkout.send_order_email(request, order) msg = _("The order email for order ID %s has been re-sent") % order_id info(request, msg) # Determine the URL to return the user to. redirect_to = next_url(request) if redirect_to is None: if request.user.is_staff: redirect_to = reverse("admin:shop_order_change", args=[order_id]) else: redirect_to = reverse("shop_order_history") return redirect(redirect_to)
def invoice_resend_email(request, order_id): """ Re-sends the order complete email for the given order and redirects to the previous page. """ try: order = Order.objects.get_for_user(order_id, request) except Order.DoesNotExist: raise Http404 if request.method == "POST": checkout.send_order_email(request, order) msg = _("The order email for order ID %s has been re-sent" % order_id) info(request, msg) # Determine the URL to return the user to. redirect_to = next_url(request) if redirect_to is None: if request.user.is_staff: redirect_to = reverse("admin:shop_order_change", args=[order_id]) else: redirect_to = reverse("shop_order_history") return redirect(redirect_to)
def payments_order_processor(request, order): increment_num_sold(order) membership_ordered, level = check_membership_purchase_order(order) class_ordered, classes = check_class_purchase_order(order) fortune_ordered, fortunes = check_fortune_purchase_order(order) prayer_ordered, prayers = check_prayer_purchase_order(order) numerology_ordered, numerologies = check_numerology_purchase_order(order) checkout.send_order_email(request, order) if membership_ordered: request.user.membership.update_membership(level) if class_ordered: send_details_email(request, order, classes, _("Classes")) if fortune_ordered: send_details_email(request, order, fortunes, _("Fortunes")) if prayer_ordered: send_details_email(request, order, prayers, _("Prayers")) if numerology_ordered: send_details_email(request, order, numerologies, _("Numerologies")) order.paid = True order.paid_time = datetime.now() return order
def checkout_steps(request): """ Display the order form and handle processing of each step. """ # Do the authentication check here rather than using standard # login_required decorator. This means we can check for a custom # LOGIN_URL and fall back to our own login view. authenticated = request.user.is_authenticated() if settings.SHOP_CHECKOUT_ACCOUNT_REQUIRED and not authenticated: url = "%s?next=%s" % (settings.LOGIN_URL, reverse("shop_checkout")) return redirect(url) # Level C Discount if request.user.profile.is_level_C: request.session['force_discount'] = 'l3v3lC15' # Determine the Form class to use during the checkout process form_class = get_callable(settings.SHOP_CHECKOUT_FORM_CLASS) initial = checkout.initial_order_data(request, form_class) cancelled = request.GET.get('c', None) if not cancelled: step = int(request.POST.get("step", None) or initial.get("step", None) or checkout.CHECKOUT_STEP_FIRST) else: step = checkout.CHECKOUT_STEP_FIRST form = form_class(request, step, initial=initial) data = request.POST checkout_errors = [] log.debug('Checkout step %s' % step) if request.POST.get("back") is not None: # Back button in the form was pressed - load the order form # for the previous step and maintain the field values entered. step -= 1 form = form_class(request, step, initial=initial) elif request.method == "POST" and request.cart.has_items(): form = form_class(request, step, initial=initial, data=data) if form.is_valid(): # Copy the current form fields to the session so that # they're maintained if the customer leaves the checkout # process, but remove sensitive fields from the session # such as the credit card fields so that they're never # stored anywhere. request.session["order"] = dict(form.cleaned_data) sensitive_card_fields = ("card_number", "card_expiry_month", "card_expiry_year", "card_ccv") for field in sensitive_card_fields: if field in request.session["order"]: del request.session["order"][field] # FIRST CHECKOUT STEP - handle shipping and discount code. if step == checkout.CHECKOUT_STEP_FIRST: try: billship_handler(request, form) tax_handler(request, form) except checkout.CheckoutError, e: checkout_errors.append(e) form.set_discount() if form.cleaned_data.get('payment_method') == 'paypal': step += 1 try: request.session["order"]["step"] = step request.session.modified = True except KeyError: pass return redirect(Paypal.process(request, form)) # FINAL CHECKOUT STEP - handle payment and process order. if step == checkout.CHECKOUT_STEP_LAST and not checkout_errors: # Create and save the initial order object so that # the payment handler has access to all of the order # fields. If there is a payment error then delete the # order, otherwise remove the cart items from stock # and send the order receipt email. order = form.save(commit=False) order.setup(request) # Try payment. try: transaction_id = payment_handler(request, form, order) except checkout.CheckoutError, e: # Error in payment handler. order.delete() checkout_errors.append(e) if settings.SHOP_CHECKOUT_STEPS_CONFIRMATION: step -= 1 else: # Finalize order - ``order.complete()`` performs # final cleanup of session and cart. # ``order_handler()`` can be defined by the # developer to implement custom order processing. # Then send the order email to the customer. if form.cleaned_data.get('payment_method') == 'paypal': payment = Paypal.find(request) if payment.shipping_info: order.shipping_detail_first_name = payment.shipping_info.first_name order.shipping_detail_last_name = payment.shipping_info.last_name order.shipping_detail_street = payment.shipping_info.address.line1 order.shipping_detail_city = payment.shipping_info.address.city order.shipping_detail_state = payment.shipping_info.address.state order.shipping_detail_postcode = payment.shipping_info.address.postal_code order.shipping_detail_country = payment.shipping_info.address.country_code order.transaction_id = transaction_id order.complete(request) order_handler(request, form, order) checkout.send_order_email(request, order) # Set the cookie for remembering address details # if the "remember" checkbox was checked. response = redirect("shop_complete") if form.cleaned_data.get("remember"): remembered = "%s:%s" % (sign(order.key), order.key) set_cookie(response, "remember", remembered, secure=request.is_secure()) else: response.delete_cookie("remember") return response # If any checkout errors, assign them to a new form and # re-run is_valid. If valid, then set form to the next step. form = form_class(request, step, initial=initial, data=data, errors=checkout_errors) if form.is_valid(): step += 1 form = form_class(request, step, initial=initial)
def checkout(request): """ Display the order form and handle processing of each step. """ # Do the authentication check here rather than using standard login_required # decorator. This means we can check for a custom LOGIN_URL and fall back # to our own login view. if settings.SHOP_CHECKOUT_ACCOUNT_REQUIRED and \ not request.user.is_authenticated(): return HttpResponseRedirect("%s?next=%s" % (settings.SHOP_LOGIN_URL, reverse("shop_checkout"))) step = int(request.POST.get("step", CHECKOUT_STEP_FIRST)) initial = initial_order_data(request) form = OrderForm(request, step, initial=initial) data = request.POST if request.POST.get("back") is not None: step -= 1 form = OrderForm(request, step, initial=initial) elif request.method == "POST": form = OrderForm(request, step, initial=initial, data=data) if form.is_valid(): checkout_errors = [] request.session["order"] = dict(form.cleaned_data) for field in ("card_number", "card_expiry_month", "card_expiry_year", "card_ccv"): del request.session["order"][field] # Handle shipping and discount code on first step. if step == CHECKOUT_STEP_FIRST: try: billing_shipping(request, form) except CheckoutError, e: checkout_errors.append(e) if hasattr(form, "discount"): cart = Cart.objects.from_request(request) discount_total = discount.calculate(cart.total_price()) request.session["free_shipping"] = discount.free_shipping request.session["discount_total"] = discount_total # Process order on final step. if step == CHECKOUT_STEP_LAST and not checkout_errors: try: payment(request, form) except CheckoutError, e: checkout_errors.append(e) if settings.SHOP_CHECKOUT_STEPS_CONFIRMATION: step -= 1 else: order = form.save(commit=False) order.process(request) send_order_email(request, order) response = HttpResponseRedirect(reverse("shop_complete")) if form.cleaned_data.get("remember") is not None: remembered = "%s:%s" % (sign(order.key), order.key) set_cookie(response, "remember", remembered, secure=request.is_secure()) else: response.delete_cookie("remember") return response # Assign checkout errors to new form if any and re-run is_valid # if valid set form to next step. form = OrderForm(request, step, initial=initial, data=data, checkout_errors=checkout_errors) if form.is_valid(): step += 1 form = OrderForm(request, step, initial=initial)
def checkout_steps(request, form_class=OrderForm, extra_context=None): """ Display the order form and handle processing of each step. """ # Do the authentication check here rather than using standard # login_required decorator. This means we can check for a custom # LOGIN_URL and fall back to our own login view. authenticated = request.user.is_authenticated() if settings.SHOP_CHECKOUT_ACCOUNT_REQUIRED and not authenticated: url = "%s?next=%s" % (settings.LOGIN_URL, reverse("shop_checkout")) return redirect(url) try: settings.SHOP_CHECKOUT_FORM_CLASS except AttributeError: pass else: from warnings import warn warn("The SHOP_CHECKOUT_FORM_CLASS setting is deprecated - please " "define your own urlpattern for the checkout_steps view, " "passing in your own form_class argument.") form_class = import_dotted_path(settings.SHOP_CHECKOUT_FORM_CLASS) initial = checkout.initial_order_data(request, form_class) step = int( request.POST.get("step", None) or initial.get("step", None) or checkout.CHECKOUT_STEP_FIRST) form = form_class(request, step, initial=initial) data = request.POST checkout_errors = [] if request.POST.get("back") is not None: # Back button in the form was pressed - load the order form # for the previous step and maintain the field values entered. step -= 1 form = form_class(request, step, initial=initial) elif request.method == "POST" and request.cart.has_items(): form = form_class(request, step, initial=initial, data=data) if form.is_valid(): # Copy the current form fields to the session so that # they're maintained if the customer leaves the checkout # process, but remove sensitive fields from the session # such as the credit card fields so that they're never # stored anywhere. request.session["order"] = dict(form.cleaned_data) sensitive_card_fields = ("card_number", "card_expiry_month", "card_expiry_year", "card_ccv") for field in sensitive_card_fields: if field in request.session["order"]: del request.session["order"][field] # FIRST CHECKOUT STEP - handle discount code. This needs to # be set before shipping, to allow for free shipping to be # first set by a discount code. if step == checkout.CHECKOUT_STEP_FIRST: form.set_discount() # ALL STEPS - run billing/tax handlers. These are run on # all steps, since all fields (such as address fields) are # posted on each step, even as hidden inputs when not # visible in the current step. try: billship_handler(request, form) tax_handler(request, form) except checkout.CheckoutError as e: checkout_errors.append(e) # FINAL CHECKOUT STEP - run payment handler and process order. if step == checkout.CHECKOUT_STEP_LAST and not checkout_errors: # Create and save the initial order object so that # the payment handler has access to all of the order # fields. If there is a payment error then delete the # order, otherwise remove the cart items from stock # and send the order receipt email. order = form.save(commit=False) order.setup(request) # Try payment. try: transaction_id = payment_handler(request, form, order) except checkout.CheckoutError as e: # Error in payment handler. order.delete() checkout_errors.append(e) if settings.SHOP_CHECKOUT_STEPS_CONFIRMATION: step -= 1 else: # Finalize order - ``order.complete()`` performs # final cleanup of session and cart. # ``order_handler()`` can be defined by the # developer to implement custom order processing. # Then send the order email to the customer. order.transaction_id = transaction_id order.complete(request) order_handler(request, form, order) checkout.send_order_email(request, order) # Set the cookie for remembering address details # if the "remember" checkbox was checked. response = redirect("shop_complete") if form.cleaned_data.get("remember"): remembered = "%s:%s" % (sign(order.key), order.key) set_cookie(response, "remember", remembered, secure=request.is_secure()) else: response.delete_cookie("remember") return response # If any checkout errors, assign them to a new form and # re-run is_valid. If valid, then set form to the next step. form = form_class(request, step, initial=initial, data=data, errors=checkout_errors) if form.is_valid(): step += 1 form = form_class(request, step, initial=initial) # Update the step so that we don't rely on POST data to take us back to # the same point in the checkout process. try: request.session["order"]["step"] = step request.session.modified = True except KeyError: pass step_vars = checkout.CHECKOUT_STEPS[step - 1] template = "shop/%s.html" % step_vars["template"] context = { "CHECKOUT_STEP_FIRST": step == checkout.CHECKOUT_STEP_FIRST, "CHECKOUT_STEP_LAST": step == checkout.CHECKOUT_STEP_LAST, "CHECKOUT_STEP_PAYMENT": (settings.SHOP_PAYMENT_STEP_ENABLED and step == checkout.CHECKOUT_STEP_PAYMENT), "step_title": step_vars["title"], "step_url": step_vars["url"], "steps": checkout.CHECKOUT_STEPS, "step": step, "form": form } context.update(extra_context or {}) return TemplateResponse(request, template, context)
def checkout_steps(request): """ Display the order form and handle processing of each step. """ # Do the authentication check here rather than using standard # login_required decorator. This means we can check for a custom # LOGIN_URL and fall back to our own login view. authenticated = request.user.is_authenticated() if settings.SHOP_CHECKOUT_ACCOUNT_REQUIRED and not authenticated: url = "%s?next=%s" % (settings.LOGIN_URL, reverse("shop_checkout")) return redirect(url) # Determine the Form class to use during the checkout process form_class = get_callable(settings.SHOP_CHECKOUT_FORM_CLASS) initial = checkout.initial_order_data(request, form_class) step = int(request.POST.get("step", None) or initial.get("step", None) or checkout.CHECKOUT_STEP_FIRST) form = form_class(request, step, initial=initial) data = request.POST checkout_errors = [] if request.POST.get("back") is not None: # Back button in the form was pressed - load the order form # for the previous step and maintain the field values entered. step -= 1 form = form_class(request, step, initial=initial) elif request.method == "POST" and request.cart.has_items(): form = form_class(request, step, initial=initial, data=data) if form.is_valid(): # Copy the current form fields to the session so that # they're maintained if the customer leaves the checkout # process, but remove sensitive fields from the session # such as the credit card fields so that they're never # stored anywhere. request.session["order"] = dict(form.cleaned_data) sensitive_card_fields = ("card_number", "card_expiry_month", "card_expiry_year", "card_ccv") for field in sensitive_card_fields: if field in request.session["order"]: del request.session["order"][field] # FIRST CHECKOUT STEP - handle shipping and discount code. if step == checkout.CHECKOUT_STEP_FIRST: # Discount should be set before shipping, to allow # for free shipping to be first set by a discount # code. form.set_discount() try: billship_handler(request, form) tax_handler(request, form) except checkout.CheckoutError as e: checkout_errors.append(e) # FINAL CHECKOUT STEP - handle payment and process order. if step == checkout.CHECKOUT_STEP_LAST and not checkout_errors: # Create and save the initial order object so that # the payment handler has access to all of the order # fields. If there is a payment error then delete the # order, otherwise remove the cart items from stock # and send the order receipt email. order = form.save(commit=False) order.setup(request) # Try payment. try: transaction_id = payment_handler(request, form, order) except checkout.CheckoutError as e: # Error in payment handler. order.delete() checkout_errors.append(e) if settings.SHOP_CHECKOUT_STEPS_CONFIRMATION: step -= 1 else: # Finalize order - ``order.complete()`` performs # final cleanup of session and cart. # ``order_handler()`` can be defined by the # developer to implement custom order processing. # Then send the order email to the customer. order.transaction_id = transaction_id order.complete(request) order_handler(request, form, order) checkout.send_order_email(request, order) # Set the cookie for remembering address details # if the "remember" checkbox was checked. response = redirect("shop_complete") if form.cleaned_data.get("remember"): remembered = "%s:%s" % (sign(order.key), order.key) set_cookie(response, "remember", remembered, secure=request.is_secure()) else: response.delete_cookie("remember") return response # If any checkout errors, assign them to a new form and # re-run is_valid. If valid, then set form to the next step. form = form_class(request, step, initial=initial, data=data, errors=checkout_errors) if form.is_valid(): step += 1 form = form_class(request, step, initial=initial) # Update the step so that we don't rely on POST data to take us back to # the same point in the checkout process. try: request.session["order"]["step"] = step request.session.modified = True except KeyError: pass step_vars = checkout.CHECKOUT_STEPS[step - 1] template = "shop/%s.html" % step_vars["template"] context = {"CHECKOUT_STEP_FIRST": step == checkout.CHECKOUT_STEP_FIRST, "CHECKOUT_STEP_LAST": step == checkout.CHECKOUT_STEP_LAST, "step_title": step_vars["title"], "step_url": step_vars["url"], "steps": checkout.CHECKOUT_STEPS, "step": step, "form": form} return render(request, template, context)
def checkout_steps(request): """ Display the order form and handle processing of each step. """ # Do the authentication check here rather than using standard # login_required decorator. This means we can check for a custom # LOGIN_URL and fall back to our own login view. authenticated = request.user.is_authenticated() if settings.SHOP_CHECKOUT_ACCOUNT_REQUIRED and not authenticated: url = "%s?next=%s" % (settings.LOGIN_URL, reverse("shop_checkout")) return redirect(url) # Determine the Form class to use during the checkout process form_class = get_callable(settings.SHOP_CHECKOUT_FORM_CLASS) initial = checkout.initial_order_data(request, form_class) step = int( request.POST.get("step", None) or initial.get("step", None) or checkout.CHECKOUT_STEP_FIRST) form = form_class(request, step, initial=initial) data = request.POST checkout_errors = [] if request.POST.get("back") is not None: # Back button in the form was pressed - load the order form # for the previous step and maintain the field values entered. step -= 1 form = form_class(request, step, initial=initial) elif request.method == "POST" and request.cart.has_items(): form = form_class(request, step, initial=initial, data=data) if form.is_valid(): # Copy the current form fields to the session so that # they're maintained if the customer leaves the checkout # process, but remove sensitive fields from the session # such as the credit card fields so that they're never # stored anywhere. request.session["order"] = dict(form.cleaned_data) sensitive_card_fields = ("card_number", "card_expiry_month", "card_expiry_year", "card_ccv") for field in sensitive_card_fields: if field in request.session["order"]: del request.session["order"][field] # FIRST CHECKOUT STEP - handle shipping and discount code. if step == checkout.CHECKOUT_STEP_FIRST: try: billship_handler(request, form) tax_handler(request, form) except checkout.CheckoutError, e: checkout_errors.append(e) form.set_discount() # FINAL CHECKOUT STEP - handle payment and process order. if step == checkout.CHECKOUT_STEP_LAST and not checkout_errors: # Create and save the initial order object so that # the payment handler has access to all of the order # fields. If there is a payment error then delete the # order, otherwise remove the cart items from stock # and send the order receipt email. order = form.save(commit=False) order.setup(request) # Try payment. try: transaction_id = payment_handler(request, form, order) except checkout.CheckoutError, e: # Error in payment handler. order.delete() checkout_errors.append(e) if settings.SHOP_CHECKOUT_STEPS_CONFIRMATION: step -= 1 else: # Finalize order - ``order.complete()`` performs # final cleanup of session and cart. # ``order_handler()`` can be defined by the # developer to implement custom order processing. # Then send the order email to the customer. order.transaction_id = transaction_id order.complete(request) order_handler(request, form, order) checkout.send_order_email(request, order) # Set the cookie for remembering address details # if the "remember" checkbox was checked. response = redirect("shop_complete") if form.cleaned_data.get("remember"): remembered = "%s:%s" % (sign(order.key), order.key) set_cookie(response, "remember", remembered, secure=request.is_secure()) else: response.delete_cookie("remember") return response # If any checkout errors, assign them to a new form and # re-run is_valid. If valid, then set form to the next step. form = form_class(request, step, initial=initial, data=data, errors=checkout_errors) if form.is_valid(): step += 1 form = form_class(request, step, initial=initial)
def checkout_steps(request): """ Display the order form and handle processing of each step. """ # Do the authentication check here rather than using standard # login_required decorator. This means we can check for a custom # LOGIN_URL and fall back to our own login view. authenticated = request.user.is_authenticated() if settings.SHOP_CHECKOUT_ACCOUNT_REQUIRED and not authenticated: url = "%s?next=%s" % (settings.LOGIN_URL, reverse("shop_checkout")) return HttpResponseRedirect(url) step = int(request.POST.get("step", checkout.CHECKOUT_STEP_FIRST)) initial = checkout.initial_order_data(request) form = OrderForm(request, step, initial=initial) data = request.POST checkout_errors = [] if request.POST.get("back") is not None: # Back button in the form was pressed - load the order form # for the previous step and maintain the field values entered. step -= 1 form = OrderForm(request, step, initial=initial) elif request.method == "POST": form = OrderForm(request, step, initial=initial, data=data) if form.is_valid(): # Copy the current form fields to the session so that # they're maintained if the customer leaves the checkout # process, but remove sensitive fields from the session # such as the credit card fields so that they're never # stored anywhere. request.session["order"] = dict(form.cleaned_data) sensitive_card_fields = ("card_number", "card_expiry_month", "card_expiry_year", "card_ccv") for field in sensitive_card_fields: del request.session["order"][field] # FIRST CHECKOUT STEP - handle shipping and discount code. if step == checkout.CHECKOUT_STEP_FIRST: try: billship_handler(request, form) except checkout.CheckoutError, e: checkout_errors.append(e) form.set_discount() # FINAL CHECKOUT STEP - handle payment and process order. if step == checkout.CHECKOUT_STEP_LAST and not checkout_errors: # Create and save the inital order object so that # the payment handler has access to all of the order # fields. If there is a payment error then delete the # order, otherwise remove the cart items from stock # and send the order reciept email. order = form.save(commit=False) order.setup(request) # Try payment. try: payment_handler(request, form, order) except checkout.CheckoutError, e: # Error in payment handler. order.delete() checkout_errors.append(e) if settings.SHOP_CHECKOUT_STEPS_CONFIRMATION: step -= 1 else: # Finalize order - ``order.complete()`` performs # final cleanup of session and cart. # ``order_handler()`` can be defined by the # developer to implement custom order processing. # Then send the order email to the customer. order.complete(request) order_handler(request, form, order) checkout.send_order_email(request, order) # Set the cookie for remembering address details # if the "remember" checkbox was checked. response = HttpResponseRedirect(reverse("shop_complete")) if form.cleaned_data.get("remember") is not None: remembered = "%s:%s" % (sign(order.key), order.key) set_cookie(response, "remember", remembered, secure=request.is_secure()) else: response.delete_cookie("remember") return response # If any checkout errors, assign them to a new form and # re-run is_valid. If valid, then set form to the next step. form = OrderForm(request, step, initial=initial, data=data, errors=checkout_errors) if form.is_valid(): step += 1 form = OrderForm(request, step, initial=initial)
def checkout_steps(request, form_class=OrderForm): """ Display the order form and handle processing of each step. """ #cart(request) # Do the authentication check here rather than using standard # login_required decorator. This means we can check for a custom # LOGIN_URL and fall back to our own login view. authenticated = request.user.is_authenticated() onekey = request.GET.get('keycode', None) checkout_errors = [] #add get instead of request.session['onekeycode'] #when homepage change to network+ style, weixin onekey order error that no onekeycode in session #but pc is OK, guess due to cookie forbidden within weixin browser, not diginto yet, just workaround here if onekey and onekey != request.session.get('onekeycode', None): #raise Exception('code got right!') #checkout_errors.append('您可能存在恶意下单,请联系客服,非常抱歉给您带来不便!') pass if settings.SHOP_CHECKOUT_ACCOUNT_REQUIRED and not authenticated and not onekey: url = "%s?next=%s" % (settings.LOGIN_URL, reverse("shop_checkout")) return redirect(url) #wni: add here for weixin pay #weixincode = request.GET.get('code',None) if settings.WITH_WEIXIN_PAY: weixinopenid = request.session.get('openid', None) if 'micromessenger' in request.META.get('HTTP_USER_AGENT').lower( ) and not weixinopenid: #and not weixincode: api_pub = JsApi_pub() #url = api_pub.createOauthUrlForCode(reverse('weixin:usercode',args=(tmp_no,),current_app=resolve(request.path).namespace)) #url = api_pub.createOauthUrlForCode('http://eason.happydiaosi.com/weixin/getusercode') url = api_pub.createOauthUrlForCode('http://%s' % settings.SITE_DOMAIN + reverse('weixin:usercode')) return redirect(url) try: settings.SHOP_CHECKOUT_FORM_CLASS except AttributeError: pass else: from warnings import warn warn("The SHOP_CHECKOUT_FORM_CLASS setting is deprecated - please " "define your own urlpattern for the checkout_steps view, " "passing in your own form_class argument.") form_class = import_dotted_path(settings.SHOP_CHECKOUT_FORM_CLASS) initial = checkout.initial_order_data(request, form_class) step = int( request.POST.get("step", None) or initial.get("step", None) or checkout.CHECKOUT_STEP_FIRST) form = form_class(request, step, initial=initial) data = request.POST #checkout_errors = [] if request.POST.get("back") is not None: # Back button in the form was pressed - load the order form # for the previous step and maintain the field values entered. step -= 1 form = form_class(request, step, initial=initial) elif request.method == "POST" and request.cart.has_items(): form = form_class(request, step, initial=initial, data=data) if form.is_valid(): #human = True # Copy the current form fields to the session so that # they're maintained if the customer leaves the checkout # process, but remove sensitive fields from the session # such as the credit card fields so that they're never # stored anywhere. request.session["order"] = dict(form.cleaned_data) sensitive_card_fields = ("card_number", "card_expiry_month", "card_expiry_year", "card_ccv") for field in sensitive_card_fields: if field in request.session["order"]: del request.session["order"][field] # FIRST CHECKOUT STEP - handle shipping and discount code. if step == checkout.CHECKOUT_STEP_FIRST: # Discount should be set before shipping, to allow # for free shipping to be first set by a discount # code. form.set_discount() try: billship_handler(request, form) tax_handler(request, form) except checkout.CheckoutError as e: checkout_errors.append(e) #wni: added for wx pay, for get order total on confirmation page #tmp_order = form.save(commit=False) #request.session['wni_wxpay_total'] = tmp_order.get_tmp_total(request) # FINAL CHECKOUT STEP - handle payment and process order. if step == checkout.CHECKOUT_STEP_LAST and not checkout_errors: # Create and save the initial order object so that # the payment handler has access to all of the order # fields. If there is a payment error then delete the # order, otherwise remove the cart items from stock # and send the order receipt email. order = form.save(commit=False) order.setup(request) # Try payment. try: transaction_id = payment_handler(request, form, order) except checkout.CheckoutError as e: # Error in payment handler. order.delete() checkout_errors.append(e) if settings.SHOP_CHECKOUT_STEPS_CONFIRMATION: step -= 1 else: # Finalize order - ``order.complete()`` performs # final cleanup of session and cart. # ``order_handler()`` can be defined by the # developer to implement custom order processing. # Then send the order email to the customer. order.transaction_id = transaction_id order.complete(request) order_handler(request, form, order) checkout.send_order_email(request, order) # Set the cookie for remembering address details # if the "remember" checkbox was checked. response = redirect("shop_complete") if form.cleaned_data.get("remember"): remembered = "%s:%s" % (sign(order.key), order.key) set_cookie(response, "remember", remembered, secure=request.is_secure()) else: response.delete_cookie("remember") return response # If any checkout errors, assign them to a new form and # re-run is_valid. If valid, then set form to the next step. form = form_class(request, step, initial=initial, data=data, errors=checkout_errors) #print type(form.errors),form.errors #form.errors.clear() if form.is_valid(): step += 1 #human = True form = form_class(request, step, initial=initial) # Update the step so that we don't rely on POST data to take us back to # the same point in the checkout process. try: request.session["order"]["step"] = step request.session.modified = True except KeyError: pass step_vars = checkout.CHECKOUT_STEPS[step - 1] template = "shop/%s.html" % step_vars["template"] context = { "CHECKOUT_STEP_FIRST": step == checkout.CHECKOUT_STEP_FIRST, "CHECKOUT_STEP_LAST": step == checkout.CHECKOUT_STEP_LAST, "step_title": step_vars["title"], "step_url": step_vars["url"], "steps": checkout.CHECKOUT_STEPS, "step": step, "form": form } return render(request, template, context)