def __init__(self, processor): self.payment_module = config_get_group('PAYMENT_%s' \ % processor.upper()) self.processor = get_processor_by_key('PAYMENT_%s' \ % processor.upper()) self.processor_configuration = config_get_group('PAYMENT_%s' \ % processor.upper()) self._postprocess_callables = []
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 pay_ship_info(request): return payship.base_pay_ship_info( request, config_get_group('PAYMENT_PAYPOINT'), payship.simple_pay_ship_process_form, 'shop/checkout/paypoint/pay_ship.html' )
def get_methods(): settings = config_get_group('shipping.modules.fedex_web_services') if not settings.ACCOUNT.value: log.warn("No fedex account found in settings") return if not settings.METER_NUMBER.value: log.warn("No fedex meter number found in settings") return if not settings.AUTHENTICATION_KEY.value: log.warn("No fedex authentication key found in settings") return if not settings.AUTHENTICATION_PASSWORD.value: log.warn("No fedex authentication password found in settings") return CONFIG_OBJ = get_config_obj(settings) packaging = settings.PACKAGING.value or "YOUR_PACKAGING" default_weight = settings.DEFAULT_ITEM_WEIGHT.value or 0.5 default_weight_units = settings.DEFAULT_WEIGHT_UNITS.value single_box = settings.SINGLE_BOX.value verbose_log = settings.VERBOSE_LOG.value dropoff_type = settings.DROPOFF_TYPE.value return [ shipper.Shipper( service_type=value, config=CONFIG_OBJ, packaging=packaging, default_weight=default_weight, default_weight_units=default_weight_units, single_box=single_box, verbose_log=verbose_log, dropoff_type=dropoff_type) for value in config_choice_values( 'shipping.modules.fedex_web_services', 'SHIPPING_CHOICES') ]
def payment_label(group): """convert a payment key into its translated text""" if not group.startswith("PAYMENT_"): group = "PAYMENT_" + group.upper() config = config_get_group(group) label = translation.ugettext(config.LABEL.value) return label.capitalize()
def transmit_shipments(queryset=None, send_msg=None): log.info("transmit_shipments invoked") log.debug("queryset: %s", str(queryset)) if send_msg is None: send_msg = lambda x: x if queryset is None: queryset = OrderShippingService.objects.all() from satchmo_store.shop.models import Config shop_details = Config.objects.get_current() settings = config_get_group('canada_post_dp_shipping') cpa_kwargs = canada_post_api_kwargs(settings) cpa = CanadaPostAPI(**cpa_kwargs) origin = get_origin(shop_details) groups = [] order_shippings = [] for order_shipping in queryset.filter(transmitted=False): log.debug("processing order shipping: %s", order_shipping) if order_shipping.shipments_created(): log.debug("shipments created") group = unicode(order_shipping.shipping_group()) groups.append(group) order_shippings.append(order_shipping) else: log.debug("shipments not created") log.debug("using groups: %s", groups) if groups: log.info("transmitting shipments") links = time_f(cpa.transmit_shipments, 'canada-post-dp-shipping.transmit-shipments', origin, groups) log.debug("received manifests: %s", links) log.debug("marking order shippings as transmitted") for order_shipping in order_shippings: order_shipping.transmitted = True order_shipping.save() manifest_count = len(links) log.info("received %d manifests", manifest_count) send_msg( ungettext_lazy( "{count} manifest generated. It will be sent via email in a " "couple of minutes".format(count=manifest_count), "{count} manifests generated. They will be sent via email in a " "couple of minutes".format(count=manifest_count), manifest_count)) if USE_CELERY: get_manifests_async.apply_async(args=(links, ), cowntdown=1) else: get_manifests(links) group_count = len(groups) send_msg( ungettext_lazy( "Transmitted shipments for {count} group".format( count=group_count), "Transmitted shipments for {count} groups".format( count=group_count), group_count))
def pay_ship_info(request): return payship.base_pay_ship_info( request, config_get_group("PAYMENT_PAYPAL"), payship.simple_pay_ship_process_form, "shop/checkout/paypal/pay_ship.html", )
def register(request, redirect=None, template="registration/registration_form.html"): """ Allows a new user to register an account. """ ret = register_handle_form(request, redirect) success = ret[0] todo = ret[1] if len(ret) > 2: extra_context = ret[2] else: extra_context = {} if success: return todo else: if config_get_group("NEWSLETTER"): show_newsletter = True else: show_newsletter = False ctx = {"form": todo, "title": _("Registration Form"), "show_newsletter": show_newsletter} if extra_context: ctx.update(extra_context) context = RequestContext(request, ctx) return render_to_response(template, context_instance=context)
def cost(self): """ Complex calculations can be done here, as long as the return value is a decimal figure. """ cartset = self.cart.cartitem_set.all() settings = config_get_group('shipping.modules.postdk') parcel_list = pack_parcels(cartset, settings) result = Decimal("0.00") for parcel in parcel_list: if parcel.weight <= 5: result += POSTDK_FEES['max_5'] elif parcel.weight <= 10: result += POSTDK_FEES['max_10'] elif parcel.weight <= 20: result += POSTDK_FEES['max_20'] else: # TODO, raise error as we currently don't accept parcels over # 20 kg, or parcel has no weight. pass if parcel.volume_fee(): result += POSTDK_FEES['volume'] result += settings['POSTDK_HANDLING'].value result *= settings['POSTDK_CURRENCY'].value return result
def notify_neworder(request, data): """ Called when google reports a new order. Looks up the order from the private data and sets the status. Empties the cart. """ # get params from data private_data = data['shopping-cart.merchant-private-data'] order_id = re.search('satchmo-order id="(\d+)"', private_data).group(1) order = Order.objects.get(pk=order_id) payment_module = config_get_group('PAYMENT_GOOGLE') processor = get_processor_by_key('PAYMENT_GOOGLE') # record pending payment amount = data['order-total'] pending_payment = processor.create_pending_payment(order) # save transaction id so we can find this order later pending_payment.capture.transaction_id = data['google-order-number'] pending_payment.capture.save() # delete cart for cart in Cart.objects.filter(customer=order.contact): cart.empty() cart.delete() # set status order.add_status(status='New', notes=_("Received through Google Checkout."))
def notify_callback(request): payment_module = config_get_group('PAYMENT_SERMEPA') if payment_module.LIVE.value: log.debug("Live IPN on %s", payment_module.KEY.value) signature_code = payment_module.MERCHANT_SIGNATURE_CODE.value terminal = payment_module.MERCHANT_TERMINAL.value else: log.debug("Test IPN on %s", payment_module.KEY.value) signature_code = payment_module.MERCHANT_TEST_SIGNATURE_CODE.value terminal = payment_module.MERCHANT_TEST_TERMINAL.value data = request.POST log.debug("Transaction data: " + repr(data)) try: sig_data = "%s%s%s%s%s%s" % ( data['Ds_Amount'], data['Ds_Order'], data['Ds_MerchantCode'], data['Ds_Currency'], data['Ds_Response'], signature_code) sig_calc = sha1(sig_data).hexdigest() if sig_calc != data['Ds_Signature'].lower(): log.error("Invalid signature. Received '%s', calculated '%s'." % (data['Ds_Signature'], sig_calc)) return HttpResponseBadRequest("Checksum error") if data['Ds_MerchantCode'] != payment_module.MERCHANT_FUC.value: log.error("Invalid FUC code: %s" % data['Ds_MerchantCode']) return HttpResponseNotFound("Unknown FUC code") if int(data['Ds_Terminal']) != int(terminal): log.error("Invalid terminal number: %s" % data['Ds_Terminal']) return HttpResponseNotFound("Unknown terminal number") # TODO: fields Ds_Currency, Ds_SecurePayment may be worth checking xchg_order_id = data['Ds_Order'] try: order_id = xchg_order_id[:xchg_order_id.index('T')] except ValueError: log.error("Incompatible order ID: '%s'" % xchg_order_id) return HttpResponseNotFound("Order not found") try: order = Order.objects.get(id=order_id) except Order.DoesNotExist: log.error("Received data for nonexistent Order #%s" % order_id) return HttpResponseNotFound("Order not found") amount = Decimal(data['Ds_Amount']) / Decimal( '100') # is in cents, divide it if int(data['Ds_Response']) > 100: log.info("Response code is %s. Payment not accepted." % data['Ds_Response']) return HttpResponse() except KeyError: log.error("Received incomplete SERMEPA transaction data") return HttpResponseBadRequest("Incomplete data") # success order.add_status(status='New', notes=u"Paid through SERMEPA.") processor = get_processor_by_key('PAYMENT_SERMEPA') payment = processor.record_payment( order=order, amount=amount, transaction_id=data['Ds_AuthorisationCode']) # empty customer's carts for cart in Cart.objects.filter(customer=order.contact): cart.empty() return HttpResponse()
def google_checkout_image_url(parser, token): """ Render the url for a google checkout image. Sample usage:: {% google_checkout_image_url [imagesize] ['transparent'] ['disabled'] %} """ args = token.split_contents() payment_module = config_get_group('PAYMENT_GOOGLE') merchid = payment_module.MERCHANT_ID sizes = CHECKOUT_BUTTON_SIZES.keys() imgsize = "MEDIUM" transparent = False disabled = False locale = None for arg in args[1:]: k = arg.upper() if k == 'TRANSPARENT': transparent = True elif k == 'DISABLED': disabled = True else: if k in sizes: imgsize = k else: raise template.TemplateSyntaxError("%r tag got an unexpected argument. Perhaps a bad size? Didn't know: %s" % (args[0], arg)) return GoogleCheckoutImageUrlNode(merchid, imgsize, transparent, disabled)
def get_manifests(links): log.info("Getting manifests from links: %s", links) settings = config_get_group('canada_post_dp_shipping') cpa_kwargs = canada_post_api_kwargs(settings) cpa = CanadaPostAPI(**cpa_kwargs) manifests = [] for link in links: log.debug("Getting manifest from %s", link['href']) try: cpa_manifest = time_f(cpa.get_manifest, 'canada-post-dp-shipping.get-manifest', link) manifest = Manifest(manifest=cpa_manifest) manifest_pdf = time_f(cpa.get_artifact, 'canada-post-dp-shipping.get-artifact', cpa_manifest) filename = os.path.basename(link['href'].rstrip('/')) if not filename.endswith('.pdf'): filename += '.pdf' manifest.artifact = File(manifest_pdf, filename) manifest.save() shipments = time_f(cpa.get_manifest_shipments, 'canada-post-dp-shipping.get-manifest-shipments', cpa_manifest) for shipment_id in shipments: log.info("Setting manifest for shipment %s", shipment_id) try: shipment = Shipment.objects.select_related().get(id=shipment_id) shipping_detail = shipment.parcel.shipping_detail shipping_detail.manifest = manifest shipping_detail.save() except Shipment.DoesNotExist: log.error("Requested shipment does not exist") manifests.append(manifest) except Exception, e: log.error("Error processing manifest: %s", e, exc_info=True)
def register(request, redirect=None, template='registration/registration_form.html'): """ Allows a new user to register an account. """ ret = register_handle_form(request, redirect) success = ret[0] todo = ret[1] if len(ret) > 2: extra_context = ret[2] else: extra_context = {} if success: return todo else: if config_get_group('NEWSLETTER'): show_newsletter = True else: show_newsletter = False ctx = { 'form': todo, 'title' : _('Registration Form'), 'show_newsletter' : show_newsletter, 'allow_nickname' : config_value('SHOP', 'ALLOW_NICKNAME_USERNAME') } if extra_context: ctx.update(extra_context) context = RequestContext(request, ctx) return render_to_response(template, context_instance=context)
def new_shipper(self, single_box=True): """ Creates a new Shipper instance, make sure that you set-up your livesettings for this module. """ service_type = ('FEDEX_GROUND', 'Fedex Ground Shipping') settings = config_get_group('shipping.modules.fedex_web_services') CONFIG_OBJ = get_config_obj(settings) packaging = settings.PACKAGING.value or "YOUR_PACKAGING" default_weight = settings.DEFAULT_ITEM_WEIGHT.value or 0.5 default_weight_units = settings.DEFAULT_WEIGHT_UNITS.value single_box = single_box verbose_log = settings.VERBOSE_LOG.value dropoff_type = settings.DROPOFF_TYPE.value shipper = Shipper(service_type=service_type, config=CONFIG_OBJ, packaging=packaging, default_weight=default_weight, default_weight_units=default_weight_units, single_box=single_box, verbose_log=verbose_log, dropoff_type=dropoff_type) return shipper
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="") 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 __init__(self, cart=None, contact=None, service_type=None): self.cart = cart self.contact = contact self._rate = None self._rate_calculated = False self.settings = config_get_group('quinode_shipping')
def testGetCreditcard(self): self.processor = config_get_group('PAYMENT_CREDITCARD') self.assert_(self.processor != None) self.assertEqual(self.processor.LABEL, 'Creditcard (Bancasella)') self.assertEqual(self.processor.CURRENCY_CODE, '242') # Euro self.assertEqual(self.processor.POST_URL, 'https://ecomm.sella.it/gestpay/pagam.asp') self.assertEqual(self.processor.POST_TEST_URL, 'https://testecomm.sella.it/gestpay/pagam.asp')
def new_shipper(self, single_box=True): """ Creates a new Shipper instance, make sure that you set-up your livesettings for this module. """ service_type = ('FEDEX_GROUND', 'Fedex Ground Shipping') settings = config_get_group('shipping.modules.fedex_web_services') CONFIG_OBJ = get_config_obj(settings) packaging = settings.PACKAGING.value or "YOUR_PACKAGING" default_weight = settings.DEFAULT_ITEM_WEIGHT.value or 0.5 default_weight_units = settings.DEFAULT_WEIGHT_UNITS.value single_box = single_box verbose_log = settings.VERBOSE_LOG.value dropoff_type = settings.DROPOFF_TYPE.value shipper = Shipper( service_type=service_type, config=CONFIG_OBJ, packaging=packaging, default_weight=default_weight, default_weight_units=default_weight_units, single_box=single_box, verbose_log=verbose_log, dropoff_type=dropoff_type) return shipper
def pay_ship_info(request): return payship.base_pay_ship_info( request, config_get_group("PAYMENT_SERMEPA"), payship.simple_pay_ship_process_form, "shop/checkout/sermepa/pay_ship.html", )
def payment_label(group): """convert a payment key into its translated text""" if not group.startswith('PAYMENT_'): group = "PAYMENT_" + group.upper() config = config_get_group(group) label = translation.ugettext(config.LABEL.value) return label.capitalize()
def notify_callback(request): payment_module = config_get_group("PAYMENT_SERMEPA") if payment_module.LIVE.value: log.debug("Live IPN on %s", payment_module.KEY.value) signature_code = payment_module.MERCHANT_SIGNATURE_CODE.value terminal = payment_module.MERCHANT_TERMINAL.value else: log.debug("Test IPN on %s", payment_module.KEY.value) signature_code = payment_module.MERCHANT_TEST_SIGNATURE_CODE.value terminal = payment_module.MERCHANT_TEST_TERMINAL.value data = request.POST log.debug("Transaction data: " + repr(data)) try: sig_data = "%s%s%s%s%s%s" % ( data["Ds_Amount"], data["Ds_Order"], data["Ds_MerchantCode"], data["Ds_Currency"], data["Ds_Response"], signature_code, ) sig_calc = sha1(sig_data).hexdigest() if sig_calc != data["Ds_Signature"].lower(): log.error("Invalid signature. Received '%s', calculated '%s'." % (data["Ds_Signature"], sig_calc)) return HttpResponseBadRequest("Checksum error") if data["Ds_MerchantCode"] != payment_module.MERCHANT_FUC.value: log.error("Invalid FUC code: %s" % data["Ds_MerchantCode"]) return HttpResponseNotFound("Unknown FUC code") if int(data["Ds_Terminal"]) != int(terminal): log.error("Invalid terminal number: %s" % data["Ds_Terminal"]) return HttpResponseNotFound("Unknown terminal number") # TODO: fields Ds_Currency, Ds_SecurePayment may be worth checking xchg_order_id = data["Ds_Order"] try: order_id = xchg_order_id[: xchg_order_id.index("T")] except ValueError: log.error("Incompatible order ID: '%s'" % xchg_order_id) return HttpResponseNotFound("Order not found") try: order = Order.objects.get(id=order_id) except Order.DoesNotExist: log.error("Received data for nonexistent Order #%s" % order_id) return HttpResponseNotFound("Order not found") amount = Decimal(data["Ds_Amount"]) / Decimal("100") # is in cents, divide it if int(data["Ds_Response"]) > 100: log.info("Response code is %s. Payment not accepted." % data["Ds_Response"]) return HttpResponse() except KeyError: log.error("Received incomplete SERMEPA transaction data") return HttpResponseBadRequest("Incomplete data") # success order.add_status(status="New", notes=u"Paid through SERMEPA.") processor = get_processor_by_key("PAYMENT_SERMEPA") payment = processor.record_payment(order=order, amount=amount, transaction_id=data["Ds_AuthorisationCode"]) # empty customer's carts for cart in Cart.objects.filter(customer=order.contact): cart.empty() return HttpResponse()
def confirm_info(request, template="shop/checkout/protx/confirm.html", extra_context={}): payment_module = config_get_group("PAYMENT_PROTX") controller = confirm.ConfirmController(request, payment_module) controller.templates["CONFIRM"] = template controller.extra_context = extra_context controller.onForm = secure3d_form_handler controller.confirm() return controller.response
def get_client(): settings = config_get_group('satchmo_correios_shipping') return Client( settings.CEP_ORIGEM.value, codigo_empresa=settings.CODIGO_EMPRESA.value, senha=settings.SENHA.value )
def confirm_info(request, template='shop/checkout/sagepay/confirm.html', extra_context={}): payment_module = config_get_group('PAYMENT_SAGEPAY') controller = confirm.ConfirmController(request, payment_module) controller.templates['CONFIRM'] = template controller.extra_context = extra_context controller.onForm = secure3d_form_handler controller.confirm() return controller.response
def render(self, context): order = context[self.order_var] payment_type = order.payments.all()[0].payment context[self.save_var] = config_get_group('PAYMENT_' + payment_type) return ''
def cost(self): """ Complex calculations can be done here as long as the return value is a decimal figure """ assert(self._calculated) settings = config_get_group('shipping.modules.usps') if settings.HANDLING_FEE and float(str(settings.HANDLING_FEE)) > 0.0: self.charges = Decimal(self.charges) + Decimal(str(settings.HANDLING_FEE)) return Decimal(str(self.charges))
def get_processor_by_key(key): """ Returns an instance of a payment processor, referred to by *key*. :param key: A string of the form 'PAYMENT_<PROCESSOR_NAME>'. """ payment_module = config_get_group('PAYMENT_%s' % key) processor_module = payment_module.MODULE.load_module('processor') return processor_module.PaymentProcessor(payment_module)
def render_template(self, template, cart=None, contact=None): from satchmo_store.shop.models import Config shop_details = Config.objects.get_current() settings = config_get_group("shipping.modules.usps") if not self.is_intl: mail_type = CODES[self.service_type_code] if mail_type == "INTL": return "" if mail_type == "FIRST CLASS": self.api = None else: self.api = APIS[mail_type] else: mail_type = None self.api = None # calculate the weight of the entire order weight = Decimal("0.0") for item in cart.cartitem_set.all(): if item.product.smart_attr("weight"): weight += item.product.smart_attr("weight") * item.quantity self.verbose_log("WEIGHT: %s" % weight) # I don't know why USPS made this one API different this way... if self.api == "ExpressMailCommitment": zip_ending = "ZIP" else: zip_ending = "zip" # get the shipping country (for the international orders) ship_country = contact.shipping_address.country.printable_name configuration = { "userid": settings.USER_ID.value, "password": settings.USER_PASSWORD.value, "container": settings.SHIPPING_CONTAINER.value, "ship_type": mail_type, "shop_details": shop_details, } c = Context( { "config": configuration, "cart": cart, "contact": contact, "is_international": self.is_intl, "api": self.api, "weight": weight, "zip": zip_ending, "country": ship_country, "first_class_types": ["LETTER", "FLAT", "PARCEL"], } ) t = loader.get_template(template) return t.render(c)
def cost(self): """ Complex calculations can be done here as long as the return value is a decimal figure """ assert self._calculated settings = config_get_group("shipping.modules.usps") if settings.HANDLING_FEE and float(str(settings.HANDLING_FEE)) > 0.0: self.charges = Decimal(self.charges) + Decimal(str(settings.HANDLING_FEE)) return Decimal(str(self.charges))
def transmit_shipments(queryset=None, send_msg=None): log.info("transmit_shipments invoked") log.debug("queryset: %s", str(queryset)) if send_msg is None: send_msg = lambda x: x if queryset is None: queryset = OrderShippingService.objects.all() from satchmo_store.shop.models import Config shop_details = Config.objects.get_current() settings = config_get_group('canada_post_dp_shipping') cpa_kwargs = canada_post_api_kwargs(settings) cpa = CanadaPostAPI(**cpa_kwargs) origin = get_origin(shop_details) groups = [] order_shippings = [] for order_shipping in queryset.filter( transmitted=False): log.debug("processing order shipping: %s", order_shipping) if order_shipping.shipments_created(): log.debug("shipments created") group = unicode(order_shipping.shipping_group()) groups.append(group) order_shippings.append(order_shipping) else: log.debug("shipments not created") log.debug("using groups: %s", groups) if groups: log.info("transmitting shipments") links = time_f(cpa.transmit_shipments, 'canada-post-dp-shipping.transmit-shipments', origin, groups) log.debug("received manifests: %s", links) log.debug("marking order shippings as transmitted") for order_shipping in order_shippings: order_shipping.transmitted = True order_shipping.save() manifest_count = len(links) log.info("received %d manifests", manifest_count) send_msg(ungettext_lazy( "{count} manifest generated. It will be sent via email in a " "couple of minutes".format(count=manifest_count), "{count} manifests generated. They will be sent via email in a " "couple of minutes".format(count=manifest_count), manifest_count)) if USE_CELERY: get_manifests_async.apply_async(args=(links,), cowntdown=1) else: get_manifests(links) group_count = len(groups) send_msg(ungettext_lazy( "Transmitted shipments for {count} group".format(count=group_count), "Transmitted shipments for {count} groups".format(count=group_count), group_count))
def get_processor_by_key(key): """ Returns an instance of a payment processor, referred to by *key*. :param key: A string of the form 'PAYMENT_<PROCESSOR_NAME>'. """ payment_module = config_get_group(key) processor_module = payment_module.MODULE.load_module('processor') return processor_module.PaymentProcessor(payment_module)
def payment_label(value): """convert a payment key into its translated text""" payments = config_get("PAYMENT", "MODULES") for mod in payments.value: config = config_get_group(mod) if config.KEY.value == value: return translation.ugettext(config.LABEL) return value.capitalize()
def cost(self): """ Complex calculations can be done here as long as the return value is a decimal figure """ assert(self._calculated) settings = config_get_group('shipping.modules.ups') if settings.HANDLING_FEE and Decimal(str(settings.HANDLING_FEE)) > Decimal(0): self.charges = Decimal(self.charges) + Decimal(str(settings.HANDLING_FEE)) return(Decimal(self.charges))
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 order_payment_methods(order): """ Returns a list of payment method labels for an order. Usage:: {{ order|order_payment_methods|join:", " }} """ return (config_get_group('PAYMENT_%s' % p.payment).LABEL.value for p in order.payments.all())
def payment_return(request): token = request.GET.get('token') payer_id = request.GET.get('PayerID') if not token and not payer_id: raise Http404 processor = PaymentProcessor(config_get_group(PROCESSOR_KEY)) processor.capture_payment(token, payer_id) return direct_to_template(request, 'shop/checkout/payment_return.html')
def checkout_image_url(merchid, imgsize, locale, transparent=False, disabled=False): payment_module = config_get_group('PAYMENT_GOOGLE') dimensions = CHECKOUT_BUTTON_SIZES[imgsize] return ("%s?%s" % ( payment_module.CHECKOUT_BUTTON_URL, urlencode((('merchant_id', merchid), ('w', dimensions[0]), ('h', dimensions[1]), ('style', _truefalse(transparent, t="trans", f="white")), ('variant', _truefalse(disabled, t="disabled", f="text")), ('loc', locale)))))
def get_cred(): payment_module = config_get_group('PAYMENT_GOOGLE') live = gateway_live(payment_module) # get key and value if live: merchant_id = payment_module.MERCHANT_ID.value merchant_key = payment_module.MERCHANT_KEY.value else: merchant_id = payment_module.MERCHANT_TEST_ID.value merchant_key = payment_module.MERCHANT_TEST_KEY.value return (merchant_id, merchant_key)
def get_cred(): gateway_settings = config_get_group('PAYMENT_GOOGLE') live = gateway_live(gateway_settings) # get key and value if live: merchant_id = gateway_settings.MERCHANT_ID.value merchant_key = gateway_settings.MERCHANT_KEY.value else: merchant_id = gateway_settings.MERCHANT_TEST_ID.value merchant_key = gateway_settings.MERCHANT_TEST_KEY.value return (merchant_id, merchant_key)
def render_template(self, template, cart=None, contact=None): from satchmo_store.shop.models import Config shop_details = Config.objects.get_current() settings = config_get_group('shipping.modules.usps') if not self.is_intl: mail_type = CODES[self.service_type_code] if mail_type == 'INTL': return '' if mail_type == 'FIRST CLASS': self.api = None else: self.api = APIS[mail_type] else: mail_type = None self.api = None # calculate the weight of the entire order weight = Decimal('0.0') for item in cart.cartitem_set.all(): if item.product.smart_attr('weight'): weight += item.product.smart_attr('weight') * item.quantity self.verbose_log('WEIGHT: %s' % weight) # I don't know why USPS made this one API different this way... if self.api == 'ExpressMailCommitment': zip_ending = 'ZIP' else: zip_ending = 'zip' # get the shipping country (for the international orders) ship_country = contact.shipping_address.country.printable_name configuration = { 'userid': settings.USER_ID.value, 'password': settings.USER_PASSWORD.value, 'container': settings.SHIPPING_CONTAINER.value, 'ship_type': mail_type, 'shop_details': shop_details } c = Context({ 'config': configuration, 'cart': cart, 'contact': contact, 'is_international': self.is_intl, 'api': self.api, 'weight': weight, 'zip': zip_ending, 'country': ship_country, 'first_class_types': ['LETTER', 'FLAT', 'PARCEL'] }) t = loader.get_template(template) return t.render(c)
def register(request, redirect=None, template='registration/registration_form.html'): """ Allows a new user to register an account. """ #print("Request post : %s" % request.POST) ret = register_handle_form(request, redirect) success = ret[0] todo = ret[1] if len(ret) > 2: extra_context = ret[2] else: extra_context = {} if success: return todo else: if config_get_group('NEWSLETTER'): show_newsletter = True else: show_newsletter = False context = {'form': todo, 'show_newsletter': show_newsletter} if extra_context: context.update(extra_context) context.update({"page_info": _get_page_parameters()}) # register to update if request.method == "POST": form_object = UpdatesRegistrationForm(request.POST) form_updates_registration = UpdatesRegistrationFormManager( form_object, request) form_success = form_updates_registration.validate() if form_success: return form_updates_registration.notify_and_redirect() else: form_object = UpdatesRegistrationForm() form_updates_registration = UpdatesRegistrationFormManager( form_object, request) context.update({ "form_updates_registration": form_updates_registration.render_html() }) return render_to_response(template, context, context_instance=RequestContext(request))
def get_url(): """ Returns the urls needed """ (merchant_id, merchant_key) = get_cred() payment_module = config_get_group('PAYMENT_GOOGLE') live = gateway_live(payment_module) if live: url_template = payment_module.POST_URL.value else: url_template = payment_module.POST_TEST_URL.value post_url = url_template % {'MERCHANT_ID': merchant_id} return post_url
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)
def success(request): """ The order has been succesfully processed. This can be used to generate a receipt or some other confirmation """ try: order = Order.objects.from_request(request) except Order.DoesNotExist: bad_or_missing_message = 'Your order has already been processed.' return bad_or_missing(request, _(bad_or_missing_message)) amount = order.balance payment_module = config_get_group('PAYMENT_CREDITCARD') processor = get_processor_by_key('PAYMENT_CREDITCARD') account = request.GET.get('a', '') ecripted_string = request.GET.get('b', '') gpc = GestPayCrypt() gpc.SetShopLogin(account) gpc.SetShopTransactionID(str(order.id)) gpc.SetAmount("%.2f" % order.total) gpc.SetEncryptedString(str(ecripted_string)) # if gpc.Decrypt() == 1 --> Transaction is OK if gpc.Decrypt() == 1: processor.record_payment( order = order, amount = amount, transaction_id = gpc.GetBankTransactionID(), reason_code = gpc.GetAuthorizationCode() ) if order.notes is None: order.notes = "" else: order.notes += "\n\n" order.save() order.add_status( status = 'New', notes = "Pagato mediante BANCASELLA" ) # Make cart empty cart = Cart.objects.from_request(request) if cart: cart.empty() return render_to_response('shop/checkout/success_creditcard.html', {'order': order,}, context_instance=RequestContext(request))
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 register_from_invite(request, redirect=None, invite_code=''): """ Wrapping registration form view for insert 'next' url paramenter """ # XXX: I copied the code of the register of Satchmo because in this # moment I have not found a better way to pass the # parameter 'next' to the template # Check if invite_code is still valid try: invite = Invite.objects.get_by_code(code=invite_code) except Invite.DoesNotExist: return invalid_code(request, invite_code) template = 'invites/registration_form.html' ret = register_handle_form(request, redirect) success = ret[0] todo = ret[1] if len(ret) > 2: extra_context = ret[2] else: extra_context = {} if success: return todo else: if config_get_group('NEWSLETTER'): show_newsletter = True else: show_newsletter = False ctx = { 'form': todo, 'recipient': invite.recipient, 'title': _(u'Registration Form'), 'show_newsletter': show_newsletter, 'allow_nickname': config_value('SHOP', 'ALLOW_NICKNAME_USERNAME'), 'next': reverse('invites_confirm', args=[invite_code]) } if extra_context: ctx.update(extra_context) context = RequestContext(request, ctx) return render_to_response(template, context_instance=context)
def get_methods(): settings = config_get_group('shipping.modules.fedex_web_services') if not settings.ACCOUNT.value: log.warn("No fedex account found in settings") return if not settings.METER_NUMBER.value: log.warn("No fedex meter number found in settings") return if not settings.AUTHENTICATION_KEY.value: log.warn("No fedex authentication key found in settings") return if not settings.AUTHENTICATION_PASSWORD.value: log.warn("No fedex authentication password found in settings") return CONFIG_OBJ = get_config_obj(settings) packaging = settings.PACKAGING.value or "YOUR_PACKAGING" default_weight = settings.DEFAULT_ITEM_WEIGHT.value or 0.5 default_weight_units = settings.DEFAULT_WEIGHT_UNITS.value single_box = settings.SINGLE_BOX.value verbose_log = settings.VERBOSE_LOG.value dropoff_type = settings.DROPOFF_TYPE.value return [ shipper.Shipper(service_type=value, config=CONFIG_OBJ, packaging=packaging, default_weight=default_weight, default_weight_units=default_weight_units, single_box=single_box, verbose_log=verbose_log, dropoff_type=dropoff_type) for value in config_choice_values( 'shipping.modules.fedex_web_services', 'SHIPPING_CHOICES') ]
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 confirm_info(request): payment_module = config_get_group('PAYMENT_GOOGLE') controller = confirm.ConfirmController(request, payment_module) if not controller.sanity_check(): return controller.response live = gateway_live(payment_module) gcart = GoogleCart(controller.order, payment_module, live) log.debug("CART:\n%s", gcart.cart_xml) post_url = auth.get_url() default_view_tax = config_value('TAX', 'DEFAULT_VIEW_TAX') ctx = { 'post_url': post_url, 'google_cart': gcart.encoded_cart(), 'google_signature': gcart.encoded_signature(), 'PAYMENT_LIVE': live } controller.extra_context = ctx controller.confirm() return controller.response
def __init__(self, cart=None, contact=None): u"""Инициализация""" self.cart = cart self.contact = contact self.id = u'EMSRussianPost' self.__locations_expires = None self.__locations = None self._charges = None self._delivery_days = None self._city_from = '' # поиск города из конфигурации self._settings = config_get_group('satchmo_emsrus') if self._settings.CITY_FROM: for location in self.locations: if (location.kind == 'T') and is_similiar( unicode(location.name), unicode(self._settings.CITY_FROM)): self._city_from = location.key if self.cart and self.contact: self.calculate()
def get_manifests(links): log.info("Getting manifests from links: %s", links) settings = config_get_group('canada_post_dp_shipping') cpa_kwargs = canada_post_api_kwargs(settings) cpa = CanadaPostAPI(**cpa_kwargs) manifests = [] for link in links: log.debug("Getting manifest from %s", link['href']) try: cpa_manifest = time_f(cpa.get_manifest, 'canada-post-dp-shipping.get-manifest', link) manifest = Manifest(manifest=cpa_manifest) manifest_pdf = time_f(cpa.get_artifact, 'canada-post-dp-shipping.get-artifact', cpa_manifest) filename = os.path.basename(link['href'].rstrip('/')) if not filename.endswith('.pdf'): filename += '.pdf' manifest.artifact = File(manifest_pdf, filename) manifest.save() shipments = time_f( cpa.get_manifest_shipments, 'canada-post-dp-shipping.get-manifest-shipments', cpa_manifest) for shipment_id in shipments: log.info("Setting manifest for shipment %s", shipment_id) try: shipment = Shipment.objects.select_related().get( id=shipment_id) shipping_detail = shipment.parcel.shipping_detail shipping_detail.manifest = manifest shipping_detail.save() except Shipment.DoesNotExist: log.error("Requested shipment does not exist") manifests.append(manifest) except Exception, e: log.error("Error processing manifest: %s", e, exc_info=True)