示例#1
0
文件: wxqrimg.py 项目: ws999/wx-app
def create():
    args = request.args.to_dict()
    redpacket_id = args.get('redpacket_id', '')
    shape = args.get('shape', '')
    logger.info('blend img redpacket_id:%s shape:%s' % (redpacket_id, shape))

    if not shape in ['circle']:
        return json_resp.failedByParameter('shape')
    redpacket = RedPacket.get_packet(redpacket_id)
    if not redpacket:
        return json_resp.failed(message='红包不存在或已过期')
    user = User.objects.filter(open_id=redpacket.open_id).first()
    if not user:
        return json_resp.failed(message='未找到红包来源')
    rp_url = 'pages/detail/detail'
    img_qr = wxqr.get_wx_qr(rp_url, redpacket_id)  # 获取圆形二维码
    if not img_qr:
        logger.error('微信二维码服务异常')
        img_qr = os.path.join('.', config.server_static_file, 'wx_qr',
                              'default_qr.png')

    try:  # 保存至本地
        img_qr = imgpro.fill_circle_qr(img_qr)
        filename = imgpro.save_img_to_disk(img_qr,
                                           'wx_qr',
                                           filename=str(redpacket_id))
        logger.info('save img to localdisk success: %s' % filename)
    except:
        logger.error('save img to localdisk failed: %s' % redpacket_id)

    cimg = imgpro.img2stringio(img_qr)
    return ImgResponse(cimg)
示例#2
0
文件: wxqrimg.py 项目: ws999/wx-app
def blend():
    redpacket_id = request.args.get('redpackey_id', '')
    redpacket = RedPacket.get_packet(redpacket_id)
    if not redpacket:
        return json_resp.failed(message='红包不存在或已过期')
    user = User.objects.filter(open_id=redpacket.open_id).first()
    if not user:
        return json_resp.failed(message='未找到红包来源')

    qr_name = redpacket_id + '.png'
    qrpath = os.path.join(config.server_static_file, 'wx_qr', qr_name)
    if not os.path.exists(qrpath):
        return json_resp.failed(message='验证码不存在')
    newimg, _ = imgpro.blend_img(qrpath, user.avatar)  # 合并图片

    try:
        filename = imgpro.save_img_to_disk(newimg,
                                           'wx_qr',
                                           filename=str(redpacket_id) + '_pic')
        logger.info('save img to localdisk success: %s' % filename)
    except Exception as e:
        logger.error('save img to localdisk failed: %s_pic\n%s' %
                     (redpacket_id, e))

    cimg = imgpro.img2stringio(newimg)
    return ImgResponse(cimg)
示例#3
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)
示例#4
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})
示例#5
0
文件: filequery.py 项目: ws999/wx-app
def get_text(filename):
    file_path = os.path.join('.', config.server_static_file, filename)
    if not os.path.exists(file_path):
        logger.error('文件不存在:%s' % file_path)
        return json_resp.failed(message='文件不存在')
    with codecs.open(file_path) as f:
        txt = f.readline()
    return TextResponse(txt)
示例#6
0
文件: filequery.py 项目: ws999/wx-app
def get_img(type, name):
    path = os.path.join('.', config.server_static_file, type, name)
    if not os.path.exists(path):
        logger.error('can\'t find file: %s' % path)
        return json_resp.failed(message='文件不存在')
    img = Image.open(path)
    cimg = imgpro.img2stringio(img)
    return ImgResponse(cimg)
示例#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
    })
示例#8
0
文件: info.py 项目: 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()
示例#9
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})
示例#10
0
文件: wxqrimg.py 项目: ws999/wx-app
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})
示例#11
0
文件: transfer.py 项目: ws999/wx-app
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'
    })
示例#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
        })
示例#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)