Example #1
0
def pay_status(order_no):
    if not current_user.is_authenticated:
        return json_resp.failedByUnauthenticated()
    flag, result = order_interface.status(order_no, current_user.open_id)
    if not flag:
        return json_resp.failed(message=result)
    return json_resp.success(data={'status': result})
Example #2
0
File: info.py Project: ws999/wx-app
def redpacket_in_log():
    if not current_user.is_authenticated:
        return json_resp.failedByUnauthenticated()
    per_page = request.args.get('per_page', 6)
    page = request.args.get('page', 1)
    per_page = int(per_page) if isinstance(per_page,
                                           int) or per_page.isdigit() else 6
    page = int(page) if isinstance(page, int) or page.isdigit() else 1

    userop = current_user.get_operator()
    rp_in_log, count, total = userop.redpacket_in_log(page, per_page)
    value = sum(
        RedPacketLog.objects.filter(
            open_id=current_user.open_id).values_list('value')) / 100.0

    logger.info('redpacket_in_log:%s-page%s/%s_per%s' %
                (current_user.open_id, page, total, per_page))
    data = {
        'total': total,
        'rp_in_log': rp_in_log,
        'page': page,
        'count': count,
        'amount_total': value
    }
    return json_resp.success(data=data)
Example #3
0
File: info.py Project: ws999/wx-app
def get_info():
    if not current_user.is_authenticated:
        return json_resp.failedByUnauthenticated()
    data = current_user.info
    data.update({'capital': current_user.capital / 100.0})
    data.pop('_id', '')
    data.pop('open_id', '')
    data.pop('union_id', '')
    return json_resp.success(data=data)
Example #4
0
def order_create():
    if not current_user.is_authenticated:
        return json_resp.failedByUnauthenticated()
    open_id = current_user.open_id
    args = request.form.to_dict()
    logger.info('[create_order] %s' % (args))
    product_type = args.pop('product_type', '')
    pay_type = args.pop('pay_type', '')
    amount = args.pop('amount', '')
    try:
        product_type = int(product_type)
        pay_type = int(pay_type)
    except:
        return json_resp.failedByParameter(
            'product_type and pay_type should be int')
    try:
        amount = int(float(amount) * 100)
    except:
        return json_resp.failedByParameter('amount should be float')

    # 1.产品订单接口类
    order_iface = order_interface.get_order_iface(product_type)
    if not order_iface:
        return json_resp.failed(message='unknown product_type')
    # 2.生成订单号
    order_no = order_iface.general_order_no(pay_type)
    if not order_no:
        return json_resp.failed(message='unknown pay_type')
    # 3.创建订单
    try:
        data = order_iface.create(open_id,
                                  product_type,
                                  order_no,
                                  pay_type,
                                  amount=amount)
    except Exception as e:
        return json_resp.failed(message=str(e))

    result_data = {'order_no': order_no}
    if pay_type == UserOrder.PAY_TYPE_WX:  # 微信
        wxpay_order = wxpay.create_unifiedorder(
            data['title'],
            order_no,
            int(data['price_pay']),
            open_id,
            spbill_create_ip=request.environ.get('REMOTE_ADDR'))
        logger.info('wxpay_order:%s' % wxpay_order)
        wxpay_jsapi_args = wxpay.get_jsapi_request_args(
            wxpay_order['prepay_id'])
        result_data['wxpay_jsapi_args'] = wxpay_jsapi_args

    return json_resp.success(data=result_data)
Example #5
0
def red_packet_collect_report(redpacket_id):
    if not current_user.is_authenticated:
        return json_resp.failedByUnauthenticated()
    redpacket = RedPacket.get_packet_all(redpacket_id)
    if not redpacket:
        return json_resp.failed(message='红包不存在')
    try:
        challenge = redpacket.collect_report(current_user.open_id,
                                             RedPacketCollectLog.STATUS_FAIL)
    except:
        challenge = 0
        logger.error('collect failed report faild(%s)' %
                     (current_user.open_id))
    return json_resp.success(data={'challenge': challenge})
Example #6
0
def uploadimg():
    file = request.files.get('file')
    dirname = request.form.get('type', 'redpacket')
    try:
        img = Image.open(file)
        alpha = min(img.size) / 100.0
        img = img.resize([int(s / alpha) for s in img.size])
        img = img.crop((0, 0, 100, 100))
        imgname = imgpro.save_img_to_disk(img, dirname)
    except Exception as e:
        logger.error('parse picture failed: %s' % e)
        return json_resp.failed(message='图片解析失败')
    filepath = os.path.join(config.MAIN_SITE, config.server_static_file,
                            dirname, imgname)
    logger.info('save file: %s' % filepath)
    return json_resp.success(data={'imgurl': filepath})
Example #7
0
def red_packet_collect(redpacket_id):
    if not current_user.is_authenticated:
        return json_resp.failedByUnauthenticated()
    redpacket = RedPacket.get_packet(redpacket_id)
    userop = current_user.get_operator()
    if not redpacket:
        return json_resp.failed(message='红包不存在或已过期')
    open_id = current_user.open_id

    if not redpacket.could_collect:
        return json_resp.failed(message='红包已经被领光啦~')

    has_collect, value = RedPacket.has_collect(redpacket_id, open_id)
    if has_collect:
        return json_resp.failed(message='您已经领取过啦~',
                                data={'value', value / 100.0})
    logger.info('collect redpcaket: %s_%s' % (open_id, redpacket_id))
    value, rpl_id = RedPacket.collect_redpacket(redpacket_id, open_id)
    if not value:
        return json_resp.failed('领取失败~')
    userop.change_capital(CapitalLog.REASON_COLLECT, value, str(rpl_id))
    try:
        redpacket.collect_report(open_id, RedPacketCollectLog.STATUS_SUCCESS,
                                 rpl_id)
    except:
        logger.error('collect success report faild(%s,%s)' % (open_id, rpl_id))

    redpacket = RedPacket.get_packet_all(redpacket_id)
    redpacket_data = redpacket._data
    redpacket_data.update({
        'user_nickname': current_user.nickname,
        'user_avatar': current_user.avatar
    })
    redpacket_data['amount'] = redpacket_data['amount'] / 100.0
    has_collect = RedPacket.has_collect(
        redpacket_id,
        current_user.open_id) if current_user.is_authenticated else False
    redpacket_data.update({
        'has_collect': has_collect,
        'could_collect': redpacket.could_collect
    })

    return json_resp.success(data={
        'value': value / 100.0,
        'redpacket': redpacket_data
    })
Example #8
0
File: info.py Project: ws999/wx-app
def capital_log():
    if not current_user.is_authenticated:
        return json_resp.failedByUnauthenticated()
    per_page = request.args.get('per_page', 6)
    page = request.args.get('page', 1)
    per_page = int(per_page) if isinstance(per_page,
                                           int) or per_page.isdigit() else 6
    page = int(page) if isinstance(page, int) or page.isdigit() else 1

    userop = current_user.get_operator()
    result, count, total = userop.capital_log(page, per_page)
    logger.info('capital_log:%s-page%s/%s_per%s' %
                (current_user.open_id, page, total, per_page))
    return json_resp.success(data={
        'total': total,
        'result': result,
        'page': page
    })
Example #9
0
File: info.py Project: ws999/wx-app
def set_info():
    if not current_user.is_authenticated:
        return json_resp.failedByUnauthenticated()
    args = request.form
    nickname = args.get('nickname', '')
    avatar = args.get('avatar', '')
    gender = args.get('gender', 'UNKNOW')
    province = args.get('province', '')
    city = args.get('city', '')
    intro = args.get('intro', '')
    if not gender in User.OPTIONS_GENDER.keys():
        return json_resp.failedByParameter('gender')

    user_id = current_user._id
    userop = current_user.get_operator()
    r = userop.set_info(user_id, nickname, avatar, gender, province, city,
                        intro)
    if r:
        return json_resp.success()
    elif r == -1:
        return json_resp.failed(message='用户不存在')
    else:
        return json_resp.failed()
Example #10
0
File: info.py Project: ws999/wx-app
def capital():
    if not current_user.is_authenticated:
        return json_resp.failedByUnauthenticated()
    value = 0 if not current_user else current_user.capital
    logger.info('get_capital:%s_%s' % (current_user.open_id, value))
    return json_resp.success(data={'capital': value / 100.0})
Example #11
0
def transfer_wx():
    if not current_user.is_authenticated:
        return json_resp.failedByUnauthenticated()
    open_id = current_user.open_id
    args = request.form.to_dict()
    if not args: args = request.args.to_dict()
    pay_type = args.pop('pay_type', '')
    product_type = args.pop('product_type', '')
    amount = args.pop('amount', '')
    try:
        pay_type = int(pay_type)
        product_type = int(product_type)
        amount = int(float(amount) * 100)
    except:
        return json_resp.failedByParameter(
            'amount, pay_type and product_type should be int')

    # 1.产品订单接口类
    order_iface = order_interface.get_order_iface(product_type)
    if not order_iface:
        return json_resp.failed(message='unknown product_type')

    # 2.生成订单号
    order_no = order_iface.general_order_no(pay_type)
    if not order_no:
        return json_resp.failed(message='unknown pay_type')
    try:  # 创建订单
        data = order_iface.create(open_id,
                                  product_type,
                                  order_no,
                                  pay_type,
                                  amount=amount)
        # 生成请求参数
        request_body = wxtransfer.get_transfer_args(
            order_no,
            amount,
            open_id,
            data.get('desc', '红包余额提取到微信'),
            spbill_create_ip=request.environ.get('REMOTE_ADDR'))
    except Exception as e:
        return json_resp.failed(message=str(e))
    # 扣除红包账户余额
    logger.info('扣除 %s 账户余额 %s' % (open_id, amount))
    userop = current_user.get_operator()
    flag, cl_id = userop.change_capital(CapitalLog.REASON_TOCASH, -amount)
    if not flag:
        logger.error('扣除失败 %s 账户余额失败 %s' % (open_id, amount))
        return json_resp.failed(message='账户余额不足')
    # 请求wx remote
    flag, msg = wxtransfer.request_transfer(request_body)
    if not flag:
        logger.error('提现失败(%s,%s)' % (open_id, amount))
        return json_resp.failed(message='提现失败,如余额已扣除请联系客服')
    # 更新关联信息
    flag, order_id = order_iface.set_success(order_no, datetime.datetime.now(),
                                             msg)
    if not flag:
        logger.error('关联信息更新失败(%s,%s,%s)' %
                     (order_no, datetime.datetime.now(), msg))
        return json_resp.success(data={
            'amount': amount / 100.0,
            'status': 'SUCCESS'
        })
    CapitalLog.objects.filter(_id=cl_id).update_one(set__remark=str(order_id))
    return json_resp.success(data={
        'amount': amount / 100.0,
        'status': 'SUCCESS'
    })
Example #12
0
def red_packet_detail(redpacket_id):
    _id = bson.ObjectId(redpacket_id)
    redpacket = RedPacket.get_packet_all(_id)
    if not redpacket:
        return json_resp.failed(message='红包不存在')
    user = User.objects.filter(open_id=redpacket.open_id).first()
    redpacket_data = redpacket._data
    redpacket_data.update({
        'user_nickname': user.nickname,
        'user_avatar': user.avatar
    })
    redpacket_data['amount'] = redpacket_data['amount'] / 100.0
    if current_user.is_authenticated:
        has_collect, value = RedPacket.has_collect(_id, current_user.open_id)
        challenge = RedPacketCollectLog.objects.filter(
            redpacket_id=bson.ObjectId(redpacket_id),
            open_id=current_user.open_id).count()
    else:
        has_collect, value = False, 0
        challenge = 0
    redpacket_data.update({
        'has_collect': has_collect,
        'challenge': challenge,
        'could_collect': redpacket.could_collect,
        'value': value
    })

    logger.info('redpacket_data:%s' % (redpacket_id))

    redpacketlog = RedPacketLog.objects.filter(
        redpacket_id=bson.ObjectId(redpacket_id),
        status=RedPacketLog.STATUS_DONE).order_by('-last_modify')
    userop = current_user.get_operator()
    redpacketlog_data = []
    for rpl in redpacketlog:
        data = rpl._data
        data.pop('_id')
        data.pop('redpacket_id')
        data.pop('status')
        data['value'] = data['value'] / 100.0
        challenge = RedPacketCollectLog.objects.filter(
            redpacket_id=bson.ObjectId(redpacket_id),
            open_id=data['open_id']).count()
        data.update({
            'rp_user': userop.get_info(data['open_id']),
            'challenge': challenge
        })
        redpacketlog_data.append(data)
    logger.info('redpacket_log:%s' % (redpacket_id))

    rp_faillog = RedPacketCollectLog.objects.filter(
        redpacket_id=bson.ObjectId(redpacket_id))
    redpacketlogfail_data = []
    fail_openids = set()
    for rpfl in rp_faillog:
        fail_openids.add(rpfl.open_id)
    for open_id in fail_openids:
        if rp_faillog.filter(open_id=open_id,
                             status=RedPacketCollectLog.STATUS_SUCCESS):
            continue
        failsobj = rp_faillog.filter(open_id=open_id).order_by('-last_modify')
        challenge = failsobj.count()
        create_time = formatter.time2str(failsobj.first().create_time)
        data = {
            'rp_user': userop.get_info(open_id),
            'challenge': challenge,
            'last_fail_time': create_time
        }
        redpacketlogfail_data.append(data)

    logger.info('redpacket_fail_log:%s' % (redpacket_id))

    return json_resp.success(
        data={
            'redpacket': redpacket_data,
            'redpacketlog': redpacketlog_data,
            'redpacketlog_fail': redpacketlogfail_data
        })
Example #13
0
def red_packet_create():
    if not current_user.is_authenticated:
        return json_resp.failedByUnauthenticated()
    token = request.args.get('token', '')
    args = request.form
    _id = bson.ObjectId()
    total_value = args.get('amount')
    number = args.get('number')
    title = args.get('title')
    level = args.get('level')
    poster = args.get('poster')
    try:
        postername = os.path.split(poster)[-1]
        posterurl = os.path.join(config.server_static_file, 'redpacket',
                                 postername)
        assert os.path.exists(posterurl)
    except AssertionError:
        # TODO 无图片则选择默认图片
        logger.error('can\'t find img: %s' % poster)
        return json_resp.failed(message='红包图片不存在')
    except:
        logger.error('invalid img path: %s' % poster)
        return json_resp.failed(message='图片地址不合法')

    try:
        amount = int(float(total_value) * 100)
        number = int(number)
        level = int(float(level))
    except:
        return json_resp.failed(message='invalid amount or number')
    if amount > current_user.capital:
        charge = amount - current_user.capital
        logger.info('%s余额不足, 需充值%s' % (current_user.open_id, charge))
        host = request.host_url.replace('http://', 'https://')
        url = host + url_for('order.order_create').strip(
            '/') + '?token=%s' % token
        params = {
            'product_type': 1,
            'pay_type': 0,
            'amount': '%.2f' % (charge / 100.0)
        }
        logger.info('local request (%s,%s)' % (url, params))
        try:
            resp = requests.post(
                url=url,
                data=params,
                timeout=3,
                headers={'content-type': 'application/x-www-form-urlencoded'})
            logger.info('local request create order:%s' % resp.content)
            data = json.loads(resp.content).get('data')
        except Exception as e:
            logger.error('local request create order err: %s' % e)
            return json_resp.failed('创建订单失败')
        return json_resp.failed(data=data, code=-5)
    userop = current_user.get_operator()
    flag, msg = userop.change_capital(reason=CapitalLog.REASON_DELIVER,
                                      value=-amount)
    if not flag:
        return json_resp.failed(message=msg)

    rp_id = RedPacket.create_redpacket(current_user.open_id, amount, number,
                                       title, level, posterurl, _id)
    if not rp_id: return json_resp.failed(message=rp_id)
    CapitalLog.objects.filter(_id=msg).update_one(set__remark=str(rp_id))
    red_packet = RedPacket.get_packet(rp_id)
    data = red_packet._data
    data['amount'] = data['amount'] / 100.0
    return json_resp.success(data=data)