def update_cart(request): pending = '' qerror = '' from django.middleware.csrf import get_token csrf_token = get_token(request) reload = 'location.reload(true);' if request.method == 'POST': postdata = request.POST.copy() page_title = postdata['page_title'] if postdata['submit'] == 'Remove': if pending_checker(request) == 0: pending = 'You have a pending transaction on this cart' else: cart.remove_from_cart(request) if postdata['submit'] == 'Update': if pending_checker(request) == 0: pending = 'You have a pending transaction on this cart' else: try: int(postdata['quantity']) cart.update_cart(request) except: if cart.cart_distinct_item_count(request) > 0: qerror = 'Invalid Quantity Value' paid = '' subtotal = cart.cart_subtotal(request) cart_items = cart.get_cart_items(request) cart_item_count = cart.cart_distinct_item_count(request) # Put this in here so that it cuts across all pages and it is related to cart. See function def for comments if bgprocess(request) == 0: paid = "(Paid)" cart_template = "tags/cart_box.html" cart_html = render_to_string(cart_template, locals()) if len(pending) == 0 and len(qerror) == 0: cart_items = cart.get_cart_items(request) cart_subtotal = cart.cart_subtotal(request) template = "cart/cart_preview.html" html = render_to_string(template, locals()) print(html) response = simplejson.dumps({ 'success': 'True', 'html': html, 'cart_html': cart_html }) else: html = '<p class="errorlist">{{ qerror }}</p>' response = simplejson.dumps({'success': 'False', 'html': html}) return HttpResponse(response, content_type='application/javascript; charset=utf-8')
def process(request): # Transaction results APPROVED = '1' DECLINED = '2' ERROR = '3' HELD_FOR_REVIEW = '4' postdata = request.POST.copy() card_num = postdata.get('credit_card_number','') exp_month = postdata.get('credit_card_expire_month','') exp_year = postdata.get('credit_card_expire_year','') exp_date = exp_month + exp_year cvv = postdata.get('credit_card_cvv','') amount = cart.cart_subtotal(request) results = {} response = authnet.do_auth_capture(amount=amount, card_num=card_num, exp_date=exp_date, card_cvv=cvv) if response[0] == APPROVED: transaction_id = response[6] order = create_order(request, transaction_id) results = {'order_number':order.id,'message':''} if response[0] == DECLINED: results = {'order_number':0, 'message': 'There is a problem with your credit card.'} if response[0] == ERROR or response[0] == HELD_FOR_REVIEW: results = {'order_number':0, 'message':'Error processing your order.'} return results
def show_cart(request, template_name="cart/cart.html"): currency_symbol = request.session.get('currency_symbol', '$') currency_rate = request.session.get('currency_rate', 1) if request.method == 'POST': postdata = request.POST.copy() if postdata['mode'] == 'remove': cart.remove_from_cart(request) if postdata['mode'] == 'update': cart.update_cart(request) print( '----------------------------------------------------------------------' ) print(postdata) # return render_to_response(template_name,locals(),context_instance=RequestContext(request)) cart_items = cart.get_cart_items(request) for c_item in cart_items: c_item.price = math.floor( c_item.price() / decimal.Decimal(currency_rate) * 100) / 100 c_item.total = math.floor( c_item.total() / decimal.Decimal(currency_rate) * 100) / 100 page_title = 'Shopping Cart' cart_subtotal = cart.cart_subtotal(request) mode = 'cart' # currency = '€' return render_to_response(template_name, locals(), context_instance=RequestContext(request))
def _charge_card(request): # Set your secret key: remember to change this to your live secret key in production # See your keys here: https://dashboard.stripe.com/account/apikeys stripe.api_key = "sk_test_WLxYShx8DyIsJkDKDAjQlpFU" # Token is created using Stripe.js or Checkout! # Get the payment token submitted by the form: token = request.POST['stripeToken'] amount = int(cart.cart_subtotal(request) * 100) try: # Charge the user's card: charge = stripe.Charge.create( amount=amount, currency="usd", description="Example charge", source=token, ) except stripe.error.CardError as e: # The card has been declined pass return charge
def process(request): # Transaction results APPROVED = '1' DECLINED = '2' ERROR = '3' HELD_FOR_REVIEW = '4' results = {} postdata = request.POST.copy() if postdata.get('payment_method',False) == "credit_card": card_num = postdata.get('credit_card_number','') exp_month = postdata.get('credit_card_expire_month','') exp_year = postdata.get('credit_card_expire_year','') exp_date = exp_month + exp_year cvv = postdata.get('credit_card_cvv','') amount = cart.cart_subtotal(request) response = authnet.do_auth_capture(amount=amount,card_num=card_num,exp_date=exp_date,card_cvv=cvv) if response[0] == APPROVED: transaction_id = response[6] order = create_order(request, transaction_id) results = {'order_number':order.id,'message':''} if postdata.get('payment_method',False) == "paypal": response = paypal_checkout.create_paypal_payment(request) if response.get('id',False): # This means the transaction was approved order = create_order(request, response.get('id')) results = {'order_number':order.id,'message':''} links = response.get("links",False) if links: approval_link = filter(lambda link: link['rel'] == 'approval_url', links) results = {'order_number':order.id,'message':'','approval_link':approval_link} else: return False return results
def checkout(request): if request.method == 'POST': cart_items = cart_module.get_cart_items(request) cart_subtotal = cart_module.cart_subtotal(request) return render(request, 'account/checkout.html', {'cart_items':cart_items, 'cart_id':cart_items[0].cart_id, 'cart_subtotal':cart_subtotal, 'user':request.user} ) else: return HttpResponseRedirect('/account/')
def show_cart(request): if request.method == 'POST': postdata = request.POST.copy() if postdata['submit'] == 'Remove': cart.remove_from_cart(request) if postdata['submit'] == 'Update': cart.update_cart(request) cart_items = cart.get_cart_items(request) cart_subtotal = cart.cart_subtotal(request) return render(request, "cart/cart.html", locals())
def show_cart(request, template_name="cart/cart.html"): if request.method == 'POST': postdata = request.POST.copy() if postdata['submit'] == 'Remove': cart.remove_from_cart(request) if postdata['submit'] == 'Update': cart.update_cart(request) cart_items = cart.get_cart_items(request) page_title = 'Shopping Cart' cart_subtotal = cart.cart_subtotal(request) return render(request, template_name, locals())
def del_item(request, template_name="catalog/subcategory.html"): cart.remove_from_cart(request) cart_item_count = cart.cart_distinct_item_count(request) cart_subtotal = cart.cart_subtotal(request) result = { 'cart_item_count': cart_item_count, 'cart_subtotal': str(cart_subtotal) } print(result) return HttpResponse(json.dumps(result), content_type='application/javascript; charset=utf-8')
def show_cart(request, template_name='cart/cart.html'): if request.method == 'POST': postdata = request.POST.copy() if postdata['submit'] == 'Remove': cart.remove_from_cart(request) if postdata['submit'] == 'Update': cart.update_cart(request) cart_items = cart.get_cart_items(request) page_title = "Shopping cart" cart_subtotal = cart.cart_subtotal(request) return render_to_response(template_name, locals(), context_instance=RequestContext(request))
def lipa_na_mpesa_online(request): postdata = request.POST.copy() phone = postdata['phone'] if phone[0] == "0": phone = phone.replace('0', '254', 1) elif phone[0:4] == "+254": phone = phone.replace('+254', '254', 1) access_token = validated_mpesa_access_token() print(access_token) print("lipalipa") api_url = MpesaC2bCredential.MPESA_URL headers = { "Authorization": "Bearer %s" % access_token, 'Content-Type': 'application/json' } conn = http.client.HTTPSConnection("proxy.server", 3128) conn.set_tunnel(api_url) requestbody = "{\r\n " \ "\"BusinessShortCode\": " + str(LipanaMpesaPpassword.Business_short_code) + ",\r\n " \ "\"Password\": \"" + str(LipanaMpesaPpassword.decode_password) + "\",\r\n " \ "\"Timestamp\": \"" + str(LipanaMpesaPpassword.lipa_time) + "\",\r\n " \ "\"TransactionType\": \"CustomerPayBillOnline\",\r\n " \ "\"Amount\": " + str(cart.cart_subtotal(request)) + ",\r\n " \ "\"PartyA\": " + str(phone) + ",\r\n " \ "\"PartyB\": " + str(LipanaMpesaPpassword.Business_short_code) + ",\r\n " \ "\"PhoneNumber\": " + str(phone) + ",\r\n " \ "\"CallBackURL\": \"https://ezi.pythonanywhere.com/api/v1/c2b/callback/\",\r\n " \ "\"AccountReference\": \"SAMIAN LTD\",\r\n " \ "\"TransactionDesc\": \"Test\"\r\n " \ "}" conn.request("POST", MpesaC2bCredential.stk_uri, requestbody, headers) response = conn.getresponse() response_data = response.read() print(requestbody) print(response_data.decode('utf-8')) data = response_data.decode('utf-8') values = json.loads(data) if 'ResponseCode' in values: MerchantRequestID = values['MerchantRequestID'] CheckoutRequestID = values['CheckoutRequestID'] ResponseCode = values['ResponseCode'] ResponseDescription = values['ResponseDescription'] CustomerMessage = values['CustomerMessage'] if ResponseCode == "0": CART_ID_SESSION_KEY = cart.CART_ID_SESSION_KEY pending = PendingMpesa() pending.phone = phone pending.checkoutid = CheckoutRequestID pending.cart = request.session[CART_ID_SESSION_KEY] pending.save() message = query_lipa(request, CheckoutRequestID) if 'errorMessage' in values: message = 23 return message
def pesapal(request): total_cost = cart.cart_subtotal(request) client = pesapal.PesaPal('uvzyNdMvjn6Ir4id+zwcUNT7bKOsp+wY','fXFK6owbt2B00Yq6JscpvKmDm6o=',True) request_data = { 'Amount': str(total_cost), 'Description': 'Purchase of Software from Aimsoft', 'Type': 'MERCHANT', 'Reference': str(datetime.datetime.now()), 'Email': '*****@*****.**' } post_params = { 'oauth_callback': '127.0.0.1:8000/checkout/process-order' } pesapal_request = client.postDirectOrder(post_params, request_data) return pesapal_request
def cart_box(request): paid = '' subtotal = cart.cart_subtotal(request) cart_items = cart.get_cart_items(request) cart_item_count = cart.cart_distinct_item_count(request) # Put this in here so that it cuts across all pages and it is related to cart. See function def for comments if bgprocess(request) == 0: paid = "(Paid)" return { 'cart_item_count': cart_item_count, 'paid': paid, 'cart_items': cart_items, 'subtotal': subtotal }
def show_cart(request, template_name="shop/cart/cart.html"): if request.method == 'POST': postdata = request.POST.copy() if postdata['submit'] == 'Remove': cart.remove_from_cart(request) if postdata['submit'] == 'Update': cart.update_cart(request) if postdata['submit'] == 'Checkout': checkout_url = checkout.get_checkout_url(request) return HttpResponseRedirect(checkout_url) cart_items = cart.get_cart_items(request) page_title = 'Shopping Cart' cart_subtotal = cart.cart_subtotal(request) merchant_id = settings.GOOGLE_CHECKOUT_MERCHANT_ID return render(request, template_name, locals())
def payment(request): """ """ order_number = request.session.get('order_number','') order = Order.objects.get(id = order_number) order1 = Order.objects.filter(id = order_number)[0] firstName = order.delivery_name email = order.email phoneNumber = order.phone order_items = OrderItem.objects.filter(order = order1) total_cost = cart.cart_subtotal(request) client = pesapal.PesaPal('mLrA2/J+vN3/BuB7+UNRM8CWO1ed3hh8','FT5//bhEvq5VejY0b4aeouB3jB0=',True) request_data = \ { 'Amount': str(total_cost), 'Description': 'Purchase of Software from Aimsoft', 'Type': 'MERCHANT', 'Reference': str(datetime.datetime.now()), 'Email': email, 'FirstName':firstName, 'PhoneNumber':phoneNumber, 'LineItems': [ { 'UniqueId': '', 'Particulars': '', 'Quantity': '', 'UnitCost': '', 'SubTotal': '' } ] } post_params = { 'oauth_callback': 'http://192.168.1.193:8080/checkout/process-order/' } pesapal_request = client.postDirectOrder(post_params, request_data) return render_to_response('checkout/checkout1.html', { 'total_cost': total_cost, 'iframe_url': pesapal_request.to_url() }, context_instance=RequestContext(request))
def show_cart(request, template_name="cart/cart.html"): if request.method == 'POST': post_data = request.POST.copy() if post_data['submit'] == 'Remove': cart.remove_from_cart(request) if post_data['submit'] == 'Update': cart.update_cart(request) if post_data['submit'] == 'Checkout': url = urlresolvers.reverse('show_checkout') return HttpResponseRedirect(url) cart_items = cart.get_cart_items(request) cart_item_count = cart.cart_distinct_item_count(request) cart_subtotal = cart.cart_subtotal(request) page_title = 'Shopping Cart' return render_to_response(template_name, locals(), context_instance=RequestContext(request))
def checkout(request, template_name=""): currency_symbol = request.session.get('currency_symbol','$'); currency_rate = request.session.get('currency_rate',1); cart_items = cart.get_cart_items(request) # sql="SELECT products.name, products.price FROM cart_items, products where cart_items.product_id = products.id" # cart_items=connection.cursor() # cart_items.execute(sql) for c_item in cart_items: print(c_item) c_item.price = math.floor(c_item.price()/decimal.Decimal(currency_rate)*100)/100 c_item.total = math.floor(c_item.total()/decimal.Decimal(currency_rate)*100)/100 cart_subtotal = cart.cart_subtotal(request) flat_price = math.floor(3.06/currency_rate*100)/100 total_price = math.floor((cart_subtotal+flat_price)*100)/100 mode = 'checkout' return render_to_response(template_name,locals(),context_instance=RequestContext(request))
def pay(request): """ Do the "create order" thing. It get the CARD_ID_SESSION_KEY from session to get the items information that been added into cart by user. Then calling the cart_subtotal() function in cart_module to get the order total price. The shipping information will also be collected through html form. If every thing is fine, then create an order, else return error message. :param request: :return: """ if request.method == 'POST': if request.session[CART_ID_SESSION_KEY] != '': cart_items = cart_module.get_cart_items(request) cart_subtotal = cart_module.cart_subtotal(request) shipping_zip = request.POST['shipping_zip'] shipping_add = request.POST['shipping_add'] shipping_to = request.POST['shipping_to'] username = request.user.username cart_id = cart_items[0].cart_id try: order = Order.objects.get(cart_id = request.session[CART_ID_SESSION_KEY]) except Order.DoesNotExist: order = None if order != None: order = Order.objects.get(cart_id=request.session[CART_ID_SESSION_KEY]) else: order = Order() order.cart_id = cart_id order.shipping_add = shipping_add order.shipping_to = shipping_to order.shipping_zip = shipping_zip order.username = username order.total_price = cart_subtotal order.save() request.session[CART_ID_SESSION_KEY] = '' # delete session key return HttpResponseRedirect('/account/order/'+order.order_id+'/') else: return render(request, 'account/error.html',{'error':'This order has been created.' }) else: return HttpResponseRedirect('/account/')
def process(request): """ Takes a POST request containing valid order data; pings the payment gateway with the billing information and returns a Python dictionary with two entries: 'order_number' and 'message' based on the success of the payment processing. An unsuccessful billing will have an order_number of 0 and an error message, and a successful billing with have an order number and an empty string message. """ # Transaction results _APPROVED = '1' _DECLINED = '2' _ERROR = '3' _HELD_FOR_REVIEW = '4' postdata = request.POST.copy() card_num = postdata.get('credit_card_number', '') exp_month = postdata.get('credit_card_expire_month', '') exp_year = postdata.get('credit_card_expire_year', '') exp_date = exp_month + exp_year cvv = postdata.get('credit_card_cvv', '') amount = cart.cart_subtotal(request) results = {} response = authnet.do_auth_capture( amount=amount, card_num=card_num, exp_date=exp_date, card_cvv=cvv, ) if response[0] == _APPROVED: transaction_id = response[6] order = create_order(request, transaction_id) results = {'order_number': order.id, 'message': ''} if response[0] == _DECLINED: results = { 'order_number': 0, 'message': 'There is a problem with your Credit Card.' } if response[0] == _ERROR or response[0] == _HELD_FOR_REVIEW: results = { 'order_number': 0, 'message': 'Error processing your order.' } return results
def show_cart(request, template_name="cart.html"): """ view function for the page displaying the customer shopping cart, and allows for the updating of quantities and removal product instances """ if request.method == 'POST': postdata = request.POST.copy() if postdata['submit'] == 'Remove': cart.remove_from_cart(request) if postdata['submit'] == 'Update': cart.update_cart(request) ## if postdata['submit'] == 'Checkout': ## checkout_url = checkout.get_checkout_url(request) ## return HttpResponseRedirect(checkout_url) cart_items = cart.get_cart_items(request) page_title = 'Shopping Cart' cart_subtotal = cart.cart_subtotal(request) return render_to_response(template_name, locals())
def show_cart(request, template_name="cart/cart.html"): request.session.set_test_cookie() next1 = '' recent_views = stats.recommended_from_views(request) if request.method == 'POST': print(request.session['cart_id']) postdata = request.POST.copy() if postdata['submit'] == 'Remove': if pending_checker(request) == 0: url = reverse('show_checkout', args=['Lipa']) return HttpResponseRedirect(url) cart.remove_from_cart(request) next1 = request.GET.get('next', '') if len(next1) > 0: url = reverse('show_checkout', args=[next1]) return HttpResponseRedirect(url) if postdata['submit'] == 'Update': if pending_checker(request) == 0: url = reverse('show_checkout', args=['Lipa']) return HttpResponseRedirect(url) try: int(postdata['quantity']) cart.update_cart(request) next1 = request.GET.get('next', '') if len(next1) > 0: url = reverse('show_checkout', args=[next1]) return HttpResponseRedirect(url) except: if cart.cart_distinct_item_count(request) > 0: qerror = 'Invalid Quantity Value' if postdata['submit'] == 'Card Checkout': checkout_url = checkout.get_checkout_url(request) return HttpResponseRedirect(checkout_url) if postdata['submit'] == 'Mpesa Checkout': checkout_url = checkout.get_checkout_url(request) return HttpResponseRedirect(checkout_url) if len(next1) > 0: url = reverse('show_checkout', args=[next1]) return HttpResponseRedirect(url) cart_items = cart.get_cart_items(request) page_title = 'Shopping Cart' cart_subtotal = cart.cart_subtotal(request) return render(request, template_name, locals(), RequestContext(request))
def cart_box(request): currency_symbol = request.session.get('currency_symbol', '$') currency_rate = request.session.get('currency_rate', 1) cart_item_count = cart.cart_distinct_item_count(request) # return {'cart_item_count' : cart_item_count } cart_items = cart.get_cart_items(request) print('++++++++++++++++++++++++') for c_item in cart_items: c_item.price = math.floor( c_item.price() / decimal.Decimal(currency_rate) * 100) / 100 cart_subtotal = cart.cart_subtotal(request) print(cart_subtotal) return { 'cart_items': cart_items, 'cart_item_count': cart_item_count, 'cart_subtotal': cart_subtotal, 'currency_symbol': currency_symbol }
def show_cart(request, template_name="cart/cart.html"): if request.method == 'POST': postdata = request.POST.copy() if postdata['submit'] == 'Remove': cart.remove_from_cart(request) if postdata['submit'] == 'Update': try: int(postdata['quantity']) cart.update_cart(request) except: if cart.cart_distinct_item_count(request) > 0: qerror = 'Invalid Quantity Value' if postdata['submit'] == 'Card Checkout': checkout_url = checkout.get_checkout_url(request) return HttpResponseRedirect(checkout_url) if postdata['submit'] == 'Mpesa Checkout': checkout_url = checkout.get_checkout_url(request) return HttpResponseRedirect(checkout_url) cart_items = cart.get_cart_items(request) page_title = 'Shopping Cart' cart_subtotal = cart.cart_subtotal(request) return render(request, template_name, locals(), RequestContext(request))
def show_checkout(request): error_message = '' if cart.is_empty(request): cart_url = reverse('show_cart') return HttpResponseRedirect(cart_url) if request.method == 'POST': postdata = request.POST.copy() form = CheckoutForm(postdata) order_number = request.session.get('order_number', '') if form.is_valid(): response = checkout.process(request) order_number = response.get('order_number', 0) error_message = response.get('message', '') if order_number: request.session['order_number'] = order_number receipt_url = reverse('checkout_receipt') return HttpResponseRedirect(receipt_url) else: error_message = 'Correct the errors below' else: if request.user.is_authenticated: user_profile = profile.retrieve(request) form = CheckoutForm(instance=user_profile) else: form = CheckoutForm() page_title = 'Checkout' total = cart.cart_subtotal(request) template = 'checkout/checkout.html' context = { 'page_title': page_title, 'error_message': error_message, 'form': form, 'total': total, } return render(request, template, context)
def process(request): """ takes a POST request containing valid order data; pings the payment gateway with the billing information and returns a Python dictionary with two entries: 'order_number' and 'message' based on the success of the payment processing. An unsuccessful billing will have an order_number of 0 and an error message, and a successful billing with have an order number and an empty string message. """ # Transaction results APPROVED = '1' DECLINED = '2' ERROR = '3' HELD_FOR_REVIEW = '4' postdata = request.POST.copy() card_num = postdata.get('credit_card_number','') exp_month = postdata.get('credit_card_expire_month','') exp_year = postdata.get('credit_card_expire_year','') exp_date = exp_month + exp_year cvv = postdata.get('credit_card_cvv','') amount = cart.cart_subtotal(request) results = {} response = authnet.do_auth_capture(amount=amount, card_num=card_num, exp_date=exp_date, card_cvv=cvv) if response[0] == APPROVED: transaction_id = response[6] order = create_order(request, transaction_id) results = {'order_number': order.id, 'message': u''} if response[0] == DECLINED: results = {'order_number': 0, 'message': u'There is a problem with your credit card.'} if response[0] == ERROR or response[0] == HELD_FOR_REVIEW: results = {'order_number': 0, 'message': u'Error processing your order.'} return results
from django.shortcuts import render from django.template import RequestContext from cart import cart if request.method == 'POST': postdata = request.POST.copy() if postdata['submit'] == 'Remove': cart.remove_from_cart(request) if postdata['submit'] == 'Update': cart.update_cart(request) if postdata['submit'] == 'Checkout': checkout_url = checkout.get_checkout_url(request) return HttpResponseRedirect(checkout_url) cart_items = cart.get_cart_items(request) page_title = 'Shopping Cart' cart_subtotal = cart.cart_subtotal(request)
def cart_box(request): cart_subtotal=cart.cart_subtotal(request) cart_item_count = cart.cart_distinct_item_count(request) return locals()
def _build_xml_shopping_cart(request): doc = Document() if request.POST: postdata = request.POST.copy() card_num = postdata.get('credit_card_number', '') exp_month = postdata.get('credit_card_expire_month', '') exp_year = postdata.get('credit_card_expire_year', '') exp_date = exp_year + '-' + exp_month cvv = postdata.get('credit_card_cvv', '') emailaddr = postdata.get('email', '') # billing info bname = postdata.get('billing_name', '') fullname = bname.split(' ') fname = fullname[0] if len(fullname) > 1: lname = fullname[len(fullname) - 1] bcity = postdata.get('shipping_city', '') bstate = postdata.get('shipping_state', '') bzip = postdata.get('shipping_zip', '') bcountry = postdata.get('shipping_country', '') baddress1 = postdata.get('billing_address_1', '') baddress2 = postdata.get('billing_address_2', '') baddress = str(baddress1) + ' ' + str(baddress2) # shipping info sname = postdata.get('shipping_name', '') sfullname = sname.split(' ') sfname = sfullname[0] if len(sfullname) > 1: slname = sfullname[len(sfullname) - 1] scity = postdata.get('billing_city', '') sstate = postdata.get('billing_state', '') szip = postdata.get('billing_zip', '') scountry = postdata.get('billing_country', '') saddress1 = postdata.get('billing_address_1', '') saddress2 = postdata.get('billing_address_2', '') saddress = str(saddress1) + ' ' + str(saddress2) root = doc.createElement('createTransactionRequest') root.setAttribute('xmlns', 'AnetApi/xml/v1/schema/AnetApiSchema.xsd') doc.appendChild(root) merchantauthentication = doc.createElement('merchantAuthentication') root.appendChild(merchantauthentication) name = doc.createElement('name') name_text = doc.createTextNode(str(settings.AUTHNET_LOGIN)) name.appendChild(name_text) merchantauthentication.appendChild(name) transactionkey = doc.createElement('transactionKey') transactionkey_text = doc.createTextNode(str(settings.AUTHNET_KEY)) transactionkey.appendChild(transactionkey_text) merchantauthentication.appendChild(transactionkey) transactionrequest = doc.createElement('transactionRequest') root.appendChild(transactionrequest) transactiontype = doc.createElement('transactionType') transactiontype_text = doc.createTextNode(str(settings.AUTHNET_TTYPE)) transactiontype.appendChild(transactiontype_text) transactionrequest.appendChild(transactiontype) amount = doc.createElement('amount') amount_text = doc.createTextNode(str(cart.cart_subtotal(request) / USD)) amount.appendChild(amount_text) transactionrequest.appendChild(amount) payment = doc.createElement('payment') transactionrequest.appendChild(payment) creditcard = doc.createElement('creditCard') payment.appendChild(creditcard) cardnumber = doc.createElement('cardNumber') cardnumber_text = doc.createTextNode(str(card_num)) cardnumber.appendChild(cardnumber_text) creditcard.appendChild(cardnumber) expirationdate = doc.createElement('expirationDate') expirationdate_text = doc.createTextNode(str(exp_date)) expirationdate.appendChild(expirationdate_text) creditcard.appendChild(expirationdate) cardcode = doc.createElement('cardCode') cardcode_text = doc.createTextNode(cvv) cardcode.appendChild(cardcode_text) creditcard.appendChild(cardcode) order = doc.createElement('order') transactionrequest.appendChild(order) invoicenumber = doc.createElement('invoiceNumber') invoicenumber_text = doc.createTextNode(str(InvNo)) invoicenumber.appendChild(invoicenumber_text) order.appendChild(invoicenumber) description = doc.createElement('description') description_text = doc.createTextNode('Modern Musician Invoice') description.appendChild(description_text) order.appendChild(description) lineitems = doc.createElement('lineItems') transactionrequest.appendChild(lineitems) cart_items = cart.get_cart_items(request) for cart_item in cart_items: lineitem = doc.createElement('lineItem') lineitems.appendChild(lineitem) itemid = doc.createElement('itemId') itemid_text = doc.createTextNode(str(cart_item.product.id)) itemid.appendChild(itemid_text) lineitem.appendChild(itemid) name = doc.createElement('name') name_text = doc.createTextNode(str(cart_item.name)) name.appendChild(name_text) lineitem.appendChild(name) description = doc.createElement('description') description_text = doc.createTextNode(str(cart_item.description)) description.appendChild(description_text) lineitem.appendChild(description) quantity = doc.createElement('quantity') quantity_text = doc.createTextNode(str(cart_item.quantity)) quantity.appendChild(quantity_text) lineitem.appendChild(quantity) price = doc.createElement('unitPrice') price_text = doc.createTextNode(str(cart_item.price / USD)) price.appendChild(price_text) lineitem.appendChild(price) customer = doc.createElement('customer') transactionrequest.appendChild(customer) id = doc.createElement('id') id_text = doc.createTextNode(str(request.user.id)) id.appendChild(id_text) customer.appendChild(id) email = doc.createElement('email') email_text = doc.createTextNode(str(emailaddr)) email.appendChild(email_text) customer.appendChild(email) billto = doc.createElement('billTo') transactionrequest.appendChild(billto) firstname = doc.createElement('firstName') firstname_text = doc.createTextNode(str(fname)) firstname.appendChild(firstname_text) billto.appendChild(firstname) lastname = doc.createElement('lastName') lastnmae_text = doc.createTextNode(str(lname)) lastname.appendChild(lastnmae_text) billto.appendChild(lastname) address = doc.createElement('address') address_text = doc.createTextNode(baddress) address.appendChild(address_text) billto.appendChild(address) city = doc.createElement('city') city_text = doc.createTextNode(str(bcity)) city.appendChild(city_text) billto.appendChild(city) state = doc.createElement('state') state_text = doc.createTextNode(str(bstate)) state.appendChild(state_text) billto.appendChild(state) zip = doc.createElement('zip') zip_text = doc.createTextNode(str(bzip)) zip.appendChild(zip_text) billto.appendChild(zip) country = doc.createElement('country') country_text = doc.createTextNode(str(bcountry)) country.appendChild(country_text) billto.appendChild(country) shipto = doc.createElement('shipTo') transactionrequest.appendChild(shipto) firstname = doc.createElement('firstName') firstname_text = doc.createTextNode(str(sfname)) firstname.appendChild(firstname_text) shipto.appendChild(firstname) lastname = doc.createElement('lastName') lastnmae_text = doc.createTextNode(str(slname)) lastname.appendChild(lastnmae_text) shipto.appendChild(lastname) address = doc.createElement('address') address_text = doc.createTextNode(saddress) address.appendChild(address_text) shipto.appendChild(address) city = doc.createElement('city') city_text = doc.createTextNode(str(scity)) city.appendChild(city_text) shipto.appendChild(city) state = doc.createElement('state') state_text = doc.createTextNode(str(sstate)) state.appendChild(state_text) shipto.appendChild(state) zip = doc.createElement('zip') zip_text = doc.createTextNode(str(szip)) zip.appendChild(zip_text) shipto.appendChild(zip) country = doc.createElement('country') country_text = doc.createTextNode(str(scountry)) country.appendChild(country_text) shipto.appendChild(country) return doc.toxml(encoding='utf-8')
def getOrder(request, type): categories = Category.objects.filter(is_active=True) brands = Brand.objects.filter(is_active=True) if request.method == 'POST': postdata = request.POST.copy() try: address = postdata.get('address') except: address = ' ' name = postdata.get('namefield') phone = postdata.get('phone') delivery = postdata.get('delivery') payment = postdata.get('payment') # post form sends a string value if delivery == 'True': delivery = True else: delivery = False if payment == 'True': payment = True else: payment = False p = 0 if int(type) == 0: total = cart.cart_subtotal(request) else: p = Product.objects.get(id=type) p.quantity -= 1 p.save() total = p.price newOrder = Order(name=name, phone=phone, address=address, total=total, is_card_payment=payment, is_delivery=delivery) newOrder.save() if int(type) == 0: oCart = cart.get_cart_items(request) for ci in oCart: oi = OrderItem(product=ci.product, order=newOrder, quantity=ci.quantity) oi.save() ci.product.quantity -= ci.quantity ci.product.save() cart.empty_cart(request) else: oi = OrderItem(product=p, order=newOrder, quantity=1) oi.save() context = { 'id': newOrder.id, 'opened': newOrder.opened_at, 'success': True, 'cart_distinct': 0, 'categories': categories, 'brands': brands, } else: cart_distinct = cart.cart_distinct_item_count(request) context = { 'success': False, 'cart_distinct': cart_distinct, 'categories': categories, 'brands': brands, } return HttpResponse(render_to_response('checkout-success.html', context, context_instance=RequestContext(request)))
def cart_items(request): cart_items_ = cart.get_cart_items(request) cart_subtotal = cart.cart_subtotal(request) return {'cart_items_': cart_items_, 'request': request, 'cart_subtotal': cart_subtotal}
def show_checkout(request, checkout_type, template_name="checkout/checkout.html"): # print(request.POST.copy()) # request1 = locals() # print(request1) print('ian') print(request.method) error_message = '' if cart.is_empty(request): cart_url = reverse('show_cart') return HttpResponseRedirect(cart_url) if request.method == 'POST' and request.POST.copy()['payment'] == "Mpesa Payment" or request.method == 'POST' and\ request.POST.copy()['phone2'] != '' and request.POST.copy()['credit_card_number'] == '' and\ request.POST.copy()['credit_card_cvv'] == '': postdata = request.POST.copy() postdata['billing_name'] = postdata['shipping_name'] postdata['billing_address_1'] = postdata['shipping_address_1'] postdata['billing_address_2'] = postdata['shipping_address_2'] postdata['billing_city'] = postdata['shipping_city'] postdata['billing_zip'] = postdata['shipping_zip'] postdata['billing_country'] = postdata['shipping_country'] postdata['payment'] = postdata['payment'] form = CheckoutForm(postdata) if form.is_valid(): response = mpesa_processor.process(request) order_number = response.get('order_number', 0) error_message = response.get('message', '') if order_number: request.session['order_number'] = order_number receipt_url = reverse('checkout_receipt') CART_ID_SESSION_KEY = cart.CART_ID_SESSION_KEY pending = PendingMpesa.objects.filter( cart=request.session[CART_ID_SESSION_KEY]) if pending.count() == 1: pending.delete() return HttpResponseRedirect(receipt_url) else: error_message = "Correct the errors below" if request.method == 'POST' and request.POST.copy()['payment'] == "Place Order" or request.method == 'POST' and\ request.POST.copy()['credit_card_number'] != '' and request.POST.copy()['credit_card_cvv'] != '' and\ request.POST.copy()['phone2'] == '': postdata = request.POST.copy() if 'billing' in request.POST.copy(): if postdata['billing_name'] == '': error_message = 'Input billing name' if postdata['billing_address_1'] == '': error_message = 'Input billing address' if postdata['billing_city'] == '': error_message = 'Input billing city' if postdata['billing_zip'] == '': error_message = 'Input billing zip/postal code' if postdata['billing_country'] == '': error_message = 'Input billing country' if not 'billing' in request.POST.copy(): postdata['billing_name'] = postdata['shipping_name'] postdata['billing_address_1'] = postdata['shipping_address_1'] postdata['billing_address_2'] = postdata['shipping_address_2'] postdata['billing_city'] = postdata['shipping_city'] postdata['billing_zip'] = postdata['shipping_zip'] postdata['billing_country'] = postdata['shipping_country'] form = CheckoutForm(postdata) # print(postdata) # print(form) # print("frm") if form.is_valid(): response = checkout.process(request) order_number = response.get('order_number', 0) error_message = response.get('message', '') if order_number: request.session['order_number'] = order_number receipt_url = reverse('checkout_receipt') return HttpResponseRedirect(receipt_url) else: error_message = 'Correct the errors below' else: if request.user.is_authenticated: user_profile = profile.retrieve(request) form = CheckoutForm(instance=user_profile) else: form = CheckoutForm() """if request.method == 'GET' and checkout_type != 'Lipa' and checkout_type != 'PendingLipa': form = CheckoutForm(instance=user_profile) if request.method == 'POST' and checkout_type == "Lipa": postdata = request.POST.copy() form = MpesaCheckoutForm(postdata) if request.GET and checkout_type == "Lipa": form = MpesaCheckoutForm(instance=user_profile) if request.GET and checkout_type == "PendingLipa": form = MpesaCheckoutForm(instance=user_profile)""" if request.method == 'POST' and checkout_type == "Lipa": postdata = request.POST.copy() # print(postdata) form = CheckoutForm(postdata) # print(request.POST.copy()['payment']) if request.POST.copy()['payment'] == 'on' and postdata['phone2'] == '' and postdata['credit_card_number']\ == '' and postdata['credit_card_cvv'] == '': empty1 = 'Please select payment method' error_message = 'Correct the errors below' if request.POST.copy()['payment'] == 'on' and postdata['phone2'] != '' and postdata['credit_card_number']\ != '' or postdata['credit_card_cvv'] != '': empty1 = 'Please select payment method' error_message = 'Correct the errors below' if request.GET and checkout_type == "Lipa": form = CheckoutForm() """if request.method == 'POST' and checkout_type == "Lipa": postdata = request.POST.copy() form = MpesaCheckoutForm(postdata) if request.GET and checkout_type == "Lipa": form = MpesaCheckoutForm() if request.GET and checkout_type == "PendingLipa": form = MpesaCheckoutForm()""" page_title = 'Checkout' cart_items = cart.get_cart_items(request) cart_subtotal = cart.cart_subtotal(request) checkout_type = checkout_type return render(request, template_name, locals(), RequestContext(request))