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, 'shop/checkout/empty_cart.html') return render(request, template) # Create a new order newOrder = Order(contact=contact) pay_ship_save(newOrder, tempCart, contact, shipping="", discount="", notes="") request.session['orderID'] = newOrder.id processor = get_processor_by_key('PAYMENT_AUTOSUCCESS') processor.prepare_data(newOrder) payment = processor.process(newOrder) tempCart.empty() 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, 'shop/checkout/empty_cart.html') return render_to_response(template, context_instance=RequestContext(request)) # Create a new order newOrder = Order(contact=contact) pay_ship_save(newOrder, tempCart, contact, shipping="", discount="", notes="") request.session['orderID'] = newOrder.id processor = get_processor_by_key('PAYMENT_AUTOSUCCESS') processor.prepare_data(newOrder) payment = processor.process(newOrder) tempCart.empty() success = lookup_url(payment_module, 'satchmo_checkout-success') return HttpResponseRedirect(success)
def simple_pay_ship_process_form(request, contact, working_cart, payment_module, allow_skip=True): 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: return (False, form) else: order_data = None try: order = Order.objects.from_request(request) if order.shipping_model: order_data = {} order_data['shipping'] = order.shipping_model ordershippable = order.is_shippable except Order.DoesNotExist: ordershippable = False form = SimplePayShipForm(request, payment_module, order_data) if allow_skip: skipping = False skipstep = form.shipping_hidden or not ordershippable or (len( form.shipping_dict) == 1) if skipstep: log.debug('Skipping pay ship, nothing to select for shipping') # no shipping choice = skip this step form.save(request, working_cart, contact, payment_module, data={'shipping': form.fields['shipping'].initial}) skipping = True elif not form.is_needed(): log.debug( 'Skipping pay ship because form is not needed, nothing to pay' ) form.save(request, working_cart, contact, None, data={'shipping': form.shipping_dict.keys()[0]}) skipping = True if skipping: url = lookup_url(payment_module, 'satchmo_checkout-step3') return (True, http.HttpResponseRedirect(url)) return (False, form)
def get_payment(request): payment_module = config_get_group('PAYMENT_PAYMENTSPRO') # get necessary order info from satchmo try: order = Order.objects.from_request(request) except Order.DoesNotExist: url = lookup_url(payment_module, 'satchmo_checkout-step1') return redirect(url) # now some context hacking: order_sub_total = order.sub_total + order.shipping_cost current_site = Site.objects.get_current().domain url = request.build_absolute_uri().split('?')[0] if settings.PAYPAL_CHECKOUT_SECURE: log.debug("secure paypal checkout") url = url.replace('http://', 'https://') log.debug("paypal express check out url: {0}".format(url)) #url = "http://" + current_site + reverse('PAYMENTSPRO_satchmo_checkout-step3') # === now the django-paypal stuff === # Fix of the 0.01 balance problem. # Bug: The payment amount sent to paypal, when formatted to two floating # points, was rounded, but the order.total is not. This would sometimes # cause a balance in 0 < balance < 0.01 which translated to a balance of # 0.01 to remain on the order. amt = "{0:.2f}".format(order.total) diff = order.total - Decimal(amt) if diff > Decimal("0") and diff < Decimal("0.01"): order.total = Decimal(amt) order.save() item = { "amt": amt, "invnum": order.id, "cancelurl": url, "returnurl": url, "currencycode": payment_module.CURRENCY_CODE.value, "paymentaction": "Authorization", } kw = { "item": item, "payment_form_cls": SatchmoPaymentsProPaymentForm, "payment_template": "shop/checkout/paymentspro/payment.html", "confirm_template": "shop/checkout/paymentspro/confirm.html", "success_url": lookup_url(payment_module, 'satchmo_checkout-success'), "context": {"order": order, "order_sub_total": order_sub_total }} ppp = PayPalPro(**kw) return ppp(request)
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) ssl = get_satchmo_setting('SSL', default_value=False) shopping_url = lookup_url(self.settings, 'satchmo_checkout-success', True, ssl) edit_url = lookup_url(self.settings, 'satchmo_cart', True, ssl) 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 pay_ship_info( request ): payment_module = coposweb # Copied from payship.base_pay_ship_info results = payship.pay_ship_info_verify( request, payment_module ) if not results[0]: return results[1] contact = results[1] working_cart = results[2] # Check if there's anything to pay try: order = Order.objects.from_request( request ) except Order.DoesNotExist: return HttpResponseRedirect( lookup_url( payment_module, 'satchmo_checkout-step1' ) ) if order.paid_in_full: form_handler = payship.simple_pay_ship_process_form template = 'shop/checkout/coposweb/pay_ship_free.html' else: form_handler = payship.credit_pay_ship_process_form template = 'shop/checkout/coposweb/pay_ship.html' results = form_handler( request, contact, working_cart, payment_module, allow_skip=False ) if results[0]: return results[1] form = results[1] return payship.pay_ship_render_form( request, form, template, payment_module, working_cart )
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 giftcert_pay_ship_process_form(request, contact, working_cart, payment_module, allow_skip): 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 gift_certificate = GiftCertificate.objects.get(code=data['giftcode'], valid=True, site=Site.objects.get_current()) # Check to see if the giftcertificate is not enough # If it isn't, then process it and prompt for next payment method if gift_certificate.balance < newOrder.balance: controller = confirm.ConfirmController(request, gc) controller.confirm() url = reverse('satchmo_balance_remaining') else: url = lookup_url(payment_module, 'satchmo_checkout-step3') return (True, http.HttpResponseRedirect(url)) else: form = GiftCertPayShipForm(request, payment_module) return (False, form)
def one_step(request): # First verify that the customer exists try: contact = Contact.objects.from_request(request, create=False) except Contact.DoesNotExist: url = lookup_url(payment_config, "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_config, "shop/checkout/empty_cart.html") return render_to_response(template, context_instance=RequestContext(request)) # Create a new order newOrder = Order(contact=contact) pay_ship_save(newOrder, tempCart, contact, shipping="", discount="", notes="") request.session["orderID"] = newOrder.id processor = get_processor_by_key("PAYMENT_REWARD_POINTS") processor.prepare_data(newOrder) processor_result = processor.process(newOrder) if processor_result.success: tempCart.empty() return success(request) else: return failure(request)
def _resolve_local_url(payment_module, cfgval, ssl=False): try: return lookup_url(payment_module, cfgval.value, include_server=True, ssl=ssl) except urlresolvers.NoReverseMatch: return cfgval.value
def __call__(self, request): #First verify that the customer exists try: contact = Contact.objects.from_request(request, create=False) except Contact.DoesNotExist: url = lookup_url(self.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( self.payment_module, 'shop/checkout/empty_cart.html' ) return render_to_response( template, context_instance=RequestContext(request) ) data = {} if request.method == 'POST': data['discount'] = request.post.get('discount_code') success = lookup_url( self.payment_module, '%s_satchmo_checkout-success' % self.processor.key, ) order = get_or_create_order(request, tempCart, contact, data) self.preprocess_order(order) # Add status order.add_status('New', _("Payment needs to be confirmed")) # Process payment self.processor.prepare_data(order) self.processor.process(order) tempCart.empty() self.postprocess_order(order) order.save() return HttpResponseRedirect(success)
def simple_pay_ship_process_form(request, contact, working_cart, payment_module, allow_skip=True): 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: return (False, form) else: order_data = None try: order = Order.objects.from_request(request) if order.shipping_model: order_data = {} order_data['shipping'] = order.shipping_model ordershippable = order.is_shippable except Order.DoesNotExist: pass form = SimplePayShipForm(request, payment_module, order_data) if allow_skip: skipping = False skipstep = form.shipping_hidden or not ordershippable or (len(form.shipping_dict) == 1) if skipstep: log.debug('Skipping pay ship, nothing to select for shipping') # no shipping choice = skip this step form.save(request, working_cart, contact, payment_module, data={'shipping' : form.fields['shipping'].initial}) skipping = True elif not form.is_needed(): log.debug('Skipping pay ship because form is not needed, nothing to pay') form.save(request, working_cart, contact, None, data={'shipping' : form.shipping_dict.keys()[0]}) skipping = True if skipping: url = lookup_url(payment_module, 'satchmo_checkout-step3') return (True, http.HttpResponseRedirect(url)) return (False, form)
def stripe_pay_ship_process_form(request, contact, working_cart, payment_module, allow_skip=True, *args, **kwargs): def _get_form(request, payment_module, *args, **kwargs): return StripePayShipForm(request, payment_module, *args, **kwargs) if request.method == "POST": new_data = request.POST.copy() #if using saved card, fill in the stripe token field with the customer_id if not new_data['stripe_token'] and new_data['use_saved_cc']: new_data['stripe_token'] = utils.check_stripe_customer(threadlocals.get_current_user()) form = _get_form(request, payment_module, new_data, *args, **kwargs) if form.is_valid(): data = form.cleaned_data form.save(request, working_cart, contact, payment_module, data=data) url = lookup_url(payment_module, 'satchmo_checkout-step3') return (True, http.HttpResponseRedirect(url)) else: log.info('Form didn\'t pass!!!!') for error in form.errors: log.info(error) pass else: order_data = {} try: order = Order.objects.from_request(request) if order.shipping_model: order_data['shipping'] = order.shipping_model kwargs['initial'] = order_data ordershippable = order.is_shippable except Order.DoesNotExist: pass form = _get_form(request, payment_module, *args, **kwargs) if not form.is_needed(): form.save(request, working_cart, contact, None, data={'shipping': form.shipping_dict.keys()[0]}) url = lookup_url(payment_module, 'satchmo_checkout-step3') return (True, http.HttpResponseRedirect(url)) return (False, form)
def confirm_info(request): payment_module = config_get_group('PAYMENT_OGONE') 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 and not order.is_partially_paid: template = lookup_template(payment_module, 'shop/checkout/empty_cart.html') return render_to_response(template, context_instance=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_instance=context) template = lookup_template(payment_module, 'shop/checkout/ogone/confirm.html') processor_module = payment_module.MODULE.load_module('processor') processor = processor_module.PaymentProcessor(payment_module) pending_payment = processor.create_pending_payment(order=order) payment = pending_payment.capture log.debug('Creating payment %s for order %s', payment, order) success_url = reverse_full_url('OGONE_satchmo_checkout-success') failure_url = reverse_full_url('OGONE_satchmo_checkout-failure') homeurl = reverse_full_url('satchmo_shop_home') catalogurl = reverse_full_url('satchmo_category_index') # Get Ogone settings from Satchmo settings = get_ogone_settings() context = get_ogone_request(payment, settings, accepturl=success_url, cancelurl=failure_url, declineurl=failure_url, exceptionurl=failure_url, homeurl=homeurl, catalogurl=catalogurl, language=getattr(request, 'LANGUAGE_CODE', 'en_US')) context.update({'order': order}) return render_to_response(template, context, RequestContext(request))
def __call__(self, request): #First verify that the customer exists try: contact = Contact.objects.from_request(request, create=False) except Contact.DoesNotExist: url = lookup_url(self.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(self.payment_module, 'shop/checkout/empty_cart.html') return render_to_response(template, context_instance=RequestContext(request)) data = {} if request.method == 'POST': data['discount'] = request.post.get('discount_code') success = lookup_url( self.payment_module, '%s_satchmo_checkout-success' % self.processor.key, ) order = get_or_create_order(request, tempCart, contact, data) self.preprocess_order(order) # Add status order.add_status('New', _("Payment needs to be confirmed")) # Process payment self.processor.prepare_data(order) self.processor.process(order) tempCart.empty() self.postprocess_order(order) order.save() return HttpResponseRedirect(success)
def stripe_pay_ship_process_form(request, contact, working_cart, payment_module, allow_skip=True, *args, **kwargs): def _get_form(request, payment_module, *args, **kwargs): return StripePayShipForm(request, payment_module, *args, **kwargs) if request.method == "POST": new_data = request.POST.copy() form = _get_form(request, payment_module, new_data, *args, **kwargs) if form.is_valid(): data = form.cleaned_data form.save(request, working_cart, contact, payment_module, data=data) url = lookup_url(payment_module, 'satchmo_checkout-step3') return (True, http.HttpResponseRedirect(url)) else: pass else: order_data = {} try: order = Order.objects.from_request(request) if order.shipping_model: order_data['shipping'] = order.shipping_model if order.credit_card: # check if valid token pass kwargs['initial'] = order_data ordershippable = order.is_shippable except Order.DoesNotExist: pass form = _get_form(request, payment_module, *args, **kwargs) if not form.is_needed(): form.save(request, working_cart, contact, None, data={'shipping', form.shipping_dict.keys()[0]}) url = lookup_url(payment_module, 'satchmo_checkout-step3') return (True, http.HttpResponseRedirect(url)) return (False, form)
def purchaseorder_process_form(request, contact, working_cart, payment_module, allow_skip): 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 confirm_info(request): 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, 'shop/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, 'shop/checkout/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 form_valid(self, form): contact = self.get_contact() new_data = self.request.POST.copy() tempCart = self.get_cart() if contact is None and self.request.user \ and self.request.user.is_authenticated(): contact = Contact(user=self.request.user) custID = form.save(self.request, cart=tempCart, contact=contact) self.request.session[CUSTOMER_ID] = custID modulename = new_data['paymentmethod'] if not modulename.startswith('PAYMENT_'): modulename = 'PAYMENT_' + modulename paymentmodule = config_get_group(modulename) url = lookup_url(paymentmodule, 'satchmo_checkout-step2') self._success_url = url return super(CheckoutForm, self).form_valid(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, 'shop/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, 'shop/checkout/empty_cart.html') return (False, render(request, template)) return (True, contact, tempCart)
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 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) else: form = SimplePayShipForm(request, payment_module) if config_value('PAYMENT','USE_DISCOUNTS') or not form.shipping_hidden: return (False, form) else: # No discounts, no shipping choice = skip this step order = get_or_create_order( request, working_cart, contact, {'shipping': form.fields['shipping'].initial, 'discount': ''} ) processor_module = payment_module.MODULE.load_module('processor') processor = processor_module.PaymentProcessor(payment_module) orderpayment = processor.create_pending_payment(order=order) url = lookup_url(payment_module, 'satchmo_checkout-step3') return (True, http.HttpResponseRedirect(url))
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(data=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(active_gateways()) }) return render_to_response('shop/checkout/balance_remaining.html', context_instance=ctx)
def giftcert_pay_ship_process_form(request, contact, working_cart, gateway_settings): if request.method == "POST": new_data = request.POST.copy() form = GiftCertPayShipForm(request, gateway_settings, 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(gateway_settings, 'satchmo_checkout-step3') return (True, http.HttpResponseRedirect(url)) else: form = GiftCertPayShipForm(request, gateway_settings) return (False, form)
def confirm_info(request): 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 and not order.is_partially_paid: template = lookup_template(payment_module, 'shop/checkout/empty_cart.html') return render_to_response(template, context_instance=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_instance=context) # from here on just setting and calling variables template = lookup_template(payment_module, 'shop/checkout/paysbuy/confirm.html') if payment_module.LIVE.value: log.debug("live order on %s", payment_module.KEY.value) url = payment_module.CONNECTION.value psb = payment_module.PSB.value account = payment_module.BIZ.value secure_code = payment_module.SECURE_CODE.value else: url = payment_module.CONNECTION_TEST.value psb = payment_module.PSB_TEST.value account = payment_module.BIZ_TEST.value secure_code = payment_module.SECURE_CODE_TEST.value try: address = lookup_url(payment_module, payment_module.FRONT_URL.value, include_server=True) except urlresolvers.NoReverseMatch: address = payment_module.FRONT_URL.value try: cart = Cart.objects.from_request(request) except: cart = None try: contact = Contact.objects.from_request(request) except: contact = None if cart and contact: cart.customer = contact log.debug(':::Updating Cart %s for %s' % (cart, contact)) cart.save() if payment_module.OPT_FIX_REDIRECT.value: opt_fix_redirect = '1' else: opt_fix_redirect = '' if payment_module.OPT_FIX_METHOD.value: opt_fix_method = '1' else: opt_fix_method = '' total_plus_tax = 0 for o in order.orderitem_set.all(): total_plus_tax = total_plus_tax + o.total_with_tax processor_module = payment_module.MODULE.load_module('processor') processor = processor_module.PaymentProcessor(payment_module) processor.create_pending_payment(order=order) ship_tax_total = total_plus_tax + order.shipping_cost psb_post_out_dict = { 'order': order, 'post_url': url, 'psb': psb[:10], 'biz': account[:200], 'secure_code': secure_code[:200], 'amount': ship_tax_total, 'paypal': ""[:2], 'commission': payment_module.COMMISSION_CODE.value[:200], 'default_pay_method': payment_module.PAY_METHOD.value[:1], 'currencyCode': payment_module.CURRENCY_CODE.value, 'lang': payment_module.LANGUAGE.value[:1], 'postURL': address[:500], 'reqURL': payment_module.BACK_URL.value[:500], 'opt_fix_redirect': opt_fix_redirect[:1], 'opt_fix_method': opt_fix_method[:1], 'opt_name': contact.full_name[:200], 'opt_email': contact.email[:200], 'opt_mobile': str(contact.primary_phone)[:200], 'opt_address': str(contact.shipping_address)[:200], 'opt_detail': ""[:200], 'invoice': str(order.id)[:200], 'itm': "Thailand Furniture Purchase"[:200], 'PAYMENT_LIVE': payment_module.LIVE.value, 'OrderPaidInFull': order.paid_in_full, } ctx = RequestContext(request, psb_post_out_dict) if not payment_module.LIVE.value: if order.notes: admin_notes = order.notes + u'\n' else: admin_notes = "" order.notes = admin_notes + 'TEST' + u'\n' order.add_status(status='New', notes=_("Payment sent to Paysbuy.")) order.save() if not payment_module.LIVE.value or payment_module.EXTRA_LOGGING.value: custom_logger(psb_post_out_dict, '%s/psb-confirm_info.log' % payment_module.PSB_LOGS_DIR) return render_to_response(template, context_instance=ctx)
def lookup_url(self, view): """Shortcut method to the the proper url from the `paymentModule`""" return lookup_url(self.paymentModule, view)
def confirm_info(request): payment_module = config_get_group('PAYMENT_SERMEPA') 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, 'shop/checkout/empty_cart.html') return render(request, template) # Check if the order is still valid if not order.validate(request): return render(request, 'shop/404.html', {'message': _('Your order is no longer valid.')}) # Check if we are in test or real mode live = payment_module.LIVE.value if live: post_url = payment_module.POST_URL.value signature_code = payment_module.MERCHANT_SIGNATURE_CODE.value terminal = payment_module.MERCHANT_TERMINAL.value else: post_url = payment_module.POST_TEST_URL.value signature_code = payment_module.MERCHANT_TEST_SIGNATURE_CODE.value terminal = payment_module.MERCHANT_TEST_TERMINAL.value # SERMEPA system does not accept multiple payment attempts with the same ID, even # if the previous one has never been finished. The worse is that it does not display # any message which could be understood by an end user. # # If user goes to SERMEPA page and clicks 'back' button (e.g. to correct contact data), # the next payment attempt will be rejected. # # To provide higher probability of ID uniqueness, we add mm:ss timestamp part # to the order id, separated by 'T' character in the following way: # # ID: oooooooTmmss # c: 123456789012 # # The Satchmo's Order number is therefore limited to 10 million - 1. now = timezone.now() xchg_order_id = "%07dT%02d%02d" % (order.id, now.minute, now.second) amount = "%d" % (order.balance * 100,) # in cents template = lookup_template(payment_module, 'shop/checkout/sermepa/confirm.html') url_callback = _resolve_local_url(payment_module, payment_module.MERCHANT_URL_CALLBACK, ssl=get_satchmo_setting('SSL')) url_ok = _resolve_local_url(payment_module, payment_module.MERCHANT_URL_OK) url_ko = _resolve_local_url(payment_module, payment_module.MERCHANT_URL_KO) if payment_module.EXTENDED_SIGNATURE.value: signature_data = ''.join( map(str, ( amount, xchg_order_id, payment_module.MERCHANT_FUC.value, payment_module.MERCHANT_CURRENCY.value, "0", #TransactionType url_callback, signature_code, ) ) ) else: signature_data = ''.join( map(str, ( amount, xchg_order_id, payment_module.MERCHANT_FUC.value, payment_module.MERCHANT_CURRENCY.value, signature_code, ) ) ) signature = sha1(signature_data).hexdigest() ctx = { 'live': live, 'post_url': post_url, 'MERCHANT_CURRENCY': payment_module.MERCHANT_CURRENCY.value, 'MERCHANT_FUC': payment_module.MERCHANT_FUC.value, 'terminal': terminal, 'MERCHANT_TITULAR': payment_module.MERCHANT_TITULAR.value, 'url_callback': url_callback, 'url_ok': url_ok, 'url_ko': url_ko, 'order': order, 'xchg_order_id' : xchg_order_id, 'amount': amount, 'signature': signature, 'default_view_tax': config_value('TAX', 'DEFAULT_VIEW_TAX'), } return render(request, template, ctx)
def confirm_info(request): payment_module = config_get_group('PAYMENT_CREDITCARD') 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 and not order.is_partially_paid: template = lookup_template( payment_module, 'shop/checkout/empty_cart.html' ) return render_to_response(template, context_instance=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_instance=context) template = lookup_template( payment_module, 'shop/checkout/creditcard/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.MERCHANT_ID.value else: url = payment_module.POST_TEST_URL.value account = payment_module.MERCHANT_TEST_ID.value try: address = lookup_url(payment_module, payment_module.RETURN_ADDRESS.value, include_server=True) except urlresolvers.NoReverseMatch: address = payment_module.RETURN_ADDRESS.value processor_module = payment_module.MODULE.load_module('processor') processor = processor_module.PaymentProcessor(payment_module) processor.create_pending_payment(order=order) 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.quantize(Decimal('.01')) } 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] 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 gpc = GestPayCrypt() gpc.SetShopLogin(account) gpc.SetShopTransactionID(str(order.id)) gpc.SetAmount("%.2f" % order.total) a = gpc.GetShopLogin() b = '' if gpc.Encrypt() == None: print "Authorization Failed" else: b = gpc.GetEncryptedString() encrypt = url params = "?a=%s&b=%s" % (a, b) url = "%s%s" % (encrypt, params) 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' : gateway_live(payment_module) }) return render_to_response(template, context_instance=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 confirm_info(request): payment_module = config_get_group('PAYMENT_PAGOSONLINE') try: order = Order.objects.from_request(request) get_buyer_email = Contact.objects.filter(id=order.contact_id) 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, 'shop/checkout/empty_cart.html') return render_to_response(template, context_instance=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_instance=context) # Check if we are in test or real mode live = payment_module.LIVE.value if live: post_url = payment_module.POST_URL.value prueba = 0 else: post_url = payment_module.POST_TEST_URL.value prueba = 1 # # PAGOSONLINE system does not accept multiple payment attempts with the same refVenta, even # if the previous one has never been finished. The worse is that it does not display # any message which could be understood by an end user. # # If user goes to PAGOSONLINE page and clicks 'back' button (e.g. to correct contact data), # the next payment attempt will be rejected. # # To provide higher probability of refVenta uniqueness, we add YYYY:DD:MM:hh:mm:ss timestamp part # to the order id, separated by 'T' character in the following way: # # refVenta: xxxxxxxTYYYYDDMMHHMMSS # now = datetime.now() xchg_order_id = "%dT%04d%02d%02d%02d%02d%02d" % (order.id, now.year, now.day, now.month, now.hour, now.minute, now.second) signature_code = payment_module.MERCHANT_SIGNATURE_CODE.value userId = payment_module.MERCHANT_USERID_CODE.value amount = "%.2f" % order.balance log.debug("Amount for confirm Info %s" % amount) coin = payment_module.MERCHANT_CURRENCY.value signature_data = '~'.join( map(str, ( signature_code, userId, xchg_order_id, amount, coin, ))) try: cartnumber = request.session['cart'] except KeyError: log.debug("No cart number found %s", request.session) signature=md5(signature_data).hexdigest() template = lookup_template(payment_module, 'shop/checkout/pagosonline/confirm.html') url_callback = _resolve_local_url(payment_module, payment_module.MERCHANT_URL_CALLBACK, ssl=get_satchmo_setting('SSL')) url_ans = _resolve_local_url(payment_module, payment_module.MERCHANT_URL_OK) # url_ko = _resolve_local_url(payment_module, payment_module.MERCHANT_URL_KO) try: request.user.email emailComprador = request.user.email except: emailComprador = get_buyer_email[0].email float_balance = float(order.balance) no_iva = float_balance/1.16 iva = round(0.16*no_iva,2) log.debug("IVA = %f" % iva) ctx = { 'live': live, 'post_url': post_url, 'coin': payment_module.MERCHANT_CURRENCY.value, 'url_callback': url_callback, 'url_ans': url_ans, 'usuarioId': userId, 'order': order, 'xchg_order_id': xchg_order_id, 'amount': amount, 'iva': iva, 'signature': signature, 'prueba': prueba, 'emailComprador': emailComprador, 'default_view_tax': config_value('TAX', 'DEFAULT_VIEW_TAX'), } log.debug(ctx) return render_to_response(template, ctx, context_instance=RequestContext(request))
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, "shop/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, "shop/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 processor_module = payment_module.MODULE.load_module("processor") processor = processor_module.PaymentProcessor(payment_module) processor.create_pending_payment(order=order) 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): payment_module = config_get_group('PAYMENT_CONCARDIS') 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 and not order.is_partially_paid: template = lookup_template(payment_module, 'shop/checkout/empty_cart.html') return render(request, template) # Check if the order is still valid if not order.validate(request): return render(request, 'shop/404.html', {'message': _('Your order is no longer valid.')}) # Make sure the order has an ORDER_ID try: order_id = order.get_variable('ORDER_ID').value except AttributeError: order_id = _get_order_id() order.add_variable('ORDER_ID', order_id) template = lookup_template(payment_module, 'shop/checkout/concardis/confirm.html') if payment_module.LIVE.value: log.debug("live order on %s", payment_module.KEY.value) url = payment_module.POST_URL.value else: url = payment_module.POST_TEST_URL.value try: address = lookup_url(payment_module, payment_module.RETURN_ADDRESS.value, include_server=True) except urlresolvers.NoReverseMatch: address = payment_module.RETURN_ADDRESS.value try: cart = Cart.objects.from_request(request) except: # pylint: disable=bare-except cart = None try: contact = Contact.objects.from_request(request) except: # pylint: disable=bare-except contact = None if cart and contact: cart.customer = contact log.debug(':::Updating Cart %s for %s', cart, contact) cart.save() processor_module = payment_module.MODULE.load_module('processor') processor = processor_module.PaymentProcessor(payment_module) processor.create_pending_payment(order=order) default_view_tax = config_value('TAX', 'DEFAULT_VIEW_TAX') recurring = None passphrase = payment_module.SHA_IN_PASSPHRASE.value address_b = order.contact.billing_address # Add return URLs accept_url = 'https://{}{}'.format( settings.SITE_DOMAIN, reverse('CONCARDIS_satchmo_checkout-success'), ) params = OrderedDict(( ('ACCEPTURL', accept_url), ('AMOUNT', int(order.balance * 100)), # Amount without decimals ('CN', order.contact.first_name + ' ' + order.contact.last_name), ('CURRENCY', payment_module.CURRENCY_CODE.value), ('EMAIL', order.contact.email), ('OPERATION', 'SAL'), # Set payment to direct sale ('ORDERID', order_id), ('OWNERADDRESS', ' '.join([address_b.street1, address_b.street2])), ('OWNERCTY', address_b.country.iso2_code), ('OWNERTOWN', address_b.city), ('OWNERZIP', address_b.postal_code), ('PARAMVAR', settings.SHORT_NAME), # Used to identify site in callbacks ('PSPID', payment_module.PSPID.value), )) # Create a sha1 digest of the parameters params['SHASIGN'] = sha1_sign(params, passphrase) # Make sure params are sorted alphabetically params = OrderedDict(sorted(params.items(), key=lambda t: t[0])) return render( request, template, { 'order': order, 'post_url': url, 'default_view_tax': default_view_tax, 'return_address': address, 'subscription': recurring, 'PAYMENT_LIVE': gateway_live(payment_module), 'params': params, })
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('shop/checkout/empty_cart.html', context_instance=RequestContext(request)) if not request.user.is_authenticated() and config_value('SHOP', '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 # -arthur- #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 try: order = Order.objects.from_request(request) if order.discount_code: init_data['discount'] = order.discount_code except Order.DoesNotExist: pass if request.method == "POST": new_data = request.POST.copy() if not tempCart.is_shippable: new_data['copy_address'] = True form = PaymentContactInfoForm(data=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(request, cart=tempCart, contact=contact) request.session[CUSTOMER_ID] = custID 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) # -arthur- #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 else: # Allow them to login from this page. request.session.set_test_cookie() #Request additional init_data form_initialdata.send(sender=PaymentContactInfoForm, initial=init_data, contact=contact, cart=tempCart, shop=shop) 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('shop/checkout/form.html', context_instance=context)
def credit_pay_ship_process_form(request, contact, working_cart, payment_module, allow_skip=True, *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(): data = form.cleaned_data form.save(request, working_cart, contact, payment_module, data=data) url = lookup_url(payment_module, 'satchmo_checkout-step3') return (True, http.HttpResponseRedirect(url)) else: log.debug('Form errors: %s', form.errors) else: order_data = {} try: order = Order.objects.from_request(request) if order.shipping_model: order_data['shipping'] = order.shipping_model if order.credit_card: cc = order.credit_card val = cc.decryptedCC if val: order_data['credit_number'] = val val = cc.ccv if val: order_data['ccv'] = val val = cc.expire_month if val: order_data['month_expires'] = val val = cc.expire_year if val: order_data['year_expires'] = val val = cc.credit_type if val: order_data['credit_type'] = val kwargs['initial'] = order_data ordershippable = order.is_shippable except Order.DoesNotExist: pass form = _get_form(request, payment_module, *args, **kwargs) if not form.is_needed(): log.debug('Skipping pay ship because form is not needed, nothing to pay') form.save(request, working_cart, contact, None, data={'shipping' : form.shipping_dict.keys()[0]}) url = lookup_url(payment_module, 'satchmo_checkout-step3') return (True, http.HttpResponseRedirect(url)) return (False, form)
def confirm_info(request): payment_module = config_get_group('PAYMENT_SERMEPA') 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, 'shop/checkout/empty_cart.html') return render_to_response(template, context_instance=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_instance=context) # Check if we are in test or real mode live = payment_module.LIVE.value if live: post_url = payment_module.POST_URL.value signature_code = payment_module.MERCHANT_SIGNATURE_CODE.value terminal = payment_module.MERCHANT_TERMINAL.value else: post_url = payment_module.POST_TEST_URL.value signature_code = payment_module.MERCHANT_TEST_SIGNATURE_CODE.value terminal = payment_module.MERCHANT_TEST_TERMINAL.value # SERMEPA system does not accept multiple payment attempts with the same ID, even # if the previous one has never been finished. The worse is that it does not display # any message which could be understood by an end user. # # If user goes to SERMEPA page and clicks 'back' button (e.g. to correct contact data), # the next payment attempt will be rejected. # # To provide higher probability of ID uniqueness, we add mm:ss timestamp part # to the order id, separated by 'T' character in the following way: # # ID: oooooooTmmss # c: 123456789012 # # The Satchmo's Order number is therefore limited to 10 million - 1. now = datetime.now() xchg_order_id = "%07dT%02d%02d" % (order.id, now.minute, now.second) amount = "%d" % (order.balance * 100,) # in cents template = lookup_template(payment_module, 'shop/checkout/sermepa/confirm.html') url_callback = _resolve_local_url(payment_module, payment_module.MERCHANT_URL_CALLBACK, ssl=get_satchmo_setting('SSL')) url_ok = _resolve_local_url(payment_module, payment_module.MERCHANT_URL_OK) url_ko = _resolve_local_url(payment_module, payment_module.MERCHANT_URL_KO) if payment_module.EXTENDED_SIGNATURE.value: signature_data = ''.join( map(str, ( amount, xchg_order_id, payment_module.MERCHANT_FUC.value, payment_module.MERCHANT_CURRENCY.value, "0", #TransactionType url_callback, signature_code, ) ) ) else: signature_data = ''.join( map(str, ( amount, xchg_order_id, payment_module.MERCHANT_FUC.value, payment_module.MERCHANT_CURRENCY.value, signature_code, ) ) ) signature = sha1(signature_data).hexdigest() ctx = { 'live': live, 'post_url': post_url, 'MERCHANT_CURRENCY': payment_module.MERCHANT_CURRENCY.value, 'MERCHANT_FUC': payment_module.MERCHANT_FUC.value, 'terminal': terminal, 'MERCHANT_TITULAR': payment_module.MERCHANT_TITULAR.value, 'url_callback': url_callback, 'url_ok': url_ok, 'url_ko': url_ko, 'order': order, 'xchg_order_id' : xchg_order_id, 'amount': amount, 'signature': signature, 'default_view_tax': config_value('TAX', 'DEFAULT_VIEW_TAX'), } return render_to_response(template, ctx, context_instance=RequestContext(request))
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 and not order.is_partially_paid: template = lookup_template(payment_module, 'shop/checkout/empty_cart.html') return render_to_response(template, context_instance=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_instance=context) template = lookup_template(payment_module, 'shop/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 try: cart = Cart.objects.from_request(request) except: cart = None try: contact = Contact.objects.from_request(request) except: contact = None if cart and contact: cart.customer = contact log.debug(':::Updating Cart %s for %s' % (cart, contact)) cart.save() processor_module = payment_module.MODULE.load_module('processor') processor = processor_module.PaymentProcessor(payment_module) processor.create_pending_payment(order=order) default_view_tax = config_value('TAX', 'DEFAULT_VIEW_TAX') recurring = None # Run only if subscription products are installed if 'product.modules.subscription' in settings.INSTALLED_APPS: order_items = order.orderitem_set.all() for item in order_items: if not item.product.is_subscription: continue if item.product.has_variants: price = item.product.productvariation.get_qty_price(item.quantity, True) else: price = item.product.get_qty_price(item.quantity, True) recurring = {'product':item.product, 'price':price.quantize(Decimal('.01'))} 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.subscription.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.subscription.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' : gateway_live(payment_module) }) return render_to_response(template, context_instance=ctx)
def credit_pay_ship_process_form(request, contact, working_cart, payment_module, allow_skip=True, *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(): data = form.cleaned_data form.save(request, working_cart, contact, payment_module, data=data) url = lookup_url(payment_module, 'satchmo_checkout-step3') return (True, http.HttpResponseRedirect(url)) else: log.debug('Form errors: %s', form.errors) else: order_data = {} try: order = Order.objects.from_request(request) if order.shipping_model: order_data['shipping'] = order.shipping_model if order.credit_card: cc = order.credit_card val = cc.decryptedCC if val: order_data['credit_number'] = val val = cc.ccv if val: order_data['ccv'] = val val = cc.expire_month if val: order_data['month_expires'] = val val = cc.expire_year if val: order_data['year_expires'] = val val = cc.credit_type if val: order_data['credit_type'] = val kwargs['initial'] = order_data ordershippable = order.is_shippable except Order.DoesNotExist: pass form = _get_form(request, payment_module, *args, **kwargs) if not form.is_needed(): log.debug( 'Skipping pay ship because form is not needed, nothing to pay') form.save(request, working_cart, contact, None, data={'shipping': form.shipping_dict.keys()[0]}) url = lookup_url(payment_module, 'satchmo_checkout-step3') return (True, http.HttpResponseRedirect(url)) return (False, form)
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 and not order.is_partially_paid: template = lookup_template(payment_module, 'shop/checkout/empty_cart.html') return render_to_response(template, context_instance=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_instance=context) template = lookup_template(payment_module, 'shop/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 try: cart = Cart.objects.from_request(request) except: cart = None try: contact = Contact.objects.from_request(request) except: contact = None if cart and contact: cart.customer = contact log.debug(':::Updating Cart %s for %s' % (cart, contact)) cart.save() processor_module = payment_module.MODULE.load_module('processor') processor = processor_module.PaymentProcessor(payment_module) processor.create_pending_payment(order=order) default_view_tax = config_value('TAX', 'DEFAULT_VIEW_TAX') recurring = None # Run only if subscription products are installed if 'product.modules.subscription' in settings.INSTALLED_APPS: order_items = order.orderitem_set.all() for item in order_items: if not item.product.is_subscription: continue if item.product.has_variants: price = item.product.productvariation.get_qty_price( item.quantity, True) else: price = item.product.get_qty_price(item.quantity, True) recurring = { 'product': item.product, 'price': price.quantize(Decimal('.01')) } 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.subscription.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.subscription.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': gateway_live(payment_module) }) return render_to_response(template, context_instance=ctx)
def confirm_info(request): payment_module = config_get_group("PAYMENT_SERMEPA") 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, "shop/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) # Check if we are in test or real mode live = payment_module.LIVE.value if live: post_url = payment_module.POST_URL.value signature_code = payment_module.MERCHANT_SIGNATURE_CODE.value terminal = payment_module.MERCHANT_TERMINAL.value else: post_url = payment_module.POST_TEST_URL.value signature_code = payment_module.MERCHANT_TEST_SIGNATURE_CODE.value terminal = payment_module.MERCHANT_TEST_TERMINAL.value # SERMEPA system does not accept multiple payment attempts with the same ID, even # if the previous one has never been finished. The worse is that it does not display # any message which could be understood by an end user. # # If user goes to SERMEPA page and clicks 'back' button (e.g. to correct contact data), # the next payment attempt will be rejected. # # To provide higher probability of ID uniqueness, we add mm:ss timestamp part # to the order id, separated by 'T' character in the following way: # # ID: oooooooTmmss # c: 123456789012 # # The Satchmo's Order number is therefore limited to 10 million - 1. now = datetime.now() xchg_order_id = "%07dT%02d%02d" % (order.id, now.minute, now.second) amount = "%d" % (order.balance * 100,) # in cents signature_data = "".join( map( str, ( amount, xchg_order_id, payment_module.MERCHANT_FUC.value, payment_module.MERCHANT_CURRENCY.value, signature_code, ), ) ) signature = sha1(signature_data).hexdigest() template = lookup_template(payment_module, "shop/checkout/sermepa/confirm.html") url_callback = _resolve_local_url( payment_module, payment_module.MERCHANT_URL_CALLBACK, ssl=payment_module.SSL.value ) url_ok = _resolve_local_url(payment_module, payment_module.MERCHANT_URL_OK) url_ko = _resolve_local_url(payment_module, payment_module.MERCHANT_URL_KO) ctx = { "live": live, "post_url": post_url, "MERCHANT_CURRENCY": payment_module.MERCHANT_CURRENCY.value, "MERCHANT_FUC": payment_module.MERCHANT_FUC.value, "terminal": terminal, "MERCHANT_TITULAR": payment_module.MERCHANT_TITULAR.value, "url_callback": url_callback, "url_ok": url_ok, "url_ko": url_ko, "order": order, "xchg_order_id": xchg_order_id, "amount": amount, "signature": signature, "default_view_tax": config_value("TAX", "DEFAULT_VIEW_TAX"), } return render_to_response(template, ctx, context_instance=RequestContext(request))
def confirm_info(request): shop = Config.objects.get_current() payment_module = config_get_group('PAYMENT_PAYBOX') try: order = Order.objects.from_request(request) except Order.DoesNotExist: url = lookup_url(payment_module, 'satchmo_checkout-step1') return HttpResponseRedirect(url) log.debug(order) tempCart = Cart.objects.from_request(request) if tempCart.numItems == 0: template = lookup_template(payment_module, 'shop/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_instance=context) template = lookup_template(payment_module, 'shop/checkout/paybox/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.ID.value bksite = payment_module.SITE.value rank = payment_module.RANK.value else: url = payment_module.POST_TEST_URL.value account = payment_module.ID_TEST.value bksite = payment_module.SITE_TEST.value rank = payment_module.RANK_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 processor_module = payment_module.MODULE.load_module('processor') processor = processor_module.PaymentProcessor(payment_module) processor.create_pending_payment(order=order) # Tax default_view_tax = config_value('TAX', 'DEFAULT_VIEW_TAX') amount=order.balance # use external sw for creation of the form (and notification of payment on paybox platform) log.debug("To be payed : %s", amount) # ./modulev3.cgi PBX_MODE=4 PBX_SITE=1999888 binprog = payment_module.BIN_PROG_FULLPATH.value args=[binprog,] args.append('PBX_MODE=4') args.append('PBX_SITE=%s'%bksite) args.append('PBX_RANG=%s'%rank) args.append('PBX_IDENTIFIANT=%s'%account) args.append('PBX_TOTAL=%d'%(int(amount*100))) args.append('PBX_CMD=%s'%order.id) args.append('PBX_PORTEUR=%s'%order.contact.email) args.append('PBX_DEVISE=%s'%PBX_DEVISES_ISO_4217['EUR']) if request.LANGUAGE_CODE=='fr': pbx_country_code='FRA' elif request.LANGUAGE_CODE=='es': pbx_country_code='ESP' elif request.LANGUAGE_CODE=='it': pbx_country_code='ITA' elif request.LANGUAGE_CODE=='de': pbx_country_code='DEU' elif request.LANGUAGE_CODE=='nl': pbx_country_code='NLD' else: pbx_country_code='GBR' args.append('PBX_LANGUE=%s'%pbx_country_code) args.append('PBX_RETOUR=amount:M;ref:R;autho:A;trans:T;type:P;card:C;idtrans:S;country:Y;error:E;valid:D;IP:I;BIN6:N;last2:J;tstmp:W;dgst:H;sign:K') args.append('PBX_OUTPUT=C') returl = lookup_url(payment_module,payment_module.RETURN_ADDRESS.value) args.append('PBX_EFFECTUE=%s%s'%(shop.base_url,returl)) returl = lookup_url(payment_module,payment_module.FAILURE_ADDRESS.value) args.append('PBX_REFUSE=%s%s'%(shop.base_url,returl)) returl = lookup_url(payment_module,payment_module.CANCELLED_ADDRESS.value) args.append('PBX_ANNULE=%s%s'%(shop.base_url,returl)) # Url directly called by paybox servers : in test mode, need to be specified if not payment_module.LIVE.value: http_callback_url = lookup_url(payment_module,'PAYBOX_satchmo_checkout-cb') args.append('PBX_REPONDRE_A=%s%s'%(shop.base_url,http_callback_url)) if not payment_module.LIVE.value: args.append('PBX_PAYBOX=%s' % url) args.append('PBX_BACKUP1=%s' % url) args.append('PBX_BACKUP2=%s' % url) log.debug("Arguments : %s ", str(args)) # Finish form footer_start = "<br /><div class='wide acenter'><input style='font-size:10px;' type='SUBMIT' value='" footer_end = "' /></div> </FORM>" value = _('Pay') footer = '%s%s%s'%(footer_start,value,footer_end) # footer= "<br /><INPUT CLASS='button' style='height:22px;font-size:10px;' TYPE='SUBMIT' VALUE='Payer' /> </FORM>" formstr = mark_safe("%s %s" % (Popen(args, stdout=PIPE).communicate()[0], footer ) ) log.debug("form proposed by bin : %s", str(formstr)) # No support for subscription. ctx = RequestContext( request, {'order': order, 'default_view_tax': default_view_tax, 'post_url': url, 'account': account, 'site' : bksite, 'rank' : rank, 'currency_code': 'EUR', 'return_address': address, 'invoice': order.id, 'PAYMENT_LIVE' : gateway_live(payment_module), 'formstr':formstr }) return render_to_response(template, context_instance=ctx)
def confirm_info(request): payment_module = config_get_group('PAYMENT_PAGSEGURO') 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 and not order.is_partially_paid: template = lookup_template(payment_module, 'shop/checkout/empty_cart.html') return render_to_response(template, context_instance=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_instance=context) template = lookup_template(payment_module, 'shop/checkout/pagseguro/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 try: cart = Cart.objects.from_request(request) except: cart = None try: contact = Contact.objects.from_request(request) except: contact = None if cart and contact: cart.customer = contact log.debug(':::Updating Cart %s for %s' % (cart, contact)) cart.save() processor_module = payment_module.MODULE.load_module('processor') processor = processor_module.PaymentProcessor(payment_module) processor.create_pending_payment(order=order) default_view_tax = config_value('TAX', 'DEFAULT_VIEW_TAX') order.add_status("Temp") recurring = None pagseguro = Pagseguro(tipo='CP', email_cobranca=account, moeda='BRL', encoding='UTF-8', ref_transacao=order.id, tipo_frete='EN') pagseguro.cliente(nome=order.contact.first_name, end=order.contact.billing_address.street1, cep=order.contact.billing_address.postal_code, email=order.contact.email, ) for item in order.orderitem_set.all(): pagseguro.item(id=item.product.id, descr=item.description, qty=int(item.quantity), valor="%.2f" % item.unit_price, peso=int(item.product.weight or 0) ) pagsegurohtml = pagseguro.mostra(imprime=False, abre=False, fecha=False) # Run only if subscription products are installed if 'product.modules.subscription' in settings.INSTALLED_APPS: order_items = order.orderitem_set.all() for item in order_items: if not item.product.is_subscription: continue recurring = {'product':item.product, 'price':item.product.price_set.all()[0].price.quantize(Decimal('.01')),} 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.subscription.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.subscription.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, 'pagseguro': pagsegurohtml, 'subscription': recurring, 'PAYMENT_LIVE' : gateway_live(payment_module) }) return render_to_response(template, context_instance=ctx)
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('shop/checkout/empty_cart.html', context_instance=RequestContext(request)) if not request.user.is_authenticated() and config_value( 'SHOP', '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 try: order = Order.objects.from_request(request) if order.discount_code: init_data['discount'] = order.discount_code except Order.DoesNotExist: pass if request.method == "POST": new_data = request.POST.copy() if not tempCart.is_shippable: new_data['copy_address'] = True form = PaymentContactInfoForm(data=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(request, cart=tempCart, contact=contact) request.session[CUSTOMER_ID] = custID 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() #Request additional init_data form_initialdata.send(sender=PaymentContactInfoForm, initial=init_data, contact=contact, cart=tempCart, shop=shop) 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('shop/checkout/form.html', context_instance=context)
def get_success_url(self): return lookup_url(self.paymentmodule, 'satchmo_checkout-step2')