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 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 __init__(self, payment_module): if payment_module.LIVE.value: log.debug("live order on %s", payment_module.KEY.value) self.PAYPAL_URL = payment_module.POST_URL.value self.API_ENDPOINT = payment_module.ENDPOINT_URL.value #account = payment_module.BUSINESS.value else: log.debug("test order on %s", payment_module.KEY.value) self.PAYPAL_URL = payment_module.POST_TEST_URL.value self.API_ENDPOINT = payment_module.ENDPOINT_TEST_URL.value ## Sandbox values self.signature_values = { 'USER' : payment_module.API_USER.value, 'VENDOR' : payment_module.API_MERCHANT_LOGIN_ID.value, 'PARTNER' : payment_module.API_PARTNER.value, 'PWD' : payment_module.API_PASSWORD.value } self.signature = urllib.urlencode(self.signature_values) + "&" self.return_url = lookup_url(payment_module, 'satchmo_checkout-step2') self.return_url = "http://" + settings.SITE_DOMAIN + self.return_url self.cancel_url = lookup_url(payment_module, 'satchmo_checkout-cancel') self.cancel_url = "http://" + settings.SITE_DOMAIN + self.cancel_url if payment_module.SHOP_LOGO.value.startswith("http"): self.shop_logo = payment_module.SHOP_LOGO.value else: self.shop_logo = "http://" + settings.SITE_DOMAIN + payment_module.SHOP_LOGO.value self.localecode = payment_module.DEFAULT_LOCALECODE.value.upper().encode() # from unicode
def _cart_xml(self, order): template = get_template(self.settings["CART_XML_TEMPLATE"].value) shopping_url = lookup_url(self.settings, 'satchmo_checkout-success', True, self.settings.SSL.value) edit_url = lookup_url(self.settings, 'satchmo_cart', True, self.settings.SSL.value) ctx = Context({"order" : order, "continue_shopping_url" : shopping_url, "edit_cart_url" : edit_url, "currency" : self.settings.CURRENCY_CODE.value, }) return template.render(ctx)
def _cart_xml(self, order): template = get_template(self.settings["CART_XML_TEMPLATE"].value) shopping_url = lookup_url(self.settings, 'satchmo_checkout-success', True, self.settings.SSL.value) edit_url = lookup_url(self.settings, 'satchmo_cart', True, self.settings.SSL.value) ctx = Context({ "order": order, "continue_shopping_url": shopping_url, "edit_cart_url": edit_url, "currency": self.settings.CURRENCY_CODE.value, }) return template.render(ctx)
def credit_pay_ship_process_form(request, contact, working_cart, payment_module, *args, **kwargs): """Handle the form information. Returns: (True, destination) on success (False, form) on failure """ def _get_form(request, payment_module, *args, **kwargs): processor = payment_module.MODULE.load_module("processor") log.debug("processor=%s", processor) if hasattr(processor, "FORM"): log.debug("getting form from module") formclass = processor.FORM else: log.debug("using default form") formclass = CreditPayShipForm form = formclass(request, payment_module, *args, **kwargs) return form if request.method == "POST": new_data = request.POST.copy() form = _get_form(request, payment_module, new_data, *args, **kwargs) if form.is_valid(): form.save(request, working_cart, contact, payment_module) url = lookup_url(payment_module, "satchmo_checkout-step3") return (True, http.HttpResponseRedirect(url)) else: log.debug("Form errors: %s", form.errors) else: form = _get_form(request, payment_module, *args, **kwargs) return (False, form)
def credit_pay_ship_process_form(request, contact, working_cart, payment_module, *args, **kwargs): """Handle the form information. Returns: (True, destination) on success (False, form) on failure """ def _get_form(request, payment_module, *args, **kwargs): processor = payment_module.MODULE.load_module('processor') log.debug('processor=%s', processor) if hasattr(processor, 'FORM'): log.debug('getting form from module') formclass = processor.FORM else: log.debug('using default form') formclass = CreditPayShipForm form = formclass(request, payment_module, *args, **kwargs) return form if request.method == "POST": new_data = request.POST.copy() form = _get_form(request, payment_module, new_data, *args, **kwargs) if form.is_valid(): form.save(request, working_cart, contact, payment_module) url = lookup_url(payment_module, 'satchmo_checkout-step3') return (True, http.HttpResponseRedirect(url)) else: log.debug('Form errors: %s', form.errors) else: form = _get_form(request, payment_module, *args, **kwargs) return (False, form)
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 simple_pay_ship_process_form(request, contact, working_cart, payment_module): if request.method == "POST": new_data = request.POST.copy() form = SimplePayShipForm(request, payment_module, new_data) if form.is_valid(): form.save(request, working_cart, contact, payment_module) url = lookup_url(payment_module, 'satchmo_checkout-step3') return (True, http.HttpResponseRedirect(url)) else: form = SimplePayShipForm(request, payment_module) return (False, form)
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 __init__(self, payment_module): if payment_module.LIVE.value: log.debug("live order on %s", payment_module.KEY.value) self.PAYPAL_URL = payment_module.POST_URL.value self.API_ENDPOINT = payment_module.ENDPOINT_URL.value api_signature_username = payment_module.API_SIGNATURE_USERNAME.value api_signature_password = payment_module.API_SIGNATURE_PASSWORD.value api_signature_code = payment_module.API_SIGNATURE_CODE.value #account = payment_module.BUSINESS.value else: log.debug("test order on %s", payment_module.KEY.value) self.PAYPAL_URL = payment_module.POST_TEST_URL.value self.API_ENDPOINT = payment_module.ENDPOINT_TEST_URL.value api_signature_username = payment_module.SANDBOX_API_SIGNATURE_USERNAME.value api_signature_password = payment_module.SANDBOX_API_SIGNATURE_PASSWORD.value api_signature_code = payment_module.SANDBOX_API_SIGNATURE_CODE.value ## Sandbox values self.signature_values = { 'USER' : api_signature_username, 'PWD' : api_signature_password, 'SIGNATURE' : api_signature_code, 'VERSION' : '53.0', } self.signature = urllib.urlencode(self.signature_values) + "&" self.return_url = lookup_url(payment_module, 'satchmo_checkout-step2') self.return_url = "http://" + settings.SITE_DOMAIN + self.return_url self.cancel_url = lookup_url(payment_module, 'satchmo_checkout-cancel') self.cancel_url = "http://" + settings.SITE_DOMAIN + self.cancel_url if payment_module.SHOP_LOGO.value.startswith("http"): self.shop_logo = payment_module.SHOP_LOGO.value else: self.shop_logo = "http://" + settings.SITE_DOMAIN + payment_module.SHOP_LOGO.value self.localecode = payment_module.DEFAULT_LOCALECODE.value.upper().encode() # from unicode
def simple_pay_ship_process_form(request, contact, working_cart, payment_module): if request.method == "POST": new_data = request.POST.copy() form = SimplePayShipForm(request, payment_module, new_data) if form.is_valid(): form.save(request, working_cart, contact, payment_module) url = lookup_url(payment_module, "satchmo_checkout-step3") return (True, http.HttpResponseRedirect(url)) else: form = SimplePayShipForm(request, payment_module) return (False, form)
def purchaseorder_process_form(request, contact, working_cart, payment_module): log.debug('purchaseorder_process_form') if request.method == "POST": log.debug('handling POST') new_data = request.POST.copy() form = PurchaseorderPayShipForm(request, payment_module, new_data) if form.is_valid(): form.save(request, working_cart, contact, payment_module) url = lookup_url(payment_module, 'satchmo_checkout-step3') return (True, http.HttpResponseRedirect(url)) else: log.debug('new form') form = PurchaseorderPayShipForm(request, payment_module) return (False, form)
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 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 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 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 giftcert_pay_ship_process_form(request, contact, working_cart, payment_module): if request.method == "POST": new_data = request.POST.copy() form = GiftCertPayShipForm(request, payment_module, new_data) if form.is_valid(): data = form.cleaned_data # Create a new order. newOrder = get_or_create_order(request, working_cart, contact, data) newOrder.add_variable(GIFTCODE_KEY, data['giftcode']) request.session['orderID'] = newOrder.id url = None if not url: url = lookup_url(payment_module, 'satchmo_checkout-step3') return (True, http.HttpResponseRedirect(url)) else: form = GiftCertPayShipForm(request, payment_module) return (False, form)
def giftcert_pay_ship_process_form(request, contact, working_cart, payment_module): if request.method == "POST": new_data = request.POST.copy() form = GiftCertPayShipForm(request, payment_module, new_data) if form.is_valid(): data = form.cleaned_data # Create a new order. newOrder = get_or_create_order(request, working_cart, contact, data) newOrder.add_variable(GIFTCODE_KEY, data["giftcode"]) request.session["orderID"] = newOrder.id url = None if not url: url = lookup_url(payment_module, "satchmo_checkout-step3") return (True, http.HttpResponseRedirect(url)) else: form = GiftCertPayShipForm(request, payment_module) return (False, form)
def balance_remaining(request): """Allow the user to pay the remaining balance.""" order = None orderid = request.session.get('orderID') if orderid: try: order = Order.objects.get(pk=orderid) except Order.DoesNotExist: # TODO: verify user against current user pass if not order: url = urlresolvers.reverse('satchmo_checkout-step1') return HttpResponseRedirect(url) if request.method == "POST": new_data = request.POST.copy() form = PaymentMethodForm(new_data, order=order) if form.is_valid(): data = form.cleaned_data modulename = data['paymentmethod'] if not modulename.startswith('PAYMENT_'): modulename = 'PAYMENT_' + modulename paymentmodule = config_get_group(modulename) url = lookup_url(paymentmodule, 'satchmo_checkout-step2') return HttpResponseRedirect(url) else: form = PaymentMethodForm(order=order) ctx = RequestContext( request, { 'form': form, 'order': order, 'paymentmethod_ct': len(config_value('PAYMENT', 'MODULES')) }) return render_to_response('checkout/balance_remaining.html', ctx)
def balance_remaining(request): """Allow the user to pay the remaining balance.""" order = None orderid = request.session.get("orderID") if orderid: try: order = Order.objects.get(pk=orderid) except Order.DoesNotExist: # TODO: verify user against current user pass if not order: url = reverse("satchmo_checkout-step1") return HttpResponseRedirect(url) if request.method == "POST": new_data = request.POST.copy() form = PaymentMethodForm(new_data, order=order) if form.is_valid(): data = form.cleaned_data modulename = data["paymentmethod"] if not modulename.startswith("PAYMENT_"): modulename = "PAYMENT_" + modulename paymentmodule = config_get_group(modulename) url = lookup_url(paymentmodule, "satchmo_checkout-step2") return HttpResponseRedirect(url) else: form = PaymentMethodForm(order=order) ctx = { "form": form, "order": order, "paymentmethod_ct": len(config_value("PAYMENT", "MODULES")), } return render(request, "checkout/balance_remaining.html", ctx)
def balance_remaining(request): """Allow the user to pay the remaining balance.""" order = None orderid = request.session.get('orderID') if orderid: try: order = Order.objects.get(pk=orderid) except Order.DoesNotExist: # TODO: verify user against current user pass if not order: url = urlresolvers.reverse('satchmo_checkout-step1') return HttpResponseRedirect(url) if request.method == "POST": new_data = request.POST.copy() form = PaymentMethodForm(new_data, order=order) if form.is_valid(): data = form.cleaned_data modulename = data['paymentmethod'] if not modulename.startswith('PAYMENT_'): modulename = 'PAYMENT_' + modulename paymentmodule = config_get_group(modulename) url = lookup_url(paymentmodule, 'satchmo_checkout-step2') return HttpResponseRedirect(url) else: form = PaymentMethodForm(order=order) ctx = RequestContext(request, { 'form': form, 'order': order, 'paymentmethod_ct': len(config_value('PAYMENT', 'MODULES')) }) return render_to_response('checkout/balance_remaining.html', ctx)
def create_payment(request, retries=0): """Call the /v1/payments/payment REST API with your client ID and secret and your payment details to create a payment ID. Return the payment ID to the client as JSON. """ if request.method != "POST": raise Http404 # Get the order, if there is no order, return to checkout step 1 try: order = Order.objects.from_request(request) except Order.DoesNotExist: raise Http404 # Contact PayPal to create the payment configure_api() payment_module = config_get_group("PAYMENT_PAYPAL") site = Site.objects.get_current() data = { "intent": "order", "payer": { "payment_method": "paypal" }, "redirect_urls": { "return_url": lookup_url(payment_module, "paypal:satchmo_checkout-success", include_server=True), "cancel_url": lookup_url(payment_module, "satchmo_checkout-step1", include_server=True), }, "transactions": [{ "amount": { "currency": order.currency.iso_4217_code, "total": str(order.total), "details": { "subtotal": str(order.sub_total - order.discount), "tax": str(order.tax), "shipping": str(order.shipping_cost), "shipping_discount": str(order.shipping_discount), }, }, "description": "Your {site} order.".format(site=site.name), "invoice_number": str(order.id), "payment_options": { "allowed_payment_method": "UNRESTRICTED" }, "item_list": { "items": [{ "name": item.product.name, "description": item.product.meta, "quantity": item.quantity, "currency": order.currency.iso_4217_code, "price": "{price:.2f}".format( price=(item.unit_price - (item.discount / item.quantity))), "tax": str(item.unit_tax), "sku": item.product.sku, } for item in order.orderitem_set.all()], "shipping_address": { "recipient_name": order.ship_addressee, "line1": order.ship_street1, "line2": order.ship_street2, "city": order.ship_city, "country_code": order.ship_country.iso2_code, "postal_code": order.ship_postal_code, "state": order.ship_state, }, "shipping_method": order.shipping_description, }, }], } # Send it to PayPal payment = paypalrestsdk.Payment(data) if payment.create(): order.notes += _("--- Paypal Payment Created ---") + "\n" order.notes += str(timezone.now()) + "\n" order.notes += pprint.pformat(payment.to_dict()) + "\n\n" order.freeze() order.save() # Create a pending payment in our system order_payment = create_pending_payment(order, payment_module) order_payment.transaction_id = payment["id"] order_payment.save() # Return JSON to client return JsonResponse(payment.to_dict(), status=201) else: subject = "PayPal API error" message = "\n".join("{key}: {value}".format(key=key, value=value) for key, value in payment.error.items()) # Add the posted data message += "\n\n" + pprint.pformat(data) + "\n" mail_admins(subject, message) log.error(payment.error) log.error(pprint.pformat(data)) if payment.error["name"] == "VALIDATION_ERROR": data = payment.error["details"] else: data = { "message": _("""Something went wrong with your PayPal payment. Please try again. If the problem persists, please contact us.""") } # Because we are returning a list of dicts, we must mark it as unsafe return JsonResponse(data, status=400, safe=False)
def lookup_url(self, view): """Shortcut method to the the proper url from the `paymentModule`""" return lookup_url(self.paymentModule, view)
def contact_info(request, **kwargs): """View which collects demographic information from customer.""" # First verify that the cart exists and has items tempCart = Cart.objects.from_request(request) if tempCart.numItems == 0: return render_to_response("checkout/empty_cart.html", RequestContext(request)) if not request.user.is_authenticated() and config_value(SHOP_GROUP, "AUTHENTICATION_REQUIRED"): url = urlresolvers.reverse("satchmo_checkout_auth_required") thisurl = urlresolvers.reverse("satchmo_checkout-step1") return http.HttpResponseRedirect(url + "?next=" + thisurl) init_data = {} shop = Config.objects.get_current() if request.user.is_authenticated(): if request.user.email: init_data["email"] = request.user.email if request.user.first_name: init_data["first_name"] = request.user.first_name if request.user.last_name: init_data["last_name"] = request.user.last_name try: contact = Contact.objects.from_request(request, create=False) except Contact.DoesNotExist: contact = None if request.method == "POST": new_data = request.POST.copy() if new_data["couple_spouse1_first_name"] == "" and new_data["couple_spouse1_last_name"] == "": spouse1 = "" else: spouse1 = ( u"Spouse 1: " + new_data["couple_spouse1_first_name"] + u" " + new_data["couple_spouse1_middle_initial"] + u" " + new_data["couple_spouse1_last_name"] ) if new_data["couple_spouse2_first_name"] == "" and new_data["couple_spouse2_last_name"] == "": spouse2 = "" else: spouse2 = ( u"\u000d\u000aSpouse 2: " + new_data["couple_spouse2_first_name"] + u" " + new_data["couple_spouse2_middle_initial"] + u" " + new_data["couple_spouse2_last_name"] ) if ( new_data["couple_wedding_month"] == "" and new_data["couple_wedding_day"] == "" and new_data["couple_wedding_year"] == "" ): wedding = "" else: wedding = ( u"\u000d\u000aWedding Date: " + new_data["couple_wedding_month"] + u" " + new_data["couple_wedding_day"] + u" " + new_data["couple_wedding_year"] ) if wedding == "" and spouse1 == "" and spouse2 == "": tempCart.desc = "" tempCart.save() else: tempCart.desc = spouse1 + spouse2 + wedding tempCart.save() if not tempCart.is_shippable: new_data["copy_address"] = True form = PaymentContactInfoForm( new_data, shop=shop, contact=contact, shippable=tempCart.is_shippable, initial=init_data, cart=tempCart ) if form.is_valid(): if contact is None and request.user and request.user.is_authenticated(): contact = Contact(user=request.user) custID = form.save(contact=contact, update_newsletter=False) request.session[CUSTOMER_ID] = custID # Ensure that if we have an existing order the address for the order gets updated try: exist_order = Order.objects.from_request(request) except Order.DoesNotExist: exist_order = None if exist_order: exist_order.copy_addresses() exist_order.save() # TODO - Create an order here and associate it with a session modulename = new_data["paymentmethod"] if not modulename.startswith("PAYMENT_"): modulename = "PAYMENT_" + modulename paymentmodule = config_get_group(modulename) url = lookup_url(paymentmodule, "satchmo_checkout-step2") return http.HttpResponseRedirect(url) else: log.debug("Form errors: %s", form.errors) else: if contact: # If a person has their contact info, make sure we populate it in the form for item in contact.__dict__.keys(): init_data[item] = getattr(contact, item) if contact.shipping_address: for item in contact.shipping_address.__dict__.keys(): init_data["ship_" + item] = getattr(contact.shipping_address, item) if contact.billing_address: for item in contact.billing_address.__dict__.keys(): init_data[item] = getattr(contact.billing_address, item) if contact.primary_phone: init_data["phone"] = contact.primary_phone.phone else: # Allow them to login from this page. request.session.set_test_cookie() form = PaymentContactInfoForm( shop=shop, contact=contact, shippable=tempCart.is_shippable, initial=init_data, cart=tempCart ) if shop.in_country_only: only_country = shop.sales_country else: only_country = None context = RequestContext( request, {"form": form, "country": only_country, "paymentmethod_ct": len(form.fields["paymentmethod"].choices)} ) return render_to_response("checkout/form.html", context)
def testLookupURL(self): try: t = lookup_url(self.dummy, "test_doesnt_exist") self.fail("Should have failed with NoReverseMatch") except NoReverseMatch: pass
def contact_info(request, **kwargs): """View which collects demographic information from customer.""" # First verify that the cart exists and has items tempCart = Cart.objects.from_request(request) if tempCart.numItems == 0: return render(request, "checkout/empty_cart.html") init_data = {} shop = Config.objects.get_current() if request.user.email: init_data["email"] = request.user.email if request.user.first_name: init_data["first_name"] = request.user.first_name if request.user.last_name: init_data["last_name"] = request.user.last_name try: contact = Contact.objects.from_request(request, create=False) except Contact.DoesNotExist: contact = None # Check that items are in stock cart = Cart.objects.from_request(request) if cart.not_enough_stock(): return http.HttpResponseRedirect(reverse("satchmo_cart")) if request.method == "POST": new_data = request.POST.copy() if not tempCart.is_shippable: new_data["copy_address"] = True form = PaymentContactInfoForm( new_data, shop=shop, contact=contact, shippable=tempCart.is_shippable, initial=init_data, cart=tempCart, ) if form.is_valid(): if contact is None and request.user and request.user.is_authenticated: contact = Contact(user=request.user) custID = form.save(contact=contact) request.session[CUSTOMER_ID] = custID # TODO - Create an order here and associate it with a session modulename = new_data["paymentmethod"] if not modulename.startswith("PAYMENT_"): modulename = "PAYMENT_" + modulename paymentmodule = config_get_group(modulename) url = lookup_url(paymentmodule, "satchmo_checkout-step2") return http.HttpResponseRedirect(url) else: log.debug("Form errors: %s", form.errors) else: if contact: # If a person has their contact info, make sure we populate it in the form for item in list(contact.__dict__.keys()): init_data[item] = getattr(contact, item) if contact.shipping_address: for item in list(contact.shipping_address.__dict__.keys()): init_data["ship_" + item] = getattr( contact.shipping_address, item) if contact.billing_address: for item in list(contact.billing_address.__dict__.keys()): init_data[item] = getattr(contact.billing_address, item) if contact.primary_phone: init_data["phone"] = contact.primary_phone.phone else: # Allow them to login from this page. request.session.set_test_cookie() init_data["copy_address"] = True form = PaymentContactInfoForm( shop=shop, contact=contact, shippable=tempCart.is_shippable, initial=init_data, cart=tempCart, ) if shop.in_country_only: only_country = shop.sales_country else: only_country = None context = { "form": form, "country": only_country, "paymentmethod_ct": len(form.fields["paymentmethod"].choices), } return render(request, "checkout/form.html", context)
def contact_info(request, **kwargs): """View which collects demographic information from customer.""" #First verify that the cart exists and has items tempCart = Cart.objects.from_request(request) if tempCart.numItems == 0: return render_to_response('checkout/empty_cart.html', RequestContext(request)) init_data = {} shop = Config.objects.get_current() if request.user.email: init_data['email'] = request.user.email if request.user.first_name: init_data['first_name'] = request.user.first_name if request.user.last_name: init_data['last_name'] = request.user.last_name try: contact = Contact.objects.from_request(request, create=False) except Contact.DoesNotExist: contact = None # Check that items are in stock cart = Cart.objects.from_request(request) if cart.not_enough_stock(): return http.HttpResponseRedirect(urlresolvers.reverse("satchmo_cart")) if request.method == "POST": new_data = request.POST.copy() if not tempCart.is_shippable: new_data['copy_address'] = True form = PaymentContactInfoForm(new_data, shop=shop, contact=contact, shippable=tempCart.is_shippable, initial=init_data, cart=tempCart) if form.is_valid(): if contact is None and request.user and request.user.is_authenticated(): contact = Contact(user=request.user) custID = form.save(contact=contact) request.session[CUSTOMER_ID] = custID #TODO - Create an order here and associate it with a session modulename = new_data['paymentmethod'] if not modulename.startswith('PAYMENT_'): modulename = 'PAYMENT_' + modulename paymentmodule = config_get_group(modulename) url = lookup_url(paymentmodule, 'satchmo_checkout-step2') return http.HttpResponseRedirect(url) else: log.debug("Form errors: %s", form.errors) else: if contact: #If a person has their contact info, make sure we populate it in the form for item in contact.__dict__.keys(): init_data[item] = getattr(contact,item) if contact.shipping_address: for item in contact.shipping_address.__dict__.keys(): init_data["ship_"+item] = getattr(contact.shipping_address,item) if contact.billing_address: for item in contact.billing_address.__dict__.keys(): init_data[item] = getattr(contact.billing_address,item) if contact.primary_phone: init_data['phone'] = contact.primary_phone.phone else: # Allow them to login from this page. request.session.set_test_cookie() init_data['copy_address'] = True form = PaymentContactInfoForm( shop=shop, contact=contact, shippable=tempCart.is_shippable, initial=init_data, cart=tempCart) if shop.in_country_only: only_country = shop.sales_country else: only_country = None context = RequestContext(request, { 'form': form, 'country': only_country, 'paymentmethod_ct': len(form.fields['paymentmethod'].choices) }) return render_to_response('checkout/form.html', context)
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 testLookupURL(self): try: t = lookup_url(self.dummy, 'test_doesnt_exist') self.fail('Should have failed with NoReverseMatch') except urlresolvers.NoReverseMatch: pass
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 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 create_payment(request, retries=0): """Call the /v1/payments/payment REST API with your client ID and secret and your payment details to create a payment ID. Return the payment ID to the client as JSON. """ if request.method != "POST": raise Http404 # Get the order, if there is no order, return to checkout step 1 try: order = Order.objects.from_request(request) except Order.DoesNotExist: raise Http404 # Contact PayPal to create the payment configure_api() payment_module = config_get_group("PAYMENT_PAYPAL") site = Site.objects.get_current() data = { "intent": "order", "payer": {"payment_method": "paypal"}, "redirect_urls": { "return_url": lookup_url( payment_module, "paypal:satchmo_checkout-success", include_server=True ), "cancel_url": lookup_url( payment_module, "satchmo_checkout-step1", include_server=True ), }, "transactions": [ { "amount": { "currency": order.currency.iso_4217_code, "total": str(order.total), "details": { "subtotal": str(order.sub_total), "tax": str(order.tax), "shipping": str(order.shipping_cost), "shipping_discount": str(order.shipping_discount), }, }, "description": "Your {site} order.".format(site=site.name), "invoice_number": str(order.id), "payment_options": {"allowed_payment_method": "UNRESTRICTED"}, "item_list": { "items": [ { "name": item.product.name, "description": item.product.meta, "quantity": item.quantity, "currency": order.currency.iso_4217_code, "price": str(item.unit_price), "tax": str(item.unit_tax), "sku": item.product.sku, } for item in order.orderitem_set.all() ], "shipping_address": { "recipient_name": order.ship_addressee, "line1": order.ship_street1, "line2": order.ship_street2, "city": order.ship_city, "country_code": order.ship_country.iso2_code, "postal_code": order.ship_postal_code, "state": order.ship_state, }, "shipping_method": order.shipping_description, }, } ], } # Send it to PayPal payment = paypalrestsdk.Payment(data) if payment.create(): order.notes += _("--- Paypal Payment Created ---") + "\n" order.notes += str(timezone.now()) + "\n" order.notes += pprint.pformat(payment.to_dict()) + "\n" order.freeze() order.save() # Create a pending payment in our system order_payment = create_pending_payment(order, payment_module) order_payment.transaction_id = payment["id"] order_payment.save() # Return JSON to client return JsonResponse(payment.to_dict(), status=201) else: subject = "PayPal API error" message = "\n".join( "{key}: {value}".format(key=key, value=value) for key, value in payment.error.items() ) mail_admins(subject, message) log.error(payment.error) log.error(pprint.pformat(data)) if payment.error["name"] == "VALIDATION_ERROR": data = payment.error["details"] else: data = { "message": _( """Something went wrong with your PayPal payment. Please try again. If the problem persists, please contact us.""" ) } # Because we are returning a list of dicts, we must mark it as unsafe return JsonResponse(data, status=400, safe=False)