def fix_payment_attrs(ctx=None):
    portal = getSite()
    payments = Payments(portal)
    orders_soup = get_orders_soup(portal)
    data = orders_soup.storage.data
    for item in data.values():
        try:
            item.attrs['payment_method']
            item.attrs['payment_label']
            continue
        except KeyError:
            payment_method = item.attrs['payment_selection.payment']
            payment = payments.get(payment_method)
            if payment:
                payment_label = payment.label
            else:
                payment_label = _('unknown', default=u'Unknown')
            item.attrs['payment_method'] = payment_method
            logging.info(
                u"Added payment_method {0} to booking {1}".format(
                    payment_method, item.attrs['uid']
                )
            )
            item.attrs['payment_label'] = payment_label
            logging.info(
                u"Added payment_label {0} to booking {1}".format(
                    payment_label, item.attrs['uid']
                )
            )
Example #2
0
 def __call__(self, **kw):
     uid = self.request['uid']
     payment = Payments(self.context).get('cash')
     payment.succeed(self.request, uid)
     url = '%s/@@cash_in_advance_done?uid=%s' % (
         self.context.absolute_url(), uid)
     self.request.response.redirect(url)
Example #3
0
 def __call__(self, **kw):
     uid = self.request['uid']
     payment = Payments(self.context).get('invoice')
     payment.succeed(self.request, uid)
     url = '{url}/@@invoiced?uid={uid}&_authenticator={token}'.format(
         url=self.context.absolute_url(), uid=uid, token=createToken())
     self.request.response.redirect(url)
 def __call__(self, **kw):
     uid = self.request['uid']
     payment = Payments(self.context).get('cash')
     payment.succeed(self.request, uid)
     url = '%s/@@cash_on_delivery_done?uid=%s' % (
         self.context.absolute_url(), uid)
     self.request.response.redirect(url)
 def __call__(self, **kw):
     uid = self.request['uid']
     payment = Payments(self.context).get('invoice')
     payment.succeed(self.request, uid)
     url = '{url}/@@pay_invoice_done?uid={uid}&_authenticator={token}'.format(
         url=self.context.absolute_url(),
         uid=uid,
         token=createToken()
     )
     self.request.response.redirect(url)
 def id(self):
     uid = self.request.get('uid', None)
     payment = Payments(self.context).get('dibs')
     payment.succeed(self.request, uid)
     
     try:
         order = get_order(self.context, uid)
     except ValueError:
         return None
     return order.attrs.get('ordernumber')
Example #7
0
 def finish(self, widget, data):
     providers = [fields_factory(self.context, self.request) \
                  for fields_factory in self.provider_registry]
     to_adapt = (self.context, self.request)
     checkout_adapter = getMultiAdapter(to_adapt, ICheckoutAdapter)
     uid = checkout_adapter.save(providers, widget, data)
     checkout_adapter.clear_session()
     p_name = data.fetch('checkout.payment_selection.payment').extracted
     payments = Payments(self.context)
     payment = payments.get(p_name)
     self.finish_redirect_url = payment.init_url(str(uid))
Example #8
0
def PaymentMethodsVocabulary(context):
    try:
        items = Payments(context).vocab
    except KeyError:
        # happens GS profile application if registry entries not present yet
        return AvailablePaymentMethodsVocabulary(context)
    return SimpleVocabulary([SimpleTerm(value=k, title=v) for k, v in items])
Example #9
0
 def finish(self, widget, data):
     providers = [fields_factory(self.context, self.request) for fields_factory in self.provider_registry]
     to_adapt = (self.context, self.request)
     checkout_adapter = getMultiAdapter(to_adapt, ICheckoutAdapter)
     try:
         uid = checkout_adapter.save(providers, widget, data)
     except CheckoutError:
         transaction.abort()
         self.checkout_back(self.request)
     checkout_adapter.clear_session()
     checkout_settings = ICheckoutSettings(self.context)
     if checkout_settings.skip_payment(uid):
         self.finish_redirect_url = checkout_settings.skip_payment_redirect_url(uid)
     else:
         p_name = data.fetch("checkout.payment_selection.payment").extracted
         payments = Payments(self.context)
         payment = payments.get(p_name)
         self.finish_redirect_url = payment.init_url(str(uid))
     event = CheckoutDone(self.context, self.request, uid)
     notify(event)
Example #10
0
    def verify(self):
        #
        # Get Payment details
        #
        data = self.request.form
        ordernumber = data['orderID']

        if get_status_category(int(data['STATUS'])) != SUCCESS_STATUS:
            return False

        #
        # SHA passphrase verification
        #
        signer = OgoneSignature(data, 'sha512', SHA_OUT_PASSWORD)
        order_uid = IPaymentData(self.context).uid_for(ordernumber)
        payment = Payments(self.context).get('ogone_payment')

        if data['SHASIGN'] == signer.signature():
            payment.succeed(self.context, order_uid)
            order = OrderData(self.context, uid=order_uid)
            order.salaried = ifaces.SALARIED_YES
            return True
        else:
            payment.failed(self.context, order_uid)
            return False
Example #11
0
def fix_payment_attrs(ctx=None):
    portal = getSite()
    payments = Payments(portal)
    orders_soup = get_orders_soup(portal)
    data = orders_soup.storage.data
    for item in data.values():
        try:
            item.attrs['payment_method']
            item.attrs['payment_label']
            continue
        except KeyError:
            payment_method = item.attrs['payment_selection.payment']
            payment = payments.get(payment_method)
            if payment:
                payment_label = payment.label
            else:
                payment_label = _('unknown', default=u'Unknown')
            item.attrs['payment_method'] = payment_method
            logging.info("Added payment_method {0} to booking {1}".format(
                payment_method, item.attrs['uid']))
            item.attrs['payment_label'] = payment_label
            logging.info("Added payment_label {0} to booking {1}".format(
                payment_label, item.attrs['uid']))
Example #12
0
    def save(self, providers, widget, data):
        super(OrderCheckoutAdapter, self).save(providers, widget, data)
        order = self.order
        # order UUID
        uid = order.attrs['uid'] = uuid.uuid4()
        # order creator
        creator = None
        member = plone.api.user.get_current()
        if member:
            creator = member.getId()
        order.attrs['creator'] = creator
        # order creation date
        created = datetime.datetime.now()
        order.attrs['created'] = created
        cart_data = get_data_provider(self.context, self.request)
        # payment related information
        if cart_data.total > Decimal(0):
            payment_param = 'checkout.payment_selection.payment'
            pid = data.fetch(payment_param).extracted
            payment = Payments(self.context).get(pid)
            order.attrs['payment_method'] = pid
            if payment:
                order.attrs['payment_label'] = payment.label
            else:
                order.attrs['payment_label'] = _('unknown', default=u'Unknown')
        # no payment
        else:
            order.attrs['payment_method'] = 'no_payment'
            order.attrs['payment_label'] = _('no_payment',
                                             default=u'No Payment')
        # shipping related information
        if cart_data.include_shipping_costs:
            shipping_param = 'checkout.shipping_selection.shipping'
            sid = data.fetch(shipping_param).extracted
            shipping = Shippings(self.context).get(sid)
            order.attrs['shipping_method'] = sid
            order.attrs['shipping_label'] = shipping.label
            order.attrs['shipping_description'] = shipping.description
            try:
                shipping_net = shipping.net(self.items)
                shipping_vat = shipping.vat(self.items)
                order.attrs['shipping_net'] = shipping_net
                order.attrs['shipping_vat'] = shipping_vat
                order.attrs['shipping'] = shipping_net + shipping_vat
            # B/C for bda.plone.shipping < 0.4
            except NotImplementedError:
                shipping_net = shipping.calculate(self.items)
                order.attrs['shipping_net'] = shipping_net
                order.attrs['shipping_vat'] = Decimal(0)
                order.attrs['shipping'] = shipping_net
        # no shipping
        else:
            order.attrs['shipping_method'] = 'no_shipping'
            order.attrs['shipping_label'] = _('no_shipping',
                                              default=u'No Shipping')
            order.attrs['shipping_description'] = ''
            order.attrs['shipping_net'] = Decimal(0)
            order.attrs['shipping_vat'] = Decimal(0)
            order.attrs['shipping'] = Decimal(0)
        # create order bookings
        bookings = self.create_bookings(order)
        # lookup booking uids, buyable uids and vendor uids
        booking_uids = list()
        buyable_uids = list()
        vendor_uids = set()
        for booking in bookings:
            booking_uids.append(booking.attrs['uid'])
            buyable_uids.append(booking.attrs['buyable_uid'])
            vendor_uids.add(booking.attrs['vendor_uid'])
        order.attrs['booking_uids'] = booking_uids
        order.attrs['buyable_uids'] = buyable_uids
        order.attrs['vendor_uids'] = list(vendor_uids)
        # cart discount related information
        cart_discount = cart_data.discount(self.items)
        order.attrs['cart_discount_net'] = cart_discount['net']
        order.attrs['cart_discount_vat'] = cart_discount['vat']
        # create ordernumber
        orders_soup = get_orders_soup(self.context)
        ordernumber = create_ordernumber()
        while self.ordernumber_exists(orders_soup, ordernumber):
            ordernumber = create_ordernumber()
        order.attrs['ordernumber'] = ordernumber

        order.attrs['state'] = ifaces.STATE_NEW
        order.attrs['salaried'] = ifaces.SALARIED_NO

        # add order
        orders_soup.add(order)
        # add bookings
        bookings_soup = get_bookings_soup(self.context)
        for booking in bookings:
            bookings_soup.add(booking)
        # return uid of added order
        return uid
Example #13
0
def AvailablePaymentMethodsVocabulary(context):
    payments = Payments(context).payments
    items = [(payment.pid, payment.label) for payment in payments]
    return SimpleVocabulary([SimpleTerm(value=k, title=v) for k, v in items])
Example #14
0
 def __call__(self):
     stripe.api_key = self.secret_key
     base_url = self.context.absolute_url()
     token = self.request['stripeToken']
     order_uid = self.request['uid']
     payment = Payments(self.context).get('stripe_payment')
     try:
         data = IPaymentData(self.context).data(order_uid)
         amount = data['amount']
         currency = data['currency']
         description = data['description']
         ordernumber = data['ordernumber']
         charge = stripe.Charge.create(
             amount=amount,
             currency=currency,
             description=description,
             source=token,
             metadata={
                 'ordernumber': ordernumber,
                 'order_uid': order_uid
             }
         )
         evt_data = {
             'charge_id': charge['id'],
         }
         payment.succeed(self.request, order_uid, evt_data)
         purge_cart(self.request)
         transaction.commit()
         redirect_url = '{base_url}/@@stripe_payment_success?uid={order_uid}'.format(
             base_url=base_url, order_uid=order_uid)
         return self.request.response.redirect(redirect_url)
     except Redirect as e:
         # simply re-raise error from above, otherwise it would get
         # caught in generel Exception catching block
         raise e
     except stripe.error.CardError as e:
         logger.error(format_traceback())
         body = e.json_body
         err = body.get('error', {})
         logger.error((
             'Failed to charge card\n'
             '    Status: {}\n'
             '    Type: {}\n'
             '    Code: {}\n'
             '    Message: {}'
         ).format(
             e.http_status,
             err.get('type'),
             err.get('code'),
             err.get('message')
         ))
         if not err.get('message'):
             message = 'Failed to charge card'
         else:
             message = err['message']
     except stripe.error.RateLimitError as e:
         logger.error(format_traceback())
         message = 'Too many requests made to the API too quickly'
     except stripe.error.InvalidRequestError as e:
         logger.error(format_traceback())
         message = 'Invalid parameters were supplied to Stripe\'s API'
     except stripe.error.AuthenticationError as e:
         logger.error(format_traceback())
         message = 'Authentication with Stripe\'s API failed'
     except stripe.error.APIConnectionError as e:
         logger.error(format_traceback())
         message = 'Network communication with Stripe failed'
     except stripe.error.StripeError as e:
         logger.error(format_traceback())
         message = 'Generic stripe error'
     except Exception as e:
         logger.error(format_traceback())
         message = 'General error'
     evt_data = {
         'charge_id': 'none',
     }
     payment.failed(self.request, order_uid, evt_data)
     transaction.commit()
     redirect_url = '{}/@@stripe_payment_failed?message={}'.format(
         base_url,
         message
     )
     raise Redirect(redirect_url)
Example #15
0
 def save(self, providers, widget, data):
     super(OrderCheckoutAdapter, self).save(providers, widget, data)
     order = self.order
     # order UUID
     uid = order.attrs['uid'] = uuid.uuid4()
     # order creator
     creator = None
     member = plone.api.user.get_current()
     if member:
         creator = member.getId()
     order.attrs['creator'] = creator
     # order creation date
     created = datetime.datetime.now()
     order.attrs['created'] = created
     cart_data = get_data_provider(self.context, self.request)
     # payment related information
     if cart_data.total > Decimal(0):
         payment_param = 'checkout.payment_selection.payment'
         pid = data.fetch(payment_param).extracted
         payment = Payments(self.context).get(pid)
         order.attrs['payment_method'] = pid
         if payment:
             order.attrs['payment_label'] = payment.label
         else:
             order.attrs['payment_label'] = _('unknown', default=u'Unknown')
     # no payment
     else:
         order.attrs['payment_method'] = 'no_payment'
         order.attrs['payment_label'] = _('no_payment',
                                          default=u'No Payment')
     # shipping related information
     if cart_data.include_shipping_costs:
         shipping_param = 'checkout.shipping_selection.shipping'
         sid = data.fetch(shipping_param).extracted
         shipping = Shippings(self.context).get(sid)
         order.attrs['shipping_method'] = sid
         order.attrs['shipping_label'] = shipping.label
         order.attrs['shipping_description'] = shipping.description
         try:
             shipping_net = shipping.net(self.items)
             shipping_vat = shipping.vat(self.items)
             order.attrs['shipping_net'] = shipping_net
             order.attrs['shipping_vat'] = shipping_vat
             order.attrs['shipping'] = shipping_net + shipping_vat
         # B/C for bda.plone.shipping < 0.4
         except NotImplementedError:
             shipping_net = shipping.calculate(self.items)
             order.attrs['shipping_net'] = shipping_net
             order.attrs['shipping_vat'] = Decimal(0)
             order.attrs['shipping'] = shipping_net
     # no shipping
     else:
         order.attrs['shipping_method'] = 'no_shipping'
         order.attrs['shipping_label'] = _('no_shipping',
                                           default=u'No Shipping')
         order.attrs['shipping_description'] = ''
         order.attrs['shipping_net'] = Decimal(0)
         order.attrs['shipping_vat'] = Decimal(0)
         order.attrs['shipping'] = Decimal(0)
     # create order bookings
     bookings = self.create_bookings(order)
     # set order state, needed for sorting in orders table
     order.attrs['state'] = calculate_order_state(bookings)
     # set order salaried, needed for sorting in orders table
     order.attrs['salaried'] = ifaces.SALARIED_NO
     # lookup booking uids, buyable uids and vendor uids
     booking_uids = list()
     buyable_uids = list()
     vendor_uids = set()
     for booking in bookings:
         booking_uids.append(booking.attrs['uid'])
         buyable_uids.append(booking.attrs['buyable_uid'])
         vendor_uids.add(booking.attrs['vendor_uid'])
     order.attrs['booking_uids'] = booking_uids
     order.attrs['buyable_uids'] = buyable_uids
     order.attrs['vendor_uids'] = list(vendor_uids)
     # cart discount related information
     cart_discount = cart_data.discount(self.items)
     order.attrs['cart_discount_net'] = cart_discount['net']
     order.attrs['cart_discount_vat'] = cart_discount['vat']
     # create ordernumber
     orders_soup = get_orders_soup(self.context)
     ordernumber = create_ordernumber()
     while self.ordernumber_exists(orders_soup, ordernumber):
         ordernumber = create_ordernumber()
     order.attrs['ordernumber'] = ordernumber
     # add order
     orders_soup.add(order)
     # add bookings
     bookings_soup = get_bookings_soup(self.context)
     # list containing items where stock threshold has been reached
     stock_threshold_reached_items = list()
     for booking in bookings:
         bookings_soup.add(booking)
         buyable = get_object_by_uid(self.context,
                                     booking.attrs['buyable_uid'])
         item_stock = get_item_stock(buyable)
         # no stock applied
         if item_stock is None:
             stock_warning_threshold = None
         else:
             stock_warning_threshold = item_stock.stock_warning_threshold
         if stock_warning_threshold:
             remaining = booking.attrs['remaining_stock_available']
             # stock threshold has been reached
             if remaining <= stock_warning_threshold:
                 stock_threshold_reached_items.append(booking.attrs)
     if stock_threshold_reached_items:
         event = events.StockThresholdReached(
             self.context,
             self.request,
             order.attrs['uid'],
             stock_threshold_reached_items,
         )
         notify(event)
     # return uid of added order
     return uid
    def verify(self):
        #
        # Get Payment details
        #
        # Get order
        order = None
        tickets = is_context_ticket(self.context)
        skip_payment = False

        order_data = {
            "order_id": "",
            "total": "",
            "shipping": "",
            "currency": "",
            "tax": "",
            "ticket": tickets,
            "download_link": None,
            "verified": False
        }

        data = self.request.form
        ordernumber = data.get('orderID', '')
        if ordernumber:
            order_uid = IPaymentData(self.context).uid_for(ordernumber)
            if get_status_category(int(data['STATUS'])) != SUCCESS_STATUS:
                return order_data
        else:
            order_uid = data.get('order_uid', '')
            if order_uid:
                try:
                    order = OrderData(self.context, uid=order_uid)
                except:
                    order = None
                if order:
                    if order.total > 0:
                        return order_data
                    else:
                        skip_payment = True
                else:
                    return order_data
            else:
                return order_data
        
        #
        # SHA passphrase verification
        #
        signer = OmnikassaSignature(data, 'sha512', SHA_OUT_PASSWORD)
        payment = Payments(self.context).get('omnikassa_payment')
        
        if not order:
            try:
                order = OrderData(self.context, uid=order_uid)
            except:
                order = None

        # Check if order exists   
        if order_uid != None and order != None:
            order = OrderData(self.context, uid=order_uid)
            order_nr = order.order.attrs['ordernumber']

            # Build order data
            order_data = {  
                "ordernumber": str(order_nr),
                "order_id": str(order_uid),
                "total": str(order.total),
                "shipping": str(order.shipping),
                "currency": str(order.currency),
                "tax": str(order.vat),
                "ticket": tickets,
                "download_link": None,
                "verified": False,
                "already_sent":False,
                "bookings":json.dumps([])
            }

            order_bookings = []
           
            for booking in order.bookings:
                try:
                    booking_uid = booking.attrs['buyable_uid']
                    item_number = booking.attrs['item_number']

                    if item_number:
                        sku = str(item_number)
                    else:
                        sku = str(booking_uid)

                    item_category = "Product" # Default category
                    if tickets:
                        item_category = "E-Ticket"

                    order_bookings.append({
                        'id':sku,
                        'price': str(float(booking.attrs['net'])),
                        'name': str(booking.attrs['title']),
                        'category': item_category,
                        'quantity': int(booking.attrs['buyable_count']),
                    })
                except:
                    pass

            try:
                order_data['bookings'] = json.dumps(order_bookings)
            except:
                # Invalid JSON format
                order_data['bookings'] = json.dumps([])

            if tickets:
                base_url = self.context.portal_url()
                params = "?order_id=%s" %(str(order_uid))
                download_as_pdf_link = "%s/download_as_pdf?page_url=%s/tickets/etickets%s" %(base_url, base_url, params)
                order_data['download_link'] = download_as_pdf_link

        else:
            # Order doesn't exist in the database
            # return blank ticket
            order_data = {
                "order_id": "",
                "total": "",
                "shipping": "",
                "currency": "",
                "tax": "",
                "ticket": tickets,
                "download_link": None,
                "verified": False
            }
            return order_data

        shasign = data.get('SHASIGN', '')
        if shasign == signer.signature() or skip_payment:
            order_data['verified'] = True
            order = OrderData(self.context, uid=order_uid)
            order.salaried = ifaces.SALARIED_YES
            if order.order.attrs['email_sent'] != 'yes':
                order.order.attrs['email_sent'] = 'yes'
                orders_soup = get_orders_soup(self.context)
                order_record = order.order
                orders_soup.reindex(records=[order_record])
                transaction.get().commit()
                if not skip_payment:
                    payment.succeed(self.context, order_uid)
                return order_data
            else:
                return order_data
        else:
            payment.failed(self.context, order_uid)
            return order_data
Example #17
0
 def __call__(self, **kw):
     uid = self.request['uid']
     payment = Payments(self.context).get('debit_order')
     payment.succeed(self.request, uid)
     url = '%s/@@debit_ordered?uid=%s' % (self.context.absolute_url(), uid)
     self.request.response.redirect(url)
 def __call__(self, **kw):
     uid = self.request['uid']
     payment = Payments(self.context).get('debit_order')
     payment.succeed(self.request, uid)
     url = '%s/@@debit_ordered?uid=%s' % (self.context.absolute_url(), uid)
     self.request.response.redirect(url)