def confirm_info(request): # Check that items are in stock cart = Cart.objects.from_request(request) if cart.not_enough_stock(): return HttpResponseRedirect(urlresolvers.reverse("satchmo_cart")) payment_module = config_get_group('PAYMENT_GOOGLE') if not 'orderID' in request.session: url = lookup_url(payment_module, 'satchmo_checkout-step1') return http.HttpResponseRedirect(url) tempCart = Cart.objects.from_request(request) if tempCart.numItems == 0: template = lookup_template(payment_module, 'checkout/empty_cart.html') return render_to_response(template, RequestContext(request)) try: order = Order.objects.from_request(request) except Order.DoesNotExist: order = None if not (order and order.validate(request)): context = RequestContext( request, {'message': _('Your order is no longer valid.')}) return render_to_response('shop_404.html', context) live = payment_live(payment_module) gcart = GoogleCart(order, payment_module, live) log.debug("CART:\n%s", gcart.cart_xml) template = lookup_template(payment_module, 'checkout/google/confirm.html') if live: merchant_id = payment_module.MERCHANT_ID.value url_template = payment_module.POST_URL.value else: merchant_id = payment_module.MERCHANT_TEST_ID.value url_template = payment_module.POST_TEST_URL.value post_url = url_template % {'MERCHANT_ID': merchant_id} default_view_tax = config_value('TAX', 'DEFAULT_VIEW_TAX') ctx = RequestContext( request, { 'order': order, 'post_url': post_url, 'default_view_tax': default_view_tax, 'google_cart': gcart.encoded_cart(), 'google_signature': gcart.encoded_signature(), 'PAYMENT_LIVE': live }) return render_to_response(template, ctx)
def confirm_info(request): # Check that items are in stock cart = Cart.objects.from_request(request) if cart.not_enough_stock(): return HttpResponseRedirect(urlresolvers.reverse("satchmo_cart")) payment_module = config_get_group('PAYMENT_GOOGLE') if not 'orderID' in request.session: url = lookup_url(payment_module, 'satchmo_checkout-step1') return http.HttpResponseRedirect(url) tempCart = Cart.objects.from_request(request) if tempCart.numItems == 0: template = lookup_template(payment_module, 'checkout/empty_cart.html') return render_to_response(template, RequestContext(request)) try: order = Order.objects.from_request(request) except Order.DoesNotExist: order = None if not (order and order.validate(request)): context = RequestContext(request, {'message': _('Your order is no longer valid.')}) return render_to_response('shop_404.html', context) live = payment_live(payment_module) gcart = GoogleCart(order, payment_module, live) log.debug("CART:\n%s", gcart.cart_xml) template = lookup_template(payment_module, 'checkout/google/confirm.html') if live: merchant_id = payment_module.MERCHANT_ID.value url_template = payment_module.POST_URL.value else: merchant_id = payment_module.MERCHANT_TEST_ID.value url_template = payment_module.POST_TEST_URL.value post_url = url_template % {'MERCHANT_ID' : merchant_id} default_view_tax = config_value('TAX', 'DEFAULT_VIEW_TAX') ctx = RequestContext(request, { 'order': order, 'post_url': post_url, 'default_view_tax': default_view_tax, 'google_cart' : gcart.encoded_cart(), 'google_signature' : gcart.encoded_signature(), 'PAYMENT_LIVE' : live }) return render_to_response(template, ctx)
def one_step(request): payment_module = config_get_group('PAYMENT_AUTOSUCCESS') #First verify that the customer exists try: contact = Contact.objects.from_request(request, create=False) except Contact.DoesNotExist: url = lookup_url(payment_module, 'satchmo_checkout-step1') return HttpResponseRedirect(url) #Verify we still have items in the cart tempCart = Cart.objects.from_request(request) if tempCart.numItems == 0: template = lookup_template(payment_module, 'checkout/empty_cart.html') return render_to_response(template, RequestContext(request)) # Create a new order newOrder = Order(contact=contact) pay_ship_save(newOrder, tempCart, contact, shipping="", discount="") request.session['orderID'] = newOrder.id newOrder.add_status(status='Pending', notes = "Order successfully submitted") record_payment(newOrder, payment_module, amount=newOrder.balance) tempCart.empty() success = lookup_url(payment_module, 'satchmo_checkout-success') return HttpResponseRedirect(success)
def one_step(request): # Check that items are in stock cart = Cart.objects.from_request(request) if cart.not_enough_stock(): return HttpResponseRedirect(reverse("satchmo_cart")) payment_module = config_get_group("PAYMENT_AUTOSUCCESS") # First verify that the customer exists try: contact = Contact.objects.from_request(request, create=False) except Contact.DoesNotExist: url = lookup_url(payment_module, "satchmo_checkout-step1") return HttpResponseRedirect(url) # Verify we still have items in the cart if cart.numItems == 0: template = lookup_template(payment_module, "checkout/empty_cart.html") return render(request, template) # Create a new order newOrder = Order(contact=contact) pay_ship_save(newOrder, cart, contact, shipping="", discount="") request.session["orderID"] = newOrder.id newOrder.add_status(status="Pending", notes="Order successfully submitted") record_payment(newOrder, payment_module, amount=newOrder.balance) success = lookup_url(payment_module, "satchmo_checkout-success") return HttpResponseRedirect(success)
def _get_shipping_choices(request, paymentmodule, cart, contact, default_view_tax=False): """Iterate through legal shipping modules, building the list for display to the user. Returns the shipping choices list, along with a dictionary of shipping choices, useful for building javascript that operates on shipping choices. """ shipping_options = [] shipping_dict = {} if not cart.is_shippable: methods = [ shipping_method_by_key('NoShipping'), ] else: methods = shipping_methods() valid_methods = [] for method in methods: method.calculate(cart, contact) if method.valid(): valid_methods.append((method, method.cost())) # sort methods by cost valid_methods.sort(key=lambda method_cost: int(method_cost[1])) for method, shipcost in valid_methods: template = lookup_template(paymentmodule, 'shipping_options.html') t = loader.get_template(template) shipping_tax = None taxed_shipping_price = None if config_value('TAX', 'TAX_SHIPPING'): shipping_tax = config_value('TAX', 'TAX_CLASS') taxer = _get_taxprocessor(request) total = shipcost + taxer.by_price(shipping_tax, shipcost) taxed_shipping_price = money_format(total) data = { 'amount': shipcost, 'description': method.description(), 'method': method.method(), 'expected_delivery': method.expectedDelivery(), 'default_view_tax': default_view_tax, 'shipping_tax': shipping_tax, 'taxed_shipping_price': taxed_shipping_price } if hasattr(method, 'shipping_discount'): data['discount'] = method.shipping_discount() c = RequestContext(request, data) shipping_options.append((method.id, t.render(c))) shipping_dict[method.id] = shipcost return shipping_options, shipping_dict
def _get_shipping_choices(request, paymentmodule, cart, contact, default_view_tax=False): """Iterate through legal shipping modules, building the list for display to the user. Returns the shipping choices list, along with a dictionary of shipping choices, useful for building javascript that operates on shipping choices. """ shipping_options = [] shipping_dict = {} if not cart.is_shippable: methods = [shipping_method_by_key("NoShipping")] else: methods = shipping_methods() valid_methods = [] for method in methods: method.calculate(cart, contact) if method.valid(): valid_methods.append((method, method.cost())) # sort methods by cost valid_methods.sort(key=lambda method_cost: int(method_cost[1])) for method, shipcost in valid_methods: template = lookup_template(paymentmodule, "shipping_options.html") t = loader.get_template(template) shipping_tax = None taxed_shipping_price = None if config_value("TAX", "TAX_SHIPPING"): shipping_tax = config_value("TAX", "TAX_CLASS") taxer = _get_taxprocessor(request) total = shipcost + taxer.by_price(shipping_tax, shipcost) currency_code = currency_for_request(request) taxed_shipping_price = money_format(total, currency_code) data = { "amount": shipcost, "description": method.description(), "method": method.method(), "expected_delivery": method.expectedDelivery(), "default_view_tax": default_view_tax, "shipping_tax": shipping_tax, "taxed_shipping_price": taxed_shipping_price, } if hasattr(method, "shipping_discount"): data["discount"] = method.shipping_discount() shipping_options.append((method.id, t.render(data))) shipping_dict[method.id] = shipcost return shipping_options, shipping_dict
def confirm_info(request): "Create form to send to Ingenico" # Check that items are in stock cart = Cart.objects.from_request(request) if cart.not_enough_stock(): return HttpResponseRedirect(reverse("satchmo_cart")) try: order = Order.objects.from_request(request) except Order.DoesNotExist: return HttpResponseRedirect(reverse("satchmo_shop_home")) if order.validate(request) is False: context = {"message": _("Your order is no longer valid.")} return render(request, "shop_404.html", context) data = { "PSPID": payment_module.PSPID.value, "ORDERID": order.id, # Amount * 100 # https://payment-services.ingenico.com/int/en/ogone/support/guides/integration%20guides/e-commerce#formparameters "AMOUNT": int(order.balance * 100), "CURRENCY": order.currency.iso_4217_code, "CN": order.bill_addressee, "EMAIL": order.contact.user.email, "OWNERADDRESS": ", ".join([order.bill_street1, order.bill_street2]), "OWNERZIP": order.bill_postal_code, "OWNERTOWN": ", ".join([order.bill_city, order.bill_state]), "OWNERCTY": order.bill_country.iso2_code, } if payment_module.ALIAS.value: data["ALIAS"] = hashlib.sha512( order.contact.user.username.encode("utf-8")).hexdigest()[:50] data["ALIASUSAGE"] = payment_module.ALIASUSAGE.value form = IngenicoForm(data) template = lookup_template(payment_module, "checkout/ingenico/confirm.html") live = payment_module.LIVE.value if live: post_url = payment_module.CONNECTION.value else: post_url = payment_module.CONNECTION_TEST.value ctx = { "form": form, "order": order, "post_url": post_url, "PAYMENT_LIVE": live } return render(request, template, ctx)
def confirm_info(request): "Create form to send to WorldPay" # Check that items are in stock cart = Cart.objects.from_request(request) if cart.not_enough_stock(): return HttpResponseRedirect(reverse("satchmo_cart")) try: order = Order.objects.from_request(request) except Order.DoesNotExist: order = None if not (order and order.validate(request)): context = {"message": _("Your order is no longer valid.")} return render(request, "shop_404.html", context) template = lookup_template(payment_module, "checkout/worldpay/confirm.html") live = payment_module.LIVE.value currency = order.currency.iso_4217_code inst_id = payment_module.INSTID.value default_view_tax = config_value("TAX", "DEFAULT_VIEW_TAX") if live: post_url = payment_module.CONNECTION.value else: post_url = payment_module.CONNECTION_TEST.value if payment_module.MD5.value > "": # Doing the MD5 Signature dance # Generating secret "secret;amount;currency;cartId" balance = trunc_decimal(order.balance, 2) signature = "%s:%s:%s:%s" % ( payment_module.MD5.value, balance, currency, order.id, ) MD5 = md5(signature).hexdigest() else: MD5 = False ctx = { "order": order, "inst_id": inst_id, "currency": currency, "post_url": post_url, "default_view_tax": default_view_tax, "PAYMENT_LIVE": live, "MD5": MD5, "session": request.session.session_key, } return render(request, template, ctx)
def _get_shipping_choices( request, paymentmodule, cart, contact, default_view_tax=False ): """Iterate through legal shipping modules, building the list for display to the user. Returns the shipping choices list, along with a dictionary of shipping choices, useful for building javascript that operates on shipping choices. """ shipping_options = [] shipping_dict = {} if not cart.is_shippable: methods = [shipping_method_by_key("NoShipping")] else: methods = shipping_methods() valid_methods = [] for method in methods: method.calculate(cart, contact) if method.valid(): valid_methods.append((method, method.cost())) # sort methods by cost valid_methods.sort(key=lambda method_cost: int(method_cost[1])) for method, shipcost in valid_methods: template = lookup_template(paymentmodule, "shipping_options.html") t = loader.get_template(template) shipping_tax = None taxed_shipping_price = None if config_value("TAX", "TAX_SHIPPING"): shipping_tax = config_value("TAX", "TAX_CLASS") taxer = _get_taxprocessor(request) total = shipcost + taxer.by_price(shipping_tax, shipcost) currency_code = currency_for_request(request) taxed_shipping_price = money_format(total, currency_code) data = { "amount": shipcost, "description": method.description(), "method": method.method(), "expected_delivery": method.expectedDelivery(), "default_view_tax": default_view_tax, "shipping_tax": shipping_tax, "taxed_shipping_price": taxed_shipping_price, } if hasattr(method, "shipping_discount"): data["discount"] = method.shipping_discount() shipping_options.append((method.id, t.render(data))) shipping_dict[method.id] = shipcost return shipping_options, shipping_dict
def pay_ship_render_form(request, form, template, payment_module, cart): template = lookup_template(payment_module, template) if cart.numItems > 0: products = [item.product for item in cart.cartitem_set.all()] sale = find_best_auto_discount(products) else: sale = None ctx = {"form": form, "sale": sale, "PAYMENT_LIVE": payment_live(payment_module)} return render(request, template, ctx)
def confirm_info(request): """Shows the user its order details and ask confirmation to send to the real payment function""" payment_module = config_get_group('PAYMENT_PAYPAL_EXPRESS') try: order = Order.objects.from_request(request) except Order.DoesNotExist: url = lookup_url(payment_module, 'satchmo_checkout-step1') return HttpResponseRedirect(url) tempCart = Cart.objects.from_request(request) if tempCart.numItems == 0: template = lookup_template(payment_module, 'checkout/empty_cart.html') return render_to_response(template, RequestContext(request)) # Check if the order is still valid if not order.validate(request): context = RequestContext(request, {'message': _('Your order is no longer valid.')}) return render_to_response('shop_404.html', context) template = lookup_template(payment_module, 'checkout/paypal_express/confirm.html') create_pending_payment(order, payment_module) default_view_tax = config_value('TAX', 'DEFAULT_VIEW_TAX') recurring = None order_items = order.orderitem_set.all() ctx = RequestContext(request, {'order': order, 'post_url': urlresolvers.reverse("PAYPAL_EXPRESS_satchmo_checkout-step4"), 'default_view_tax': default_view_tax, 'currency_code': payment_module.CURRENCY_CODE.value, 'invoice': order.id, }) return render_to_response(template, ctx)
def _get_shipping_choices(request, paymentmodule, cart, contact, default_view_tax=False): """Iterate through legal shipping modules, building the list for display to the user. Returns the shipping choices list, along with a dictionary of shipping choices, useful for building javascript that operates on shipping choices. """ shipping_options = [] shipping_dict = {} if not cart.is_shippable: methods = [shipping_method_by_key('NoShipping'), ] else: methods = shipping_methods() valid_methods = [] for method in methods: method.calculate(cart, contact) if method.valid(): valid_methods.append((method, method.cost())) # sort methods by cost valid_methods.sort(key=lambda method_cost: int(method_cost[1])) for method, shipcost in valid_methods: template = lookup_template(paymentmodule, 'shipping_options.html') t = loader.get_template(template) shipping_tax = None taxed_shipping_price = None if config_value('TAX', 'TAX_SHIPPING'): shipping_tax = config_value('TAX', 'TAX_CLASS') taxer = _get_taxprocessor(request) total = shipcost + taxer.by_price(shipping_tax, shipcost) taxed_shipping_price = money_format(total) data = { 'amount': shipcost, 'description': method.description(), 'method': method.method(), 'expected_delivery': method.expectedDelivery(), 'default_view_tax': default_view_tax, 'shipping_tax': shipping_tax, 'taxed_shipping_price': taxed_shipping_price } if hasattr(method, 'shipping_discount'): data['discount'] = method.shipping_discount() c = RequestContext(request, data) shipping_options.append((method.id, t.render(c))) shipping_dict[method.id] = shipcost return shipping_options, shipping_dict
def confirm_info(request): "Create form to send to WorldPay" # Check that items are in stock cart = Cart.objects.from_request(request) if cart.not_enough_stock(): return HttpResponseRedirect(urlresolvers.reverse("satchmo_cart")) try: order = Order.objects.from_request(request) except Order.DoesNotExist: order = None if not (order and order.validate(request)): context = RequestContext( request, {'message': _('Your order is no longer valid.')}) return render_to_response('shop_404.html', context) template = lookup_template(payment_module, 'checkout/worldpay/confirm.html') live = payment_module.LIVE.value currency = payment_module.CURRENCY_CODE.value inst_id = payment_module.INSTID.value default_view_tax = config_value('TAX', 'DEFAULT_VIEW_TAX') if live: post_url = payment_module.CONNECTION.value else: post_url = payment_module.CONNECTION_TEST.value if payment_module.MD5.value > "": # Doing the MD5 Signature dance # Generating secret "secret;amount;currency;cartId" balance = trunc_decimal(order.balance, 2) signature = "%s:%s:%s:%s" % (payment_module.MD5.value, balance, currency, order.id) MD5 = md5(signature).hexdigest() else: MD5 = False ctx = RequestContext( request, { 'order': order, 'inst_id': inst_id, 'currency': currency, 'post_url': post_url, 'default_view_tax': default_view_tax, 'PAYMENT_LIVE': live, 'MD5': MD5, 'session': request.session.session_key }) return render_to_response(template, ctx)
def confirm_info(request): # Check that items are in stock cart = Cart.objects.from_request(request) if cart.not_enough_stock(): return HttpResponseRedirect(reverse("satchmo_cart")) payment_module = config_get_group("PAYMENT_PAYPAL") # Get the order, # if there is no order, return to checkout step 1 try: order = Order.objects.from_request(request) except Order.DoesNotExist: url = lookup_url(payment_module, "satchmo_checkout-step1") return HttpResponseRedirect(url) # Check that the cart has items in it. if cart.numItems == 0: template = lookup_template(payment_module, "checkout/empty_cart.html") return render(request, template) # Check if the order is still valid if not order.validate(request): context = {"message": _("Your order is no longer valid.")} return render(request, "shop_404.html", context) # Set environment if payment_module.LIVE.value: environment = "production" else: environment = "sandbox" context = { "order": order, "environment": environment, "PAYMENT_LIVE": payment_live(payment_module), } template = lookup_template(payment_module, "checkout/paypal/confirm.html") return render(request, template, context)
def confirm_info(request): "Create form to send to Ingenico" # Check that items are in stock cart = Cart.objects.from_request(request) if cart.not_enough_stock(): return HttpResponseRedirect(reverse("satchmo_cart")) try: order = Order.objects.from_request(request) except Order.DoesNotExist: return HttpResponseRedirect(reverse("satchmo_shop_home")) if order.validate(request) is False: context = {"message": _("Your order is no longer valid.")} return render(request, "shop_404.html", context) data = { "PSPID": payment_module.PSPID.value, "ORDERID": order.id, # Amount * 100 # https://payment-services.ingenico.com/int/en/ogone/support/guides/integration%20guides/e-commerce#formparameters "AMOUNT": int(order.balance * 100), "CURRENCY": order.currency.iso_4217_code, "CN": order.bill_addressee, "EMAIL": order.contact.user.email, "OWNERADDRESS": ", ".join([order.bill_street1, order.bill_street2]), "OWNERZIP": order.bill_postal_code, "OWNERTOWN": ", ".join([order.bill_city, order.bill_state]), "OWNERCTY": order.bill_country.iso2_code, } if payment_module.ALIAS.value: data["ALIAS"] = hashlib.sha512( order.contact.user.username.encode("utf-8") ).hexdigest()[:50] data["ALIASUSAGE"] = payment_module.ALIASUSAGE.value form = IngenicoForm(data) template = lookup_template(payment_module, "checkout/ingenico/confirm.html") live = payment_module.LIVE.value if live: post_url = payment_module.CONNECTION.value else: post_url = payment_module.CONNECTION_TEST.value ctx = {"form": form, "order": order, "post_url": post_url, "PAYMENT_LIVE": live} return render(request, template, ctx)
def confirm_info(request): "Create form to send to WorldPay" # Check that items are in stock cart = Cart.objects.from_request(request) if cart.not_enough_stock(): return HttpResponseRedirect(urlresolvers.reverse("satchmo_cart")) try: order = Order.objects.from_request(request) except Order.DoesNotExist: order = None if not (order and order.validate(request)): context = RequestContext(request, {'message': _('Your order is no longer valid.')}) return render_to_response('shop_404.html', context) template = lookup_template(payment_module, 'checkout/worldpay/confirm.html') live = payment_module.LIVE.value currency = payment_module.CURRENCY_CODE.value inst_id = payment_module.INSTID.value default_view_tax = config_value('TAX', 'DEFAULT_VIEW_TAX') if live: post_url = payment_module.CONNECTION.value else: post_url = payment_module.CONNECTION_TEST.value if payment_module.MD5.value > "": # Doing the MD5 Signature dance # Generating secret "secret;amount;currency;cartId" balance = trunc_decimal(order.balance, 2) signature = "%s:%s:%s:%s" % (payment_module.MD5.value, balance, currency, order.id) MD5 = md5(signature).hexdigest() else: MD5 = False ctx = RequestContext(request, { 'order': order, 'inst_id': inst_id, 'currency': currency, 'post_url': post_url, 'default_view_tax': default_view_tax, 'PAYMENT_LIVE' : live, 'MD5' : MD5, 'session' : request.session.session_key }) return render_to_response(template, ctx)
def pay_ship_render_form(request, form, template, payment_module, cart): template = lookup_template(payment_module, template) if cart.numItems > 0: products = [item.product for item in cart.cartitem_set.all()] sale = find_best_auto_discount(products) else: sale = None ctx = RequestContext(request, { 'form': form, 'sale' : sale, 'PAYMENT_LIVE': payment_live(payment_module)}) return render_to_response(template, ctx)
def pay_ship_render_form(request, form, template, payment_module, cart): template = lookup_template(payment_module, template) if cart.numItems > 0: products = [item.product for item in cart.cartitem_set.all()] sale = find_best_auto_discount(products) else: sale = None ctx = { "form": form, "sale": sale, "PAYMENT_LIVE": payment_live(payment_module) } return render(request, template, ctx)
def pay_ship_render_form(request, form, template, payment_module, cart): template = lookup_template(payment_module, template) if cart.numItems > 0: products = [item.product for item in cart.cartitem_set.all()] sale = find_best_auto_discount(products) else: sale = None ctx = RequestContext(request, { 'form': form, 'sale': sale, 'PAYMENT_LIVE': payment_live(payment_module) }) return render_to_response(template, ctx)
def pay_ship_info_verify(request, payment_module): """Verify customer and cart. Returns: True, contact, cart on success False, destination of failure """ # Verify that the customer exists. try: contact = Contact.objects.from_request(request, create=False) except Contact.DoesNotExist: log.debug('No contact, returning to step 1 of checkout') url = lookup_url(payment_module, 'satchmo_checkout-step1') return (False, http.HttpResponseRedirect(url)) # Verify that we still have items in the cart. tempCart = Cart.objects.from_request(request) if tempCart.numItems == 0: template = lookup_template(payment_module, 'checkout/empty_cart.html') return (False, render_to_response(template, RequestContext(request))) return (True, contact, tempCart)
def pay_ship_info_verify(request, payment_module): """Verify customer and cart. Returns: True, contact, cart on success False, destination of failure """ # Verify that the customer exists. try: contact = Contact.objects.from_request(request, create=False) except Contact.DoesNotExist: log.debug("No contact, returning to step 1 of checkout") url = lookup_url(payment_module, "satchmo_checkout-step1") return (False, http.HttpResponseRedirect(url)) # Verify that we still have items in the cart. tempCart = Cart.objects.from_request(request) if tempCart.numItems == 0: template = lookup_template(payment_module, "checkout/empty_cart.html") return (False, render(request, template)) return (True, contact, tempCart)
def lookup_template(self, key): """Shortcut method to the the proper template from the `paymentModule`""" return lookup_template(self.paymentModule, self.templates[key])
def testLookupTemplateSet(self): t = lookup_template(self.dummy, "test.html") self.assertEqual(t, "test.html")
def testLookupTemplateSet(self): t = lookup_template(self.dummy, 'test.html') self.assertEqual(t, 'test.html')
def confirm_info(request): payment_module = config_get_group('PAYMENT_PAYPAL') try: order = Order.objects.from_request(request) except Order.DoesNotExist: url = lookup_url(payment_module, 'satchmo_checkout-step1') return HttpResponseRedirect(url) tempCart = Cart.objects.from_request(request) if tempCart.numItems == 0: template = lookup_template(payment_module, 'checkout/empty_cart.html') return render_to_response(template, RequestContext(request)) # Check if the order is still valid if not order.validate(request): context = RequestContext(request, {'message': _('Your order is no longer valid.')}) return render_to_response('shop_404.html', context) template = lookup_template(payment_module, 'checkout/paypal/confirm.html') if payment_module.LIVE.value: log.debug("live order on %s", payment_module.KEY.value) url = payment_module.POST_URL.value account = payment_module.BUSINESS.value else: url = payment_module.POST_TEST_URL.value account = payment_module.BUSINESS_TEST.value try: address = lookup_url(payment_module, payment_module.RETURN_ADDRESS.value, include_server=True) except urlresolvers.NoReverseMatch: address = payment_module.RETURN_ADDRESS.value create_pending_payment(order, payment_module) default_view_tax = config_value('TAX', 'DEFAULT_VIEW_TAX') recurring = None order_items = order.orderitem_set.all() for item in order_items: if item.product.is_subscription: recurring = {'product':item.product, 'price':item.product.price_set.all()[0].price,} trial0 = recurring['product'].subscriptionproduct.get_trial_terms(0) if len(order_items) > 1 or trial0 is not None or recurring['price'] < order.balance: recurring['trial1'] = {'price': order.balance,} if trial0 is not None: recurring['trial1']['expire_length'] = trial0.expire_length recurring['trial1']['expire_unit'] = trial0.expire_unit[0] # else: # recurring['trial1']['expire_length'] = recurring['product'].subscriptionproduct.get_trial_terms(0).expire_length trial1 = recurring['product'].subscriptionproduct.get_trial_terms(1) if trial1 is not None: recurring['trial2']['expire_length'] = trial1.expire_length recurring['trial2']['expire_unit'] = trial1.expire_unit[0] recurring['trial2']['price'] = trial1.price ctx = RequestContext(request, {'order': order, 'post_url': url, 'default_view_tax': default_view_tax, 'business': account, 'currency_code': payment_module.CURRENCY_CODE.value, 'return_address': address, 'invoice': order.id, 'subscription': recurring, 'PAYMENT_LIVE' : payment_live(payment_module) }) return render_to_response(template, ctx)
def confirm_info(request): # Check that items are in stock cart = Cart.objects.from_request(request) if cart.not_enough_stock(): return HttpResponseRedirect(urlresolvers.reverse("satchmo_cart")) payment_module = config_get_group('PAYMENT_PAYPAL') # Get the order, # if there is no order, return to checkout step 1 try: order = Order.objects.from_request(request) except Order.DoesNotExist: url = lookup_url(payment_module, 'satchmo_checkout-step1') return HttpResponseRedirect(url) # Check that the cart has items in it. if cart.numItems == 0: template = lookup_template(payment_module, 'checkout/empty_cart.html') return render_to_response(template, RequestContext(request)) # Check if the order is still valid if not order.validate(request): context = RequestContext( request, {'message': _('Your order is no longer valid.')}) return render_to_response('shop_404.html', context) # Set URL and accounts based on whether the site is LIVE or not if payment_module.LIVE.value: log.debug("live order on %s", payment_module.KEY.value) url = payment_module.POST_URL.value account = payment_module.BUSINESS.value else: url = payment_module.POST_TEST_URL.value account = payment_module.BUSINESS_TEST.value # Is there a custom return URL # Or will we use the default one? try: address = lookup_url(payment_module, payment_module.RETURN_ADDRESS.value, include_server=True) except urlresolvers.NoReverseMatch: address = payment_module.RETURN_ADDRESS.value # Create a pending payment create_pending_payment(order, payment_module) default_view_tax = config_value('TAX', 'DEFAULT_VIEW_TAX') recurring = None order_items = order.orderitem_set.all() for item in order_items: if item.product.is_subscription: recurring = { 'product': item.product, 'price': item.product.price_set.all()[0].price } trial0 = recurring['product'].subscriptionproduct.get_trial_terms( 0) if len(order_items) > 1 or trial0 is not None or recurring[ 'price'] < order.balance: recurring['trial1'] = {'price': order.balance} if trial0 is not None: recurring['trial1']['expire_length'] = trial0.expire_length recurring['trial1']['expire_unit'] = trial0.expire_unit[0] # else: # recurring['trial1']['expire_length'] = recurring['product'].subscriptionproduct.get_trial_terms(0).expire_length trial1 = recurring[ 'product'].subscriptionproduct.get_trial_terms(1) if trial1 is not None: recurring['trial2']['expire_length'] = trial1.expire_length recurring['trial2']['expire_unit'] = trial1.expire_unit[0] recurring['trial2']['price'] = trial1.price ctx = RequestContext( request, { 'order': order, 'post_url': url, 'default_view_tax': default_view_tax, 'business': account, 'currency_code': payment_module.CURRENCY_CODE.value, 'return_address': address, 'invoice': order.id, 'subscription': recurring, 'PAYMENT_LIVE': payment_live(payment_module) }) template = lookup_template(payment_module, 'checkout/paypal/confirm.html') return render_to_response(template, ctx)
def paypal_express_request_authorization(request): """Requests payment authorization for the payment with SetExpressCheckout""" payment_module = config_get_group('PAYMENT_PAYPAL_EXPRESS') tempCart = Cart.objects.from_request(request) if tempCart.numItems == 0: template = lookup_template(payment_module, 'checkout/empty_cart.html') return render_to_response(template, RequestContext(request)) #total = tempCart.total try: maxTaxRate = TaxRate.objects.all().order_by('-percentage')[0].percentage except: maxTaxRate = 0 maxTaxesAmount = tempCart.total * maxTaxRate maxShippingCosts = Decimal(payment_module.MAX_SHIPPING_COSTS.value) max_amt = '%.2f' % (tempCart.total + maxTaxesAmount + maxShippingCosts) amt = '%.2f' % (tempCart.total) paypal = PayPal(payment_module) noshipping = 0 params = { 'ACTION' : "S", # SetExpressCheckout 'NOSHIPPING' : noshipping, #1, 'TRXTYPE' : 'S', # Sale 'CURRENCYCODE' : payment_module.CURRENCY_CODE.value.encode(), # from Unicode 'ALLOWNOTE' : 1, #true 'AMT' : amt, 'MAXAMT': max_amt, 'LANDINGPAGE' : "Billing", 'REQCONFIRMSHIPPING': 0, 'SOLUTIONTYPE': "Sole", # Do not require forced paypal registration #'HDRIMG': paypal.shop_logo # 'HANDLINGAMT' : order.shipping_cost, # 'ITEMAMT' : order.total, # 'TAXAMT': order.tax, } if request.LANGUAGE_CODE: params["LOCALECODE"]=request.LANGUAGE_CODE.upper().encode() elif request.META["HTTP_ACCEPT_LANGUAGE"]: params["LOCALECODE"]=request.META["HTTP_ACCEPT_LANGUAGE"][:2].upper() # I set the paypal language else: params["LOCALECODE"]= paypal.localecode # If the user is authenticated I prepopulate paypal express checkout with its data if request.user.is_authenticated(): try: contact = Contact.objects.get(user=request.user) shipping_address = contact.shipping_address phone = contact.primary_phone params["EMAIL"] = unicodedata.normalize('NFC', contact.email).encode('ascii','ignore') params["ADDRESSOVERRIDE"] = 1 if shipping_address.addressee: params["NAME"] = unicode_to_ascii(shipping_address.addressee) else: params["NAME"] = unicode_to_ascii(contact.first_name+ " " + contact.second_name) params["LOCALECODE"] = shipping_address.country.iso2_code params["SHIPTOSTREET"] = unicode_to_ascii(shipping_address.street1) params["SHIPTOSTREET2"] = unicode_to_ascii(shipping_address.street2) params["SHIPTOCITY"] = unicode_to_ascii(shipping_address.city) params["SHIPTOSTATE"] = unicode_to_ascii(shipping_address.state) params["SHIPTOZIP"] = unicode_to_ascii(shipping_address.postal_code) params["SHIPTOCOUNTRY"] = shipping_address.country.iso2_code params["PHONENUM"] = unicode_to_ascii(phone.phone) except: pass #user is authenticated but he haven't contact pp_token = paypal.SetExpressCheckout(params) express_token = paypal.GetExpressCheckoutDetails(pp_token) url= paypal.PAYPAL_URL + express_token request.session['paypal_express_token'] = pp_token # I save my cart to get it once finished #request.session['cart_id'] = tempCart return HttpResponseRedirect(url)
def paypal_express_pay(request): """Process the real payment on PayPal Express Checkout with DoExpressCheckoutPayment""" try: order = Order.objects.from_request(request) except Order.DoesNotExist: url = lookup_url(payment_module, 'satchmo_checkout-step1') return HttpResponseRedirect(url) tempCart = Cart.objects.from_request(request) if tempCart.numItems == 0: template = lookup_template(payment_module, 'checkout/empty_cart.html') return render_to_response(template, RequestContext(request)) # Check if the order is still valid if not order.validate(request): context = RequestContext(request, {'message': _('Your order is no longer valid.')}) return render_to_response('shop_404.html', context) payment_module = config_get_group('PAYMENT_PAYPAL_EXPRESS') #amount = '%.2f' % (order.total) paypal = PayPal(payment_module) shipping_amount = order.shipping_cost shipping_discount = order.shipping_discount if 'paypal_express_token' in request.session: paypal_express_token = request.session['paypal_express_token'] response_getDetails = paypal.GetExpressCheckoutDetails(paypal_express_token, return_all=True) params = { 'PAYERID' : response_getDetails["PAYERID"][0], 'CURRENCYCODE' : 'USD', 'AMT' : '%.2f' % order.total, 'ITEMAMT' : '%.2f' % order.sub_total, 'SHIPPINGAMT' : '%.2f' % order.shipping_cost, 'SHIPPINGDISCOUNT' : '%.2f' % order.shipping_discount, 'TAXAMT' : '%.2f' % (order.tax - order.discount), 'TOKEN' : paypal_express_token, } # This function does the payment data = paypal.DoExpressCheckoutPayment(params) #try: log.debug("PayPal Express Checkout data: " + repr(data)) if not 'RESULT' in data or not data['RESULT'] == '0': #if not 'payment_status' in data or not data['payment_status'] == "Completed": # We want to respond to anything that isn't a payment - but we won't insert into our database. log.info("Ignoring IPN data for non-completed payment.") # I show a failed payment error template = lookup_template(payment_module, 'checkout/paypal_express/failed.html') # {'ACK': 'Failure', 'TIMESTAMP': '2009-02-28T13:48:55Z', 'L_SEVERITYCODE0': 'Error', 'L_SHORTMESSAGE0': 'Transaction cannot complete.', 'L_LONGMESSAGE0': 'The transaction cannot complete successfully. Instruct the customer to use an alternative payment method.', 'VERSION': '53.0', 'BUILD': '845846', 'L_ERRORCODE0': '10417', 'CORRELATIONID': 'be804544f01'} ctx = RequestContext(request, {'order': order, 'data': repr(data), 'ack': data["RESPMSG"], #'severity_code': data["L_SEVERITYCODE0"], #'short_message': data["L_SHORTMESSAGE0"], #'long_message': data["L_LONGMESSAGE0"], #'error_code': data["L_ERRORCODE0"], }) # Li aggiungo fuori perche se ne manca uno altrimenti restituisce un keyerror try: ctx["severity_code"]= data["RESULT"] except: pass try: ctx["short_message"]= data["RESPMSG"] except: pass try: ctx["long_message"]= data["RESPMSG"] except: pass try: ctx["error_code"]=data["RESULT"] except: pass return render_to_response(template, ctx) txn_id = data['PNREF'] if not OrderPayment.objects.filter(transaction_id=txn_id).count(): # If the payment hasn't already been processed: #order = Order.objects.get(pk=invoice) order.add_status(status='Billed', notes=_("Paid through PayPal Express Checkout.")) #orderstatus = order.status record_payment(order, payment_module, amount=order.total, transaction_id=txn_id) notes_changed = False if order.notes: notes = order.notes + "\n" else: notes = "" # Retrieving notes from paypal NOTE field if 'NOTE' in response_getDetails: notes_changed = True response_notes = response_getDetails['NOTE'][0] # If I get some problems, the error will include notes if I put it in a variable. notes = u"\n%s \n%s \n%s" % (notes, _('---Comment via Paypal EXPRESS CHECKOUT---') ,response_notes ) log.debug("Saved order notes from Paypal Express Checkout") # Retrieving notes from confirmation page if (request.method == "POST") and ('note' in request.POST) and (request.POST['note'] != ""): notes_changed = True #notes = notes + u'\n\n' + _('---Notes sent by confirm Order Form---') + u'\n' + request.POST['note'] notes = u"%s \n\n%s \n %s" % (notes, _('---Notes sent by confirm Order Form---'), request.POST['note']) log.debug("Saved order notes from Confirm Order Page") # If I must add some notes to my order if notes_changed: order.notes = notes order.save() for item in order.orderitem_set.filter(product__subscriptionproduct__recurring=True, completed=False): item.completed = True item.save() for cart in Cart.objects.filter(customer=order.contact): cart.empty() # I remove the token from the session request.session['paypal_express_token'] #order.save() #except: # log.exception(''.join(format_exception(*exc_info()))) # assert False url = urlresolvers.reverse("PAYPAL_EXPRESS_satchmo_checkout-success") return HttpResponseRedirect(url)
def pp_express_pay_ship_info_verify(request, payment_module): """Verify customer and cart. Returns: True, contact, cart on success False, destination of failure """ # Get Customer Info from Paypal Express Checkout paypal = PayPal(payment_module) if 'paypal_express_token' in request.session: paypal_express_token = request.session['paypal_express_token'] else: # If the user didn't get the authorization I redirect to the request authorization page return False response_dict = paypal.GetExpressCheckoutDetails(paypal_express_token, return_all=True) if 'SHIPTOSTREET' not in response_dict: # If the user didn't get the authorization I redirect to the request authorization page return False email = response_dict["EMAIL"][0] first_name = response_dict["FIRSTNAME"][0] last_name = response_dict["LASTNAME"][0] addressee = response_dict["SHIPTONAME"][0] street1 = response_dict["SHIPTOSTREET"][0] try: street2 = response_dict["SHIPTOSTREET2"][0] except: street2 = "" city = response_dict["SHIPTOCITY"][0] try: state = response_dict["SHIPTOSTATE"][0] except: state = " " postal_code = response_dict["SHIPTOZIP"][0] country_code = response_dict["SHIPTOCOUNTRY"][0] country = Country.objects.get(iso2_code__iexact=country_code) # I get users notes if request.user.is_authenticated(): try: contact = Contact.objects.get(user=request.user) # If the user is authenticated I don't neet to create a new contact contact.email = email contact.first_name = first_name contact.last_name = last_name # I delete the user shipping address to overwrite with paypal express data try: contact.shipping_address.delete() except: pass # I delete the user phone number to overwrite with paypal express data try: contact.primary_phone.delete() except: pass except: pass elif request.session.get(CUSTOMER_ID): try: contact = Contact.objects.get(id=request.session[CUSTOMER_ID]) contact.email = email contact.first_name = first_name contact.last_name = last_name # I delete the user shipping address to overwrite with paypal express data try: contact.shipping_address.delete() except: pass # I delete the user phone number to overwrite with paypal express data try: contact.primary_phone.delete() except: pass except Contact.DoesNotExist: del request.session[CUSTOMER_ID] try: contact except NameError: try: # If a user with the same name, email and last name exists, I get that instead of a new contact creation contact = Contact.objects.filter(email__iexact=email).filter(first_name__iexact=first_name).filter(last_name__iexact=last_name)[0] except: # if it doesn't exists, I create it contact = Contact(email=email, first_name = first_name, last_name=last_name) # If the user wrote a note, I save it try: #if the user exists, I overwrite his contact data contact.notes = contact.notes + '\n' + response_dict["NOTE"][0] except: pass # I save my contact contact.save() #request.session['CUSTOMER_ID'] = contact.id request.session[CUSTOMER_ID] = contact.id shipping_address = AddressBook(addressee=addressee, contact=contact, street1=street1, street2=street2,city = city, state=state, postal_code=postal_code,\ country=country, is_default_shipping=True) shipping_address.save() #billing_address = AddressBook(addressee=addressee, contact=contact, street1=street1, street2=street2,city = city, state=state, postal_code=postal_code,\ # country=country, is_default_shipping=True) #billing_address.save() try: phone = PhoneNumber(contact=contact, phone=response_dict["PHONENUM"][0], primary=True, type="Home") phone.save() except: log.debug("PayPal Error importing phone number: " + repr(response_dict)) # Verify that we still have items in the cart. tempCart = Cart.objects.from_request(request) tempCart.customer = contact tempCart.save() if tempCart.numItems == 0: template = lookup_template(payment_module, 'checkout/empty_cart.html') return (False, render_to_response(template, RequestContext(request))) return (True, contact, tempCart)