Пример #1
0
def signature():
    url = request.args.get('url')
    import logging
    logging.error(url)
    ticket = LocalCache.get('TICKET_CACHE_KEY')
    if not ticket:
        token = WXClient.get_service_token()
        ticket_info = WXClient.get_js_ticket(token)
        if not ticket_info or ticket_info.get('errcode'):
            return Response(code=ResponseCode.OPERATE_ERROR,
                            msg='获取ticket失败').out()

        ticket = ticket_info.get('ticket')
        expire_time = ticket_info.get('expires_in')
        LocalCache.set('TICKET_CACHE_KEY',
                       ticket,
                       expire_time=expire_time - 100)

    time_stamp = int(time.time())
    noncestr = hashlib.md5(str(time.time())).hexdigest().lower()
    msgs = [['jsapi_ticket', ticket], ['noncestr', noncestr],
            ['timestamp', time_stamp], ['url', url]]

    signature = hashlib.sha1('&'.join(
        ['%s=%s' % (msg[0], msg[1]) for msg in msgs])).hexdigest()
    return Response(
        data={
            'appId': conf.wechat_app_id,
            'signature': signature,
            'timestamp': time_stamp,
            'nonceStr': noncestr
        }).out()
Пример #2
0
def payment_order():
    user = request.user
    item_id = request.args.get('item_id')
    item = PaymentItem.find(item_id)

    if user.openid or not item_id:
        order = Order(uid=user.id,
                      name=item.name,
                      money=-item.money,
                      balance=item.money + item.charge,
                      type=Order.Type.CHARGE)
        order.set_order_id()
        resp = order.save(return_keys=[Order.PKEY])
        order = Order.find(resp[Order.PKEY])

        wxorder = WXOrder(user, order)
        tokens = wxorder.get_token()
        if not tokens:
            return str(Response(code=ResponseCode.OPERATE_ERROR, msg='订单生成失败'))

        return str(Response(data={'order_id': order.id, 'order': tokens}))
    elif not user.openid:
        return str(Response(code=ResponseCode.AUTH_REQUIRED, msg='请微信关注服务号'))
    else:
        return str(Response(code=ResponseCode.PARAMETER_ERROR, msg='参数错误'))
Пример #3
0
def create_event():
    ev = Event()
    ev.fee = int(request.form.get('fee', 0)) * 100
    if ev.fee < 0:
        return Response(code=ResponseCode.PARAMETER_ERROR, msg='输入收费错误').out()
    ev.shop_id = request.form.get('shop_id', 0)
    ev.show_num = request.form.get('show_num') == 'on'
    ev.title = request.form.get('title')
    ev.user_limit = request.form.get('user_limit', 0)
    ev.description = request.form.get('description')
    ev.creator = request.user.id
    ev.open_at = request.form.get('open_at')
    ev.close_at = request.form.get('close_at')

    file = request.files.get('poster')
    if not file or file.filename == '':
        return Response(code=ResponseCode.OPERATE_ERROR, msg='请选择上传文件').out()
    elif allowed_file(file.filename):
        filename = '%s_%s' % (request.user.id,
                              datetime.now().strftime('%Y%m%d%H%M%S'))
        QiniuCloud.upload_file(file, filename, conf.qiniu_img_bucket)
        ev.poster_url = conf.qiniu_img_prefix + filename
        ev.save()
    else:
        return Response(code=ResponseCode.OPERATE_ERROR,
                        msg='请选择正确的上传格式文件').out()

    return str(Response())
Пример #4
0
def delete_event(event_id=0):
    ev = Event.find(event_id)
    if ev.creator != request.user.id:
        return Response(code=ResponseCode.OPERATE_ERROR, msg='没有权限').out()
    ev.state = Event.State.DELETED
    ev.save()
    return Response().out()
Пример #5
0
def _pay_cart_with_balance(carts):
    user = request.user
    money = 0
    name = ''

    for each in carts:
        pd = Product.find(each['product_id'])
        money += pd.price * each['num']
        if name:
            name = '%s,%sx%s' % (name, pd.name, each['num'])
        else:
            name = '%sx%s' % (pd.name, each['num'])

    if user.balance >= money:
        for each in carts:
            ct = Cart(**each)
            ct.state = Cart.State.FINISHED
            ct.save()

        order = Order(uid=user.id,
                      name=name,
                      balance=-money,
                      type=Order.Type.PAY)
        order.set_order_id()
        order.state = Order.State.FINISHED
        resp = order.save(return_keys=[Order.PKEY])
        order = Order.find(resp[Order.PKEY])

        user.balance -= money
        user.save()
        return Response(data=order.to_dict()).out()
    elif user.openid:
        order = Order(uid=user.id,
                      name=name,
                      money=user.balance - money,
                      balance=-user.balance,
                      type=Order.Type.PAY)
        order.set_order_id()
        resp = order.save(return_keys=[Order.PKEY])
        order = Order.find(resp[Order.PKEY])

        wxorder = WXOrder(user, order)
        tokens = wxorder.get_token()
        if not tokens:
            return Response(code=ResponseCode.OPERATE_ERROR,
                            msg='订单生成失败').out()

        return Response(code=ResponseCode.LOW_BALANCE,
                        msg='余额不足',
                        data={
                            'need_money': money - user.balance,
                            'order_id': order.id,
                            'order': tokens
                        }).out()
    else:
        return str(Response(code=ResponseCode.AUTH_REQUIRED, msg='请微信关注服务号'))
Пример #6
0
def delete_cart():
    cart_id = request.form['cart_id']
    cart = Cart.query_instance(id=cart_id, uid=request.user.id)

    if not cart:
        return str(Response(code=ResponseCode.DATA_NOT_EXIST, msg='数据不存在'))

    cart.state = Cart.State.CANCELED
    cart.save()
    return Response(data=cart.to_dict()).out()
Пример #7
0
def order(order_id=0):
    order = Order.find(order_id)
    if order.uid != request.user.id:
        return Response(code=ResponseCode.OPERATE_ERROR,
                        msg='没有权限查看他人订单').out()

    resp = order.to_dict()
    resp['user_name'] = request.user.name
    time.sleep(0.5)
    return Response(data=resp).out()
Пример #8
0
def update_cart():
    cart_id = request.form['cart_id']
    num = request.form['num']
    cart = Cart.query_instance(id=cart_id, uid=request.user.id)

    if not cart:
        return str(Response(code=ResponseCode.DATA_NOT_EXIST, msg='数据不存在'))

    cart.num = num
    cart.save()
    return Response(data=cart.to_dict()).out()
Пример #9
0
def cancel_event(event_id=0):
    ev = Event.find(event_id)
    user = request.user
    user_ev = UserEvent.query(uid=user.id, event_id=ev.id)
    if not user_ev or user_ev['state'] != UserEvent.State.INIT:
        return Response(code=ResponseCode.DATA_NOT_EXIST, msg='暂无报名').out()

    user_ev = UserEvent(**user_ev)
    user_ev.state = UserEvent.State.CANCELED
    user_ev.save()
    return Response().out()
Пример #10
0
def pay_cart():
    carts = Cart.query(fetchone=False,
                       uid=request.user.id,
                       state=Cart.State.INIT)

    if not carts:
        return Response(code=ResponseCode.DATA_NOT_EXIST, msg='购物车内没有物品').out()

    if request.user.balance <= 0 and request.user.coupon > 0:
        return _pay_cart_with_coupon(carts)
    elif request.user.balance >= 0 and request.user.coupon <= 0:
        return _pay_cart_with_balance(carts)
    else:
        return Response(code=ResponseCode.UNKNOWN).out()
Пример #11
0
def _pay_cart_with_coupon(carts):
    user = request.user

    if user.is_founder():
        discount = 0.4
    elif user.is_cofounder():
        discount = 0.3
    else:
        discount = 0.2

    money = 0
    name = ''
    for each in carts:
        pd = Product.find(each['product_id'])
        money += pd.price * each['num']
        if name:
            name = '%s,%sx%s' % (name, pd.name, each['num'])
        else:
            name = '%sx%s' % (pd.name, each['num'])

    discount_money = min(user.coupon, int(money * discount))
    need_money = money - discount_money

    if user.openid:
        order = Order(uid=user.id,
                      name=name,
                      money=-need_money,
                      coupon=-discount_money,
                      type=Order.Type.PAY)
        order.set_order_id()
        resp = order.save(return_keys=[Order.PKEY])
        order = Order.find(resp[Order.PKEY])

        wxorder = WXOrder(user, order)
        tokens = wxorder.get_token()
        if not tokens:
            return str(Response(code=ResponseCode.OPERATE_ERROR, msg='订单生成失败'))

        return str(
            Response(code=ResponseCode.LOW_BALANCE,
                     msg='余额不足',
                     data={
                         'need_money': need_money,
                         'order_id': order.id,
                         'order': tokens
                     }))
    else:
        return str(Response(code=ResponseCode.AUTH_REQUIRED, msg='请微信关注服务号'))
Пример #12
0
def buy(product_id=0):
    if request.user.balance <= 0 and request.user.coupon > 0:
        return _buy_product_with_balance(product_id)
    elif request.user.balance > 0 and request.user.coupon <= 0:
        return _buy_product_with_coupon(product_id)
    else:
        return Response(code=ResponseCode.UNKNOWN).out()
Пример #13
0
def all_orders():
    if not request.user.is_employee():
        return Response(code=ResponseCode.OPERATE_ERROR, msg='没有权限').out()
    max_id = request.args.get('max_id', 0)
    orders = Order.query(fetchone=False,
                         state=Order.State.FINISHED,
                         orderby='id asc',
                         extra={'id>': max_id})
    resp = []
    for each in orders:
        data = Order(**each).to_dict()
        user = User.find(each['uid'])
        data['user_name'] = user.name
        resp.append(data)

    return Response(data=resp).out()
Пример #14
0
def buy_item(item_id=0):
    it = PaymentItem.find(item_id)
    user = request.user

    user.balance += user.balance + it.money + it.charge
    user.save()

    return Response(data=it.to_dict()).out()
Пример #15
0
    def wraper(*args, **argv):
        uid = request.cookies.get('uid')
        session = request.cookies.get('session')
        user = None
        need_cookie = False
        if uid:
            user = User.query_instance(id=uid, session_data=session)
        if not user and request.args.get('code'):
            code = request.args.get('code')
            token = WXClient.get_wx_token(conf.wechat_app_id,
                                          conf.wechat_secret, code)
            if token and token.get('errcode') is None:
                need_cookie = True
                openid = token.get('openid')
                access_token = token.get('access_token')
                user = User.query_instance(openid=openid)
                if user:
                    user.access_token = access_token
                    user.update_session()
                    user.save()
                else:
                    user = User()
                    user.openid = openid
                    user.access_token = access_token
                    user.update_session()
                    if _signup(user):
                        user.save()
                        user = User.query_instance(openid=openid, master=True)

                        WXClient.send_signup_msg(user, {"openid": openid})
                    else:
                        return str(
                            Response(code=ResponseCode.OPERATE_ERROR,
                                     msg='获取用户资料失败'))

        if user:
            request.user = user

            resp = make_response(func(*args, **argv))
            resp.mimetype = 'application/json'
            if need_cookie:
                resp.set_cookie('uid', '%s' % user.id)
                resp.set_cookie('session', user.session_data)
            return resp

        return str(Response(code=ResponseCode.AUTH_REQUIRED, msg='请先登录'))
Пример #16
0
def add_cart():
    product_id = request.form['product_id']
    if not product_id or not Product.find(product_id):
        return str(Response(code=ResponseCode.DATA_NOT_EXIST, msg='商品不存在'))

    cart = Cart.query_instance(uid=request.user.id,
                               product_id=product_id,
                               state=Cart.State.INIT)
    if cart:
        cart.num += 1
    else:
        cart = Cart()
        cart.uid = request.user.id
        cart.product_id = product_id
    ct = cart.save(return_keys=[Cart.PKEY])
    cart = Cart.find(ct[Cart.PKEY])

    return Response(data=cart.to_dict()).out()
Пример #17
0
def pay_cart_with_coupon():
    carts = Cart.query(fetchone=False,
                       uid=request.user.id,
                       state=Cart.State.INIT)

    if not carts:
        return Response(code=ResponseCode.DATA_NOT_EXIST, msg='购物车内没有物品').out()

    return _pay_cart_with_coupon(carts)
Пример #18
0
def _buy_product_with_balance(product_id):
    pd = Product.find(product_id)
    user = request.user

    if user.balance >= pd.price:
        order = Order(uid=user.id,
                      name=pd.name,
                      money=user.balance - pd.price,
                      balance=-user.balance,
                      type=Order.Type.PAY)
        order.set_order_id()
        order.save()

        user.balance -= pd.price
        user.save()

        return Response(data=pd.to_dict()).out()
    elif user.openid:
        order = Order(uid=user.id,
                      name=pd.name,
                      money=user.balance - pd.price,
                      balance=-user.balance,
                      type=Order.Type.PAY)
        order.set_order_id()
        order.save()

        order = WXOrder(user, order)

        tokens = order.get_token()
        if not tokens:
            return Response(code=ResponseCode.OPERATE_ERROR,
                            msg='订单生成失败').out()

        return Response(code=ResponseCode.LOW_BALANCE,
                        msg='余额不足',
                        data={
                            'need_money': pd.price - user.balance,
                            'order': tokens
                        }).out()
    else:
        return str(Response(code=ResponseCode.AUTH_REQUIRED, msg='请微信关注服务号'))
Пример #19
0
def join_event(event_id=0):
    ev = Event.find(event_id)
    user = request.user
    user_ev = UserEvent.query(uid=user.id, event_id=ev.id)
    if user_ev and user_ev['state'] == UserEvent.State.INIT:
        return Response(code=ResponseCode.DUPLICATE_DATA, msg='已经报名成功').out()

    if ev.fee <= 0:
        if user_ev:
            user_ev = UserEvent(**user_ev)
            user_ev.state = UserEvent.State.INIT
            user_ev.save()
        else:
            UserEvent(uid=user.id, event_id=ev.id).save()

        return Response().out()
    elif user.openid:
        order = Order(uid=user.id,
                      name=ev.title,
                      money=-ev.fee,
                      item_id=ev.id,
                      type=Order.Type.JOIN_EVENT)
        order.set_order_id()
        resp = order.save(return_keys=[Order.PKEY])
        order = Order.find(resp[Order.PKEY])

        wxorder = WXOrder(user, order)
        tokens = wxorder.get_token()
        if not tokens:
            return Response(code=ResponseCode.OPERATE_ERROR,
                            msg='订单生成失败').out()

        return Response(code=ResponseCode.LOW_BALANCE,
                        msg='余额不足',
                        data={
                            'need_money': ev.fee,
                            'order_id': order.id,
                            'order': tokens
                        }).out()
    else:
        return str(Response(code=ResponseCode.AUTH_REQUIRED, msg='请微信关注服务号'))
Пример #20
0
def event(event_id=0):
    ev = Event.find(event_id)
    resp = ev.to_dict()
    resp['creator'] = ev.get_creator().to_dict()
    resp['num'] = UserEvent.count(event_id=ev.id, state=UserEvent.State.INIT)
    resp['member'] = 0

    if request.user and UserEvent.query(
            event_id=ev.id, uid=request.user.id, state=UserEvent.State.INIT):
        resp['member'] = 1

    return str(Response(data=resp))
Пример #21
0
def events():
    evs = Event.query(fetchone=False,
                      extra={"state <": Event.State.DELETED},
                      orderby='open_at asc')
    resp = []
    for each in evs:
        ev = Event(**each)
        r = ev.to_dict()
        r['creator'] = ev.get_creator().to_dict()
        r['num'] = UserEvent.count(event_id=ev.id, state=UserEvent.State.INIT)
        resp.append(r)
    return str(Response(data=resp))
Пример #22
0
def joined_events():
    evs = UserEvent.query(fetchone=False,
                          uid=request.user.id,
                          state=UserEvent.State.INIT,
                          orderby='id desc')
    resp = []
    for each in evs:
        ev = Event.find(each['event_id'])
        r = ev.to_dict()
        r['join_at'] = dt_to_str(each['create_at'])
        resp.append(r)
    return Response(data=resp).out()
Пример #23
0
def published_events():
    evs = Event.query(fetchone=False,
                      creator=request.user.id,
                      extra={"state <": Event.State.DELETED},
                      orderby='id desc')
    resp = []
    for each in evs:
        ev = Event(**each)
        r = ev.to_dict()
        r['num'] = UserEvent.count(event_id=ev.id, state=UserEvent.State.INIT)
        resp.append(r)
    return str(Response(data=resp))
Пример #24
0
def pay_order(order_id=0):
    order = Order.find(order_id)

    user = request.user
    if order.state != Order.State.NORMAL or user.balance + order.balance < 0 or user.coupon + order.coupon < 0:
        return str(Response(code=ResponseCode.DATA_NOT_EXIST, msg='订单已失效'))

    if order.money < 0:
        if user.openid:
            wxorder = WXOrder(user, order)
            tokens = wxorder.get_token()
            if not tokens:
                return str(
                    Response(code=ResponseCode.OPERATE_ERROR, msg='订单生成失败'))

            return str(Response(data=tokens))
        elif not user.openid:
            return str(
                Response(code=ResponseCode.AUTH_REQUIRED, msg='请微信关注服务号'))
        else:
            return str(Response(code=ResponseCode.PARAMETER_ERROR, msg='参数错误'))
    else:
        user.balance += order.balance
        user.coupon += order.coupon
        user.save()
        order.close()
        return Response().out()
Пример #25
0
def edit_event(event_id=0):
    ev = Event.find(event_id)
    ev.fee = int(request.form.get('fee', 0)) * 100
    if ev.fee < 0:
        return Response(code=ResponseCode.PARAMETER_ERROR, msg='输入收费错误').out()
    ev.shop_id = request.form.get('shop_id', 0)
    ev.show_num = request.form.get('show_num') == 'on'
    ev.title = request.form.get('title')
    ev.user_limit = request.form.get('user_limit', 0)
    ev.description = request.form.get('description')
    ev.open_at = request.form.get('open_at')
    ev.close_at = request.form.get('close_at')

    file = request.files.get('poster')
    if file and file.filename != "" and allowed_file(file.filename):
        filename = '%s_%s' % (request.user.id,
                              datetime.now().strftime('%Y%m%d%H%M%S'))
        QiniuCloud.upload_file(file, filename, conf.qiniu_img_bucket)
        ev.poster_url = conf.qiniu_img_prefix + filename
    ev.save()

    return str(Response())
Пример #26
0
def cart():
    carts = Cart.query(fetchone=False,
                       uid=request.user.id,
                       state=Cart.State.INIT)
    resp = []
    for each in carts:
        pd = Product.find(each['product_id'])
        cart = Cart(**each).to_dict()
        cart['product_name'] = pd.name
        cart['product_price'] = pd.price
        cart['product_icon'] = pd.icon
        resp.append(cart)
    return str(Response(data=resp))
Пример #27
0
def _buy_product_with_coupon(product_id):
    pd = Product.find(product_id)
    user = request.user
    if user.is_founder():
        discount = 0.4
    elif user.is_cofounder():
        discount = 0.3
    else:
        discount = 0.2

    discount_money = min(user.coupon, int(pd.price * discount))
    need_money = pd.price - discount_money

    if user.openid:
        order = Order(uid=user.id,
                      name=pd.name,
                      money=-need_money,
                      coupon=-discount_money,
                      type=Order.Type.PAY)
        order.set_order_id()
        order.save()

        wxorder = WXOrder(user, order)
        tokens = wxorder.get_token()
        if not tokens:
            return str(Response(code=ResponseCode.OPERATE_ERROR, msg='订单生成失败'))

        return str(
            Response(code=ResponseCode.LOW_BALANCE,
                     msg='余额不足',
                     data={
                         'need_money': need_money,
                         'order': tokens
                     }))
    else:
        return str(Response(code=ResponseCode.AUTH_REQUIRED, msg='请微信关注服务号'))
Пример #28
0
def user_event(event_id=0):
    ev = Event.find(event_id)
    ev_user = UserEvent.query(fetchone=False,
                              event_id=ev.id,
                              state=UserEvent.State.INIT,
                              orderby='id desc')
    resp = ev.to_dict()
    users = []
    for each in ev_user:
        user = User.find(each['uid'])
        r = user.json()
        r['join_at'] = dt_to_str(each['create_at'])
        users.append(r)

    resp['users'] = users
    resp['num'] = len(users)
    return Response(data=resp).out()
Пример #29
0
def product(product_id=0):
    product = Product.find(product_id)
    return Response(data=product.to_dict()).out()
Пример #30
0
def products():
    shop_id = request.args.get('shop_id', Shop.GEHUA)
    products = Product.query(fetchone=False, shop_id=shop_id) or []
    return Response(data=[Product(**each).to_dict()
                          for each in products]).out()