Ejemplo n.º 1
0
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))
Ejemplo n.º 2
0
def confirm_secure3d(
        request,
        secure3d_template='shop/checkout/sagepay/secure3d_form.html',
        confirm_template='shop/checkout/confirm.html',
        extra_context={}):
    """Handles confirming an order and processing the charges when secured by secure3d.
 
    """
    payment_module = config_get_group('PAYMENT_SAGEPAY')
    controller = confirm.ConfirmController(request,
                                           payment_module,
                                           extra_context=extra_context)
    controller.template['CONFIRM'] = confirm_template
    if not controller.sanity_check():
        return controller.response

    auth3d = request.session.get('3D', None)
    if not auth3d:
        controller.processorMessage = _(
            '3D Secure transaction expired. Please try again.')

    else:
        if request.method == "POST":
            returnMD = request.POST.get('MD', None)
            if not returnMD:
                template = lookup_template(payment_module, secure3d_template)
                ctx = RequestContext(request, {
                    'order': controller.order,
                    'auth': auth3d
                })
                return render_to_response(template, context_instance=ctx)

            elif returnMD == auth3d['MD']:
                pares = request.POST.get('PaRes', None)
                controller.processor.prepare_data(controller.order)
                controller.processor.prepare_data3d(returnMD, pares)
                if controller.process():
                    return controller.onSuccess(controller)
                else:
                    controller.processorMessage = _(
                        '3D Secure transaction was not approved by payment gateway. Please contact us.'
                    )
        else:
            template = lookup_template(payment_module, secure3d_template)
            ctx = RequestContext(request, {
                'order': controller.order,
                'auth': auth3d
            })
            return render_to_response(template, context_instance=ctx)

    return secure3d_form_handler(controller)
Ejemplo n.º 3
0
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)
Ejemplo n.º 4
0
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)
Ejemplo n.º 5
0
def pay_ship_info(request):
    template = 'satchmo_stripe/pay_ship.html'
    payment_module = stripe
    form_handler = stripe_pay_ship_process_form
    result = payship.pay_ship_info_verify(request, payment_module)

    if not result[0]:
        return result[1]

    contact = result[1]
    working_cart = result[2]

    success, form = form_handler(request, contact, working_cart, payment_module)
    if success:
        return form

    template = lookup_template(payment_module, template)
    live = gateway_live(payment_module)

    ctx = RequestContext(request, {
        'form': form,
        'PAYMENT_LIVE': live,        
        })

    return render_to_response(template, context_instance=ctx)
Ejemplo n.º 6
0
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)
Ejemplo n.º 7
0
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)
Ejemplo n.º 8
0
Archivo: payship.py Proyecto: 34/T
def pay_ship_render_form(request, form, template, payment_module, cart):
    template = lookup_template(payment_module, template)
            
    ctx = RequestContext(request, {
        'form': form,
        'PAYMENT_LIVE': gateway_live(payment_module),
        })
    return render_to_response(template, context_instance=ctx)
Ejemplo n.º 9
0
def pay_ship_render_form(request, form, template, payment_module, cart):
    template = lookup_template(payment_module, template)

    ctx = RequestContext(request, {
        'form': form,
        'PAYMENT_LIVE': gateway_live(payment_module),
    })
    return render_to_response(template, context_instance=ctx)
Ejemplo n.º 10
0
def pay_ship_render_form(request, form, template, payment_module, cart):
    template = lookup_template(payment_module, template)
            
    ctx = {
        'form': form,
        'PAYMENT_LIVE': gateway_live(payment_module),
    }
    return render(request, template, ctx)
Ejemplo n.º 11
0
def confirm_secure3d(request, secure3d_template='shop/checkout/sagepay/secure3d_form.html', 
    confirm_template='shop/checkout/confirm.html', extra_context={}):
    """Handles confirming an order and processing the charges when secured by secure3d.
 
    """
    payment_module = config_get_group('PAYMENT_SAGEPAY')
    controller = confirm.ConfirmController(request, payment_module, extra_context=extra_context)
    controller.template['CONFIRM'] = confirm_template
    if not controller.sanity_check():
        return controller.response
    
    auth3d = request.session.get('3D', None)
    if not auth3d:
        controller.processorMessage = _('3D Secure transaction expired. Please try again.')

    else:
        if request.method == "POST":
            returnMD = request.POST.get('MD', None)
            if not returnMD:
                template = lookup_template(payment_module, secure3d_template)
                ctx = RequestContext(request, {'order': controller.order, 'auth': auth3d })
                return render_to_response(template, context_instance=ctx)

            elif returnMD == auth3d['MD']:
                pares = request.POST.get('PaRes', None)
                controller.processor.prepare_data(controller.order)
                controller.processor.prepare_data3d(returnMD, pares)
                if controller.process():
                    return controller.onSuccess(controller)
                else:
                    controller.processorMessage = _('3D Secure transaction was not approved by payment gateway. Please contact us.')
        else:
            template = lookup_template(payment_module, secure3d_template)
            ctx =RequestContext(request, {
                'order': controller.order, 'auth': auth3d 
                })
            return render_to_response(template, context_instance=ctx)

    return secure3d_form_handler(controller)
Ejemplo n.º 12
0
def pay_ship_render_form(request, form, template, payment_module, cart):
    template = lookup_template(payment_module, template)
    
    if cart.numItems > 0:
        products = [item.product for item in cart.cartitem_set.all()]
        sale = find_best_auto_discount(products)
    else:
        sale = None
        
    ctx = RequestContext(request, {
        'form': form,
        'sale' : sale,
        'PAYMENT_LIVE': payment_live(payment_module),
        })
    return render_to_response(template, ctx)
Ejemplo n.º 13
0
def pay_ship_info(request):
    template = 'satchmo_stripe/pay_ship.html'
    payment_module = stripe_config
    form_handler = stripe_pay_ship_process_form
    result = payship.pay_ship_info_verify(request, payment_module)

    if not result[0]:
        return result[1]

    contact = result[1]
    working_cart = result[2]

    success, form = form_handler(request, contact, working_cart, payment_module)
    if success:
        return form

    template = lookup_template(payment_module, template)
    live = gateway_live(payment_module)

    last4=''
    cc_type=''
    user = threadlocals.get_current_user()
    if user and user.is_authenticated:
      stripe_id = utils.check_stripe_customer(threadlocals.get_current_user())
      if stripe_id:
        customer = utils.get_customer(stripe_id)
        if customer:
          last4 = customer.active_card.last4
          cc_type = customer.active_card.type
          if utils.card_is_about_to_expire(customer.active_card):
#Raise message telling user that the card is about to expire
            message = "The %s card ending in %s will expire in less than %d days, please enter a new card" % (cc_type,last4,payment_module.MIN_DAYS.value)
            messages.add_message(request, messages.WARNING, message)
            cc_type = ''
            last4=''


    ctx = RequestContext(request, {
        'form': form,
        'PAYMENT_LIVE': live,        
        'saved_card' : last4,
        'cc_type' : cc_type,
        'show_save_option' : payment_module.CAPTURE.value,
        })

    return render_to_response(template, context_instance=ctx)
Ejemplo n.º 14
0
    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)
Ejemplo n.º 15
0
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)
Ejemplo n.º 16
0
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)
Ejemplo n.º 17
0
    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)
Ejemplo n.º 18
0
def _get_shipping_choices(request, paymentmodule, cart, contact, default_view_tax=False):
    """Iterate through legal shipping modules, building the list for display to the user.
    
    Returns the shipping choices list, along with a dictionary of shipping choices, useful
    for building javascript that operates on shipping choices.
    """
    shipping_options = []
    shipping_dict = {}
    
    if not cart.is_shippable:
        methods = [shipping_method_by_key('NoShipping'),]
    else:
        methods = shipping_methods()
    
    for method in methods:
        method.calculate(cart, contact)
        if method.valid():
            template = lookup_template(paymentmodule, 'shipping/options.html')
            t = loader.get_template(template)
            shipcost = method.cost()
            shipping_tax = None
            taxed_shipping_price = None
            if config_value_safe('TAX','TAX_SHIPPING', False):
                shipping_tax = TaxClass.objects.get(title=config_value('TAX', 'TAX_CLASS'))
                taxer = _get_taxprocessor(request)
                total = shipcost + taxer.by_price(shipping_tax, shipcost)
                taxed_shipping_price = moneyfmt(total)
            c = RequestContext(request, {
                'amount': shipcost,
                'description' : method.description(),
                'method' : method.method(),
                'expected_delivery' : method.expectedDelivery(),
                'default_view_tax' : default_view_tax,
                'shipping_tax': shipping_tax,
                'taxed_shipping_price': taxed_shipping_price})
            shipping_options.append((method.id, t.render(c)))
            shipping_dict[method.id] = shipcost
    
    return shipping_options, shipping_dict
Ejemplo n.º 19
0
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))
Ejemplo n.º 20
0
def _get_shipping_choices(request, paymentmodule, cart, contact, default_view_tax=False, order=None):
    """Iterate through legal shipping modules, building the list for display to the user.

    Returns the shipping choices list, along with a dictionary of shipping choices, useful
    for building javascript that operates on shipping choices.
    """
    shipping_options = []
    shipping_dict = {}
    rendered = {}
    if not order:
        try:
            order = Order.objects.from_request(request)
        except Order.DoesNotExist:
            pass

    discount = None
    if order:
        try:
            discount = Discount.objects.by_code(order.discount_code)
        except Discount.DoesNotExist:
            pass

    if not cart.is_shippable:
        methods = [shipping_method_by_key('NoShipping'),]
    else:
        methods = shipping_methods()

    tax_shipping = config_value_safe('TAX','TAX_SHIPPING', False)
    shipping_tax = None

    if tax_shipping:
        taxer = _get_taxprocessor(request)
        shipping_tax = TaxClass.objects.get(title=config_value('TAX', 'TAX_CLASS'))

    for method in methods:
        method.calculate(cart, contact)
        if method.valid():
            template = lookup_template(paymentmodule, 'shipping/options.html')
            t = loader.get_template(template)
            shipcost = finalcost = method.cost()

            if discount and order:
                order.shipping_cost = shipcost
                discount.calc(order)
                shipdiscount = discount.item_discounts.get('Shipping', 0)
            else:
                shipdiscount = 0

            # set up query to determine shipping price to show
            shipprice = Price()
            shipprice.price = shipcost
            shipadjust = PriceAdjustmentCalc(shipprice)
            if shipdiscount:
                shipadjust += PriceAdjustment('discount', _('Discount'), shipdiscount)

            satchmo_shipping_price_query.send(cart, adjustment=shipadjust)
            shipdiscount = shipadjust.total_adjustment()

            if shipdiscount:
                finalcost -= shipdiscount

            shipping_dict[method.id] = {'cost' : shipcost, 'discount' : shipdiscount, 'final' : finalcost}

            taxed_shipping_price = None
            if tax_shipping:
                taxcost = taxer.by_price(shipping_tax, finalcost)
                total = finalcost + taxcost
                taxed_shipping_price = moneyfmt(total)
                shipping_dict[method.id]['taxedcost'] = total
                shipping_dict[method.id]['tax'] = taxcost

            c = RequestContext(request, {
                'amount': finalcost,
                'description' : method.description(),
                'method' : method.method(),
                'expected_delivery' : method.expectedDelivery(),
                'default_view_tax' : default_view_tax,
                'shipping_tax': shipping_tax,
                'taxed_shipping_price': taxed_shipping_price})
            rendered[method.id] = t.render(c)

    #now sort by price, low to high
    sortme = [(value['cost'], key) for key, value in shipping_dict.items()]
    sortme.sort()

    shipping_options = [(key, rendered[key]) for cost, key in sortme]

    shipping_choices_query.send(sender=cart, cart=cart,
        paymentmodule=paymentmodule, contact=contact,
        default_view_tax=default_view_tax, order=order,
        shipping_options = shipping_options,
        shipping_dict = shipping_dict)
    return shipping_options, shipping_dict
Ejemplo n.º 21
0
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)
Ejemplo n.º 22
0
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):
    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)
Ejemplo n.º 24
0
 def testLookupTemplateSet(self):
     t = lookup_template(self.dummy, 'test.html')
     self.assertEqual(t, 'test.html')
Ejemplo n.º 25
0
def confirm_info(request):
    payment_module = config_get_group('PAYMENT_PAYPOINT')
    try:
        order = Order.objects.from_request(request)
    except Order.DoesNotExist:
        url = lookup_url(payment_module, 'satchmo_checkout-step1')
        return redirect(url)

    tmp_cart = Cart.objects.from_request(request)
    if tmp_cart.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')}
        )

    template = lookup_template(
        payment_module,
        'shop/checkout/paypoint/confirm.html'
    )

    live = payment_module.LIVE.value

    if live:
        log.debug('Live order on %s', payment_module.KEY.value)
        url = payment_module.POST_URL.value
        merchant = payment_module.MERCHANT_NAME.value
        secret = payment_module.SECRET.value
    else:
        log.debug('Test order on %s', payment_module.KEY.value)
        url = payment_module.TEST_POST_URL.value
        merchant = payment_module.TEST_MERCHANT_NAME.value
        secret = payment_module.TEST_SECRET.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('-> Adding %s to %s' % (contact, cart))
        cart.save()

    trans_id = '%07d' % order.id
    digest = '%s%s%s' % (trans_id, order.balance, secret)
    digest = hashlib.md5(digest).hexdigest()

    site = Site.objects.get_current()
    callback = 'http://%s%s' % \
        (site, reverse('PAYPOINT_satchmo_checkout-success'))

    ctx = {
        'merchant': merchant,
        'trans_id': trans_id,
        'amount': order.balance,
        'callback': callback,
        'digest': digest,
        'currency': payment_module.CURRENCY_CODE.value,
        'PAYMENT_LIVE': live,
        'post_url': url,
        'order': order
    }
    return render(request, template, ctx)
Ejemplo n.º 26
0
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)
Ejemplo n.º 27
0
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)
Ejemplo n.º 28
0
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,
        })
Ejemplo n.º 29
0
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):
    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)
Ejemplo n.º 31
0
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)
Ejemplo n.º 32
0
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)
Ejemplo n.º 33
0
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)
Ejemplo n.º 34
0
def _get_shipping_choices(request,
                          paymentmodule,
                          cart,
                          contact,
                          default_view_tax=False,
                          order=None):
    """Iterate through legal shipping modules, building the list for display to the user.

    Returns the shipping choices list, along with a dictionary of shipping choices, useful
    for building javascript that operates on shipping choices.
    """
    shipping_options = []
    shipping_dict = {}
    rendered = {}
    if not order:
        try:
            order = Order.objects.from_request(request)
        except Order.DoesNotExist:
            pass

    discount = None
    if order:
        try:
            discount = Discount.objects.by_code(order.discount_code)
        except Discount.DoesNotExist:
            pass

    if not cart.is_shippable:
        methods = [
            shipping_method_by_key('NoShipping'),
        ]
    else:
        methods = shipping_methods()

    tax_shipping = config_value_safe('TAX', 'TAX_SHIPPING', False)
    shipping_tax = None

    if tax_shipping:
        taxer = _get_taxprocessor(request)
        shipping_tax = TaxClass.objects.get(
            title=config_value('TAX', 'TAX_CLASS'))

    for method in methods:
        method.calculate(cart, contact)
        if method.valid(order=order):
            template = lookup_template(paymentmodule, 'shipping/options.html')
            t = loader.get_template(template)
            shipcost = finalcost = method.cost()

            if discount and order:
                order.shipping_cost = shipcost
                discount.calc(order)
                shipdiscount = discount.item_discounts.get('Shipping', 0)
            else:
                shipdiscount = 0

            # set up query to determine shipping price to show
            shipprice = Price()
            shipprice.price = shipcost
            shipadjust = PriceAdjustmentCalc(shipprice)
            if shipdiscount:
                shipadjust += PriceAdjustment('discount', _('Discount'),
                                              shipdiscount)

            satchmo_shipping_price_query.send(cart, adjustment=shipadjust)
            shipdiscount = shipadjust.total_adjustment()

            if shipdiscount:
                finalcost -= shipdiscount

            shipping_dict[method.id] = {
                'cost': shipcost,
                'discount': shipdiscount,
                'final': finalcost
            }

            taxed_shipping_price = None
            if tax_shipping:
                taxcost = taxer.by_price(shipping_tax, finalcost)
                total = finalcost + taxcost
                taxed_shipping_price = moneyfmt(total)
                shipping_dict[method.id]['taxedcost'] = total
                shipping_dict[method.id]['tax'] = taxcost

            c = RequestContext(
                request, {
                    'amount': finalcost,
                    'description': method.description(),
                    'method': method.method(),
                    'expected_delivery': method.expectedDelivery(),
                    'default_view_tax': default_view_tax,
                    'shipping_tax': shipping_tax,
                    'taxed_shipping_price': taxed_shipping_price
                })
            rendered[method.id] = t.render(c)

    #now sort by price, low to high
    sortme = [(value['cost'], key) for key, value in shipping_dict.items()]
    sortme.sort()

    shipping_options = [(key, rendered[key]) for cost, key in sortme]

    shipping_choices_query.send(sender=cart,
                                cart=cart,
                                paymentmodule=paymentmodule,
                                contact=contact,
                                default_view_tax=default_view_tax,
                                order=order,
                                shipping_options=shipping_options,
                                shipping_dict=shipping_dict)
    return shipping_options, shipping_dict
Ejemplo n.º 35
0
 def testLookupTemplateSet(self):
     t = lookup_template(self.dummy, 'test.html')
     self.assertEqual(t, 'test.html')
Ejemplo n.º 36
0
 def lookup_template(self, key):
     """Shortcut method to the the proper template from the `paymentModule`"""
     return lookup_template(self.paymentModule, self.templates[key])
Ejemplo n.º 37
0
 def lookup_template(self, key):
     """Shortcut method to the the proper template from the `paymentModule`"""
     return lookup_template(self.paymentModule, self.templates[key])
Ejemplo n.º 38
0
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)