Пример #1
0
def refresh_reward_stock(redis, session):
    """
    刷新所有商品的库存接口
    :params  sid  返回最新库存的ID和库存
    """
    onshop_fields = ('reward_per_stock', )
    fields = ('sid', )
    for field in fields:
        exec('%s = request.forms.get("%s","").strip()' % (field, field))

    try:
        log_util.debug('[try refresh_reward_stock] sid[%s]' % (sid))
    except:
        return {'code': -300, 'msg': '接口参数请求错误!'}

    SessionTable, account, uid, verfiySid = getInfoBySid(redis, sid)
    check_code, check_msg, user_table = check_session_verfiy(
        redis, '/fish/getRewardInfo/', SessionTable, account, sid, verfiySid)
    log_util.debug('[try do_refresh] check_code[%s] check_msg[%s]' %
                   (check_code, check_msg))
    if int(check_code) < 0:
        if check_code == -4:
            return {'code': check_code, 'msg': check_msg, 'osid': sid}
        return {'code': check_code, 'msg': check_msg}

    reward_info = get_reward_shop_data(redis, onshop_fields)
    log_util.debug('[try refresh_reward_stock]  sid[%s] goodsInfo[%s] ' %
                   (sid, reward_info))
    return {'code': 0, 'rewardInfo': reward_info}
Пример #2
0
def do_gain_exchange_ticket(redis, session):
    """
    获取捕鱼奖品兑换卷接口
    """
    fields = ('sid', 'tickets')
    for field in fields:
        exec(consts.FORMAT_PARAMS_POST_STR % (field, field))

    try:
        log_util.debug('[try do_gain_exchange_ticket] sid[%s] tickets[%s]' %
                       (sid, tickets))
    except:
        return {'code': -300, 'msg': '接口请求参数错误'}

    SessionTable, account, uid, verfiySid = getInfoBySid(redis, sid)
    check_code, check_msg, user_table = check_session_verfiy(
        redis, '/fish/getRewardInfo/', SessionTable, account, sid, verfiySid)
    log_util.debug('[try do_refresh] check_code[%s] check_msg[%s]' %
                   (check_code, check_msg))
    if int(check_code) < 0:
        if check_code == -4:
            return {'code': check_code, 'msg': check_msg, 'osid': sid}
        return {'code': check_code, 'msg': check_msg}

    if int(tickets) < 0:
        return {'code': -5001, 'msg': '奖券数据错误'}
    #测试
    exchange_ticket = redis.hincrby(user_table, 'exchange_ticket',
                                    int(tickets))
    return {'code': 0, 'userTickets': exchange_ticket}
Пример #3
0
def get_benefit_info(redis,session):
    fields = ('sid',)
    for field in fields:
        exec(consts.FORMAT_PARAMS_POST_STR%(field,field))

    SessionTable,account,uid,verfiySid = getInfoBySid(redis,sid)
    check_code,check_msg,user_table,osid = check_session_verfiy(redis,'/fish/getRewardInfo/',SessionTable,account,sid,verfiySid)
    log_util.debug('[try do_refresh] check_code[%s] check_msg[%s]'%(check_code,check_msg))
    if int(check_code)<0:
        if check_code == -4:
            return {'code':check_code,'msg':check_msg,'osid':osid}
        return {'code':check_code,'msg':check_msg}

    #判断是否能领取救济金
    code, _,benefit= can_take_benefit(redis,uid,user_table)
    if code < 0:
        canTakeBenefit = 0
    else:
        canTakeBenefit = 1

    benefitInfo = {
            'minCoin': benefit['min_coin'],
            'benefitCoin': benefit['benefit_coin'],
            'benefitCount': benefit['take_count'],
            'userCount':  benefit['user_take_count'],
            'canTakeBenefit': canTakeBenefit
    }

    token = encrypt_util.to_md5(str(time.time())+sid)
    redis.set(USER_BENEFIT_TOKEN%(uid),token)
    log_util.info('[getBenefitInfo] uid[%s] token[%s]'%(uid,token))
    return {'code':0,'benefitInfo':benefitInfo,'token':token}
Пример #4
0
def do_take_sign_reward(redis,session):
    """ 领取签到奖励接口 """
    fields = ('sid','signDay','isRetake')
    for field in fields:
        exec(consts.FORMAT_PARAMS_POST_STR%(field,field))

    SessionTable,account,uid,verfiySid = getInfoBySid(redis,sid)
    check_code,check_msg,user_table,osid = check_session_verfiy(redis,'/fish/doSign/',SessionTable,account,sid,verfiySid)
    log_util.debug('[try do_refresh] check_code[%s] check_msg[%s]'%(check_code,check_msg))
    if int(check_code)<0:
        if check_code == -4:
            return {'code':check_code,'msg':check_msg,'osid':osid}
        return {'code':check_code,'msg':check_msg}

    sign_id = redis.get(FISH_TABLE_NOW_RUN)
    if not sign_id:
        sign_id = 1

    #检查领取是否有效
    code,msg,sign_day_info= check_sign_valid(redis,uid,signDay,sign_id)
    if code<0:
        return {'code':code,'msg':msg}
    weekTime = time.strftime("%Y-%m-%d:%W")
    pipe = redis.pipeline()
    message = ''
    sign_type = convert_util.to_int(sign_day_info['give_type'])
    if sign_type == consts.GIVE_COIN:
        #领取的是金币的话
        message = "金币{}".format(sign_day_info['coin'])
        #pipe.hincrby(user_table,'coin',convert_util.to_int(sign_day_info['coin']))

        # 改成领取1000000弹头
        sign_warheads = get_should_sign_warheads(redis,uid)
        pipe.hincrby(user_table,'warhead',sign_warheads)
        # sign_day_info['taked'].append(uid)
        pipe.hset(FISH_SIGN_TABLE%(sign_id), signDay, sign_day_info)

        users = redis.hget(FISH_SIGN_TABLE_WEEK % (sign_id, weekTime), signDay)
        if users:
            users = eval(users)
        else:
            users = []
        users.append(uid)
        pipe.hset(FISH_SIGN_TABLE_WEEK % (sign_id, weekTime), signDay, users)
        log_util.info('[do_take_sign_reward] uid[%s] do sign success.signDay[%s] coin[%s]'%(uid,signDay,sign_day_info['coin']))

    month = time.strftime("%Y-%m")
    number = redis.hget(FISH_SIGN_TABLE_USER_NUMBER % month, account)
    if number:
        number = int(number)
        redis.hincrby(FISH_SIGN_TABLE_USER_NUMBER % month, account, 1)
        number += 1
    else:
        redis.hset(FISH_SIGN_TABLE_USER_NUMBER % month, account, 1)
        number = 1
    pipe.hset("users:%s"%uid,"last_sign_date",str(datetime.now())[:10])
    pipe.execute()
    #return {'code':0,'msg':'签到成功,获取{}'.format(message), "number": number}
    return {'code':0,'msg':'签到成功,获取{}'.format(sign_warheads), "number": number}
Пример #5
0
def do_address(redis, session):
    '''
    玩家操作收获地址接口
    @params:
        sid
        phone
        province
        city
        address
        name
    '''
    fields = ('sid', 'name', 'phone', 'city', 'address', 'action')
    for field in fields:
        exec(consts.FORMAT_PARAMS_POST_STR % (field, field))

    try:
        log_util.debug(
            '[try do_address] get parasm sid[%s] name[%s]  phone[%s] city[%s] addr[%s]'
            % (sid, name, phone, city, address))
    except:
        return {'code': -300, 'msg': '接口参数错误'}

    SessionTable, account, uid, verfiySid = getInfoBySid(redis, sid)
    check_code, check_msg, user_table = check_session_verfiy(
        redis, '/fish/getRewardInfo/', SessionTable, account, sid, verfiySid)
    log_util.debug('[try do_refresh] check_code[%s] check_msg[%s]' %
                   (check_code, check_msg))
    if int(check_code) < 0:
        if check_code == -4:
            return {'code': check_code, 'msg': check_msg, 'osid': sid}
        return {'code': check_code, 'msg': check_msg}

    if action not in ['add', 'modify', 'delete']:
        return {'code': -2001, 'msg': '不被允许的操作,请重试.'}

    address_info = {
        'name': name,
        'phone': phone,
        'city': city,
        'address': address
    }
    action_2_fun = {
        'add': do_user_modify_addr,
        'modify': do_user_modify_addr,
        'delete': do_user_del_addr
    }
    op_result = action_2_fun[action](redis, uid, address_info)
    log_util.debug('[try do_address] sid[%s] action[%s] op_result[%s]' %
                   (sid, action, op_result))
    return {'code': 0, 'msg': '操作成功'}
Пример #6
0
def do_take_benefit(redis,session):
    """ 救济金补领接口 """

    fields = ('sid','token')
    for field in fields:
        exec(consts.FORMAT_PARAMS_POST_STR%(field,field))

    SessionTable,account,uid,verfiySid = getInfoBySid(redis,sid)
    check_code,check_msg,user_table,osid = check_session_verfiy(redis,'/fish/getRewardInfo/',SessionTable,account,sid,verfiySid)

    # ----------暂时可无限领取弹头救济金-----------------
    '''
    warhead = redis.hget('users:%s'%uid,'warhead') 
    warhead = int(warhead or 0)
    if warhead < 1000:
        redis.hincrby('users:%s'%uid,20000)
        sendProtocol2AllGameService(redis, HEAD_SERVICE_PROTOCOL_MEMBER_REFRESH%(account),game="FISH")
        return {'code':0,'msg':'领取救济金成功'}
    '''
    # ----------暂时可无限领取弹头救济金-----------------

    log_util.debug('[try do_refresh] check_code[%s] check_msg[%s]'%(check_code,check_msg))
    if int(check_code)<0:
        if check_code == -4:
            return {'code':check_code,'msg':check_msg,'osid':osid}
        return {'code':check_code,'msg':check_msg}

    server_token = redis.get(USER_BENEFIT_TOKEN%(uid))
    if token != server_token:
        log_util.info('[do_take_benefit] client_token[%s] server_token[%s]'%(token,server_token))
        return {'code':-9003,'msg':'不能重复领取!'}

    code,msg,benefit_info = can_take_benefit(redis,uid,user_table)
    if code < 0:
        log_util.debug('[do_take_benefit] can\'t take benefit code[%s] msg[%s]'%(code,msg))
        return {'code':code,'msg':msg}


    _datetime = time.strftime("%Y-%m-%d", time.localtime())
    try:
        #领取救济金
        pipe = redis.pipeline()
        pipe.hincrby(FISH_BENEFIT_COIN_TABLE % _datetime ,uid,1)
        pipe.hincrby(user_table,'coin',benefit_info['benefit_coin'])

    except Exception,e:
        log_util.error('[do_take_benefit] take benefit error[%s]'%(e))
        return {'code':-9000,'msg':'领取救济金失败!'}
Пример #7
0
def doSignMonth(redis, session):
    "领取"
    fields = ('sid', 'day')
    for field in fields:
        exec (consts.FORMAT_PARAMS_POST_STR % (field, field))

    SessionTable, account, uid, verfiySid = getInfoBySid(redis, sid)
    check_code,check_msg,user_table,osid = check_session_verfiy(redis,'/fish/getRewardInfo/',SessionTable,account,sid,verfiySid)
    log_util.debug('[try do_refresh] check_code[%s] check_msg[%s]'%(check_code,check_msg))
    if int(check_code)<0:
        if check_code == -4:
            return {'code':check_code,'msg':check_msg,'osid':osid}
        return {'code':check_code,'msg':check_msg}
    account2user_table = FORMAT_ACCOUNT2USER_TABLE % (account)
    userTable = redis.get(account2user_table)
    receiveMoney = json.loads(json.dumps({
        5: 100000,
        10: 250000,
        15: 500000,
        20: 1000000
    }))

    month = time.strftime("%Y-%m")
    # 获取领取表格
    receive = redis.hget(FISH_SIGN_TABLE_USER_RECEIVE % month, account)
    number = redis.hget(FISH_SIGN_TABLE_USER_NUMBER % month, account)
    number = int(number) if number else 0
    if not receive:
        receive = json.loads(json.dumps({5: 0, 10:0, 15:0, 20:0}))
    else:
        receive = json.loads(receive)

    if int(day) <= number:
        print(u"传进来的天数:%s" % day)
        if day not in receive.keys():
            return {"code": 1, "msg": "不存在这一天"}
        money = receiveMoney[day]
        print(u"天数:%s 金钱:%s " % (day, money))
        if receive[day] == 0:
            redis.hincrby(userTable, 'coin', money)
            receive[day] = 1
            redis.hset(FISH_SIGN_TABLE_USER_RECEIVE % month, account, json.dumps(receive))
        else:
            return {"code": 1, "msg": "你已经领取过了"}
        #return {"code": 0, "msg": "成功", 'receive': receive, "money": money}
        return {"code": 0, "msg": "成功", 'receive': '1000000', "money": 1000000}
    else:
        return {"code": 1, "msg": "暂时还不能领取"}
Пример #8
0
def do_buyCoin(redis, session):
    """
    测试购买金币接口
    :params sid  用户sid
    :params cards 购买金币数
    """
    fields = ('sid', 'cards', 'price', 'goodId')
    for field in fields:
        exec('%s = request.forms.get("%s","").strip()' % (field, field))

    try:
        log_util.debug('[try do_buyCoin] sid[%s] cardNums[%s] price[%s]' %
                       (sid, cards, price))
        if not price:
            return {'code': -300, 'msg': '接口参数请求错误'}
    except:
        return {'code': -300, 'msg': '接口参数请求错误'}

    SessionTable, account, uid, verfiySid = getInfoBySid(redis, sid)
    check_code, check_msg, user_table = check_session_verfiy(
        redis, '/fish/buyCoin/', SessionTable, account, sid, verfiySid)

    if int(check_code) < 0:
        if check_code == -4:
            return {'code': check_code, 'msg': check_msg, 'osid': sid}
        return {'code': check_code, 'msg': check_msg}

    _wechatHandler = fish_pay_func.test_WeChatPay(redis, goodId, user_table)
    if not _wechatHandler:
        return {'code': -6001, 'msg': '购买金币失败'}

    #统计金币
    _handler = fish_pay_func.do_pay_record(redis, uid, user_table, cards,
                                           price)
    if not _handler:
        return {'code': -6000, 'msg': '购买金币失败.'}

    coin = redis.hget(user_table, 'coin')
    log_util.debug('[try buyCoin] return coin[%s]' % (coin))
    redis.hincrby(user_table, 'warhead', int(cards))
    print '=' * 66
    print '=' * 66
    print 'cards:'
    print cards
    print '=' * 66
    print '=' * 66
    return {'code': 0, 'msg': '购买金币成功', 'coin': coin}
Пример #9
0
def get_user_reward_record(redis, session):
    """
    玩家兑换记录接口
    """
    fields = ('sid', 'pageNum')
    exchange_fields = (  # 兑换记录需要的字段
        'exchange_reward_name', 'exchange_card_no', 'exchange_card_pwd',
        'exchange_date', 'exchange_reward_status')
    for field in fields:
        exec(consts.FORMAT_PARAMS_POST_STR % (field, field))

    try:
        log_util.debug(
            '[try get_user_reward_record] get params sid[%s] pageNum[%s]' %
            (sid, pageNum))
        if not pageNum:
            pageNum = 1
    except:
        return {'code': -300, 'msg': '接口参数错误'}
    SessionTable, account, uid, verfiySid = getInfoBySid(redis, sid)
    check_code, check_msg, user_table = check_session_verfiy(
        redis, '/fish/getRewardInfo/', SessionTable, account, sid, verfiySid)
    log_util.debug('[try do_refresh] check_code[%s] check_msg[%s]' %
                   (check_code, check_msg))
    if int(check_code) < 0:
        if check_code == -4:
            return {'code': check_code, 'msg': check_msg, 'osid': sid}
        return {'code': check_code, 'msg': check_msg}

    pageNum = convert_util.to_int(pageNum)

    user_exchange_list, user_total_record = get_user_exchange_list(
        redis, uid, exchange_fields, pageNum, consts.NUMS_PER_PAGE)
    log_util.debug(
        '[try get_user_reward_record]  sid[%s] user_exchange_list[%s]' %
        (sid, user_exchange_list))
    return {
        'code': 0,
        'userExchangeInfo': user_exchange_list,
        'totalRecords': user_total_record
    }
Пример #10
0
def do_checkOrder(redis, session):
    """
    检查微信支付是否成功接口
    """
    curTime = datetime.now()

    orderSwitch = convert_util.to_int(
        redis.hget(FISH_CONSTS_CONFIG, 'wechat_switch'))

    outTradeNo = request.forms.get('outTradeNo', '').strip()
    sid = request.forms.get('sid', '').strip()

    SessionTable, account, uid, verfiySid = getInfoBySid(redis, sid)
    check_code, check_msg, user_table = check_session_verfiy(
        redis, '/fish/checkOrder/', SessionTable, account, sid, verfiySid)
    log_util.debug('[try checkOrder] check_code[%s] check_msg[%s]' %
                   (check_code, check_msg))
    if int(check_code) < 0:
        if check_code == -4:
            return {'code': check_code, 'msg': check_msg, 'osid': sid}
        return {'code': check_code, 'msg': check_msg}

    if not outTradeNo:
        return {'code': -1, 'msg': 'outTradeNo不存在'}

    orderTable = ORDER_TABLE4FISH % (outTradeNo)
    if not redis.exists(SUCCEED_ORDER4FISH) or not redis.sismember(
            SUCCEED_ORDER4FISH, orderTable):
        return {'code': -9}

    if not orderTable:
        return {'code': -1, 'msg': 'orderTable不存在'}

    roomCards = redis.hget(orderTable, ('roomCards'))
    checkNum = redis.hincrby(orderTable, 'CheckNum', 1)

    groupId = redis.hget(user_table, 'parentAg')
    redis.hset(orderTable, 'groupId', groupId)
    # roomCard = redis.get(USER4AGENT_CARD%(groupId, id))
    roomCard = redis.hget(user_table, 'coin')
    return {'code': 0, 'roomCard': roomCard}
Пример #11
0
def get_fish_goods_info(redis, session):
    '''
    捕鱼获取商城商品接口
    :params sid 用户登录session
    :params ver 当前商城的ver
    :return  rewardInfo:[{},{}],addressInfo:{}
    '''
    fields = ('sid', 'rewardType', 'ver')
    onshop_fields = ('reward_name', 'reward_per_stock', 'reward_img_path',
                     'reward_need_ticket', 'reward_pos', 'reward_type')
    for field in fields:
        exec(consts.FORMAT_PARAMS_POST_STR % (field, field))

    SessionTable, account, uid, verfiySid = getInfoBySid(redis, sid)
    check_code, check_msg, user_table = check_session_verfiy(
        redis, '/fish/getRewardInfo/', SessionTable, account, sid, verfiySid)
    log_util.debug('[try do_refresh] check_code[%s] check_msg[%s]' %
                   (check_code, check_msg))
    if int(check_code) < 0:
        if check_code == -4:
            return {'code': check_code, 'msg': check_msg, 'osid': sid}
        return {'code': check_code, 'msg': check_msg}

    user_addr_table = FORMAT_USER_ADDRESS_TABLE % (uid)
    if not redis.exists(user_addr_table):
        address_info = {}
    else:
        address_info = redis.hgetall(user_addr_table)
    #获取奖品列表
    reward_type_info, reward_goods_info = get_reward_shop_api_data(
        redis, onshop_fields)
    log_util.debug(
        '[try get_fish_goods_info]  sid[%s] goodsInfo[%s] address_info[%s] ' %
        (sid, reward_goods_info, address_info))
    return {
        'code': 0,
        'typeInfo': reward_type_info,
        'rewardInfo': reward_goods_info,
        'addressInfo': address_info
    }
Пример #12
0
def get_sign_info(redis,session):
    """ 获取签到信息接口 """
    fields = ('sid',)
    for field in fields:
        exec(consts.FORMAT_PARAMS_POST_STR%(field,field))

    SessionTable,account,uid,verfiySid = getInfoBySid(redis,sid)
    check_code,check_msg,user_table,osid = check_session_verfiy(redis,'/fish/getSignInfo/',SessionTable,account,sid,verfiySid)
    log_util.debug('[try do_refresh] check_code[%s] check_msg[%s]'%(check_code,check_msg))
    if int(check_code)<0:
        if check_code == -4:
            return {'code':check_code,'msg':check_msg,'osid':osid}
        return {'code':check_code,'msg':check_msg}

    sign_id = redis.get(FISH_TABLE_NOW_RUN)
    if not sign_id:
        sign_id = 1
    code,msg,sign_info = get_user_sign_info(redis,uid,sign_id)
    if code<0:
        return {'code':code,'msg':msg}

    now_day_index = convert_util.to_week_day(datetime.now())
    #signInfo = get_user_sign_table(redis,uid,user_table)
    log_util.info('[get_sign_info] sign table info[%s] now_day[%s]'%(sign_info,now_day_index))
    month = time.strftime("%Y-%m")
    number = redis.hget(FISH_SIGN_TABLE_USER_NUMBER % month, account)
    number = int(number) if number else 0
    receiveMoney = json.loads(json.dumps({
        5:1000000,
        10:1000000,
        15:1000000,
        20:1000000
    }))
    receive = redis.hget(FISH_SIGN_TABLE_USER_RECEIVE % month, account)
    if not receive:
        receive = json.loads(json.dumps({5: 0, 10:0, 15:0, 20:0}))
    else:
        receive = json.loads(receive)

    return {'code':0,'signInfo':sign_info,'nowDay':now_day_index, "number": number, "receiveMoney": receiveMoney, "receive": receive}
Пример #13
0
def do_reward_exchange(redis, session):
    '''
    玩家兑换奖品协议
    @params:
            sid : 玩家sesion
            rewardId : 奖品ID
    '''
    curTime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    dateStr = datetime.now().strftime('%Y-%m-%d')
    fields = ('sid', 'rewardId', 'needTicket')
    for field in fields:
        exec(consts.FORMAT_PARAMS_POST_STR % (field, field))

    try:
        log_util.debug(
            '[try do_reward_exchange] get params ticket[%s] sid[%s] rewardId[%s]'
            % (needTicket, sid, rewardId))
    except:
        return {'code': -300, 'msg': '接口参数错误.'}

    SessionTable, account, uid, verfiySid = getInfoBySid(redis, sid)
    check_code, check_msg, user_table = check_session_verfiy(
        redis, '/fish/doExchange/', SessionTable, account, sid, verfiySid)
    log_util.debug('[try do_refresh] check_code[%s] check_msg[%s]' %
                   (check_code, check_msg))
    if int(check_code) < 0:
        if check_code == -4:
            return {'code': check_code, 'msg': check_msg, 'osid': sid}
        return {'code': check_code, 'msg': check_msg}

    if not redis.exists(FISH_REWARD_TABLE % (rewardId)):
        return {'code': -4001, 'msg': '兑换商品不存在或已过期'}

    reward_table = FISH_REWARD_TABLE % (rewardId)
    user_addr_table = FORMAT_USER_ADDRESS_TABLE % (uid)
    if not redis.exists(user_addr_table):
        return {'code': -4004, 'msg': '请先设置奖品收货地址信息'}

    user_exchange_ticket = convert_util.to_int(
        redis.hget(user_table, 'exchange_ticket'))
    needTicket = convert_util.to_int(needTicket)
    #获取奖品对应信息
    reward_need_ticket,reward_name,reward_per_stock,reward_img_path,reward_card_no,reward_card_pwd,reward_type,reward_coin,reward_status= \
                redis.hmget(reward_table,('reward_need_ticket','reward_name','reward_per_stock','reward_img_path','reward_card_no','reward_card_pwd','reward_type','reward_coin','reward_status'))

    reward_need_ticket = convert_util.to_int(reward_need_ticket)
    reward_coin = convert_util.to_int(reward_coin)
    reward_type = convert_util.to_int(reward_type)
    reward_status = convert_util.to_int(reward_status)
    reward_per_stock = convert_util.to_int(reward_per_stock)

    if reward_status == consts.REWARD_OFFLINE:
        return {'code': -4005, 'msg': '该奖品未上架'}

    if reward_per_stock <= 0:
        #根正数据错误
        redis.hset(reward_table, 'reward_per_stock', 0)
        return {
            'code': 0,
            'msg': '库存不足',
            'type': 3,
            'userTicket': user_exchange_ticket,
            'needTicket': reward_need_ticket,
            'rewardStock': 0
        }

    if needTicket != reward_need_ticket:
        reward_per_stock = convert_util.to_int(
            redis.hget(reward_table, 'reward_per_stock'))
        return {
            'code': 0,
            'msg': '使用兑换卷和所需兑换卷不一致',
            'type': 3,
            'userTicket': user_exchange_ticket,
            'needTicket': reward_need_ticket,
            'rewardStock': reward_per_stock
        }

    if user_exchange_ticket < needTicket:
        reward_per_stock = convert_util.to_int(
            redis.hget(reward_table, 'reward_per_stock'))
        log_util.debug(
            '[try do_reward_exchange] needTicke[%s] user_exchange_ticket[%s]' %
            (needTicket, user_exchange_ticket))
        return {
            'code': 0,
            'msg': '兑换卷不足',
            'type': 3,
            'userTicket': user_exchange_ticket,
            'needTicket': reward_need_ticket,
            'rewardStock': reward_per_stock
        }

    #写入相应的兑换记录表
    #减去玩家相应的兑换卷
    #减去兑换奖品库存
    user_addr_info = redis.hgetall(user_addr_table)
    exchange_info = {
        'user_id': uid,
        'exchange_date': curTime,
        'exchange_reward_id': rewardId,
        'exchange_reward_name': reward_name,
        'exchange_use_ticket': needTicket,
        'exchange_type': reward_type,
        'exchange_leave_ticket': user_exchange_ticket - needTicket,
        'exchange_reward_img_path': reward_img_path,
        'exchange_need_ticket': reward_need_ticket,
        'exchange_card_no': reward_card_no if reward_card_no else '',
        'exchange_card_pwd': reward_card_pwd if reward_card_pwd else '',
        'exchange_reward_status': '0',
        'exchange_user_name': user_addr_info['name'],
        'exchange_user_phone': user_addr_info['phone'],
        'exchange_user_addr':
        user_addr_info['city'] + user_addr_info['address']
    }
    pipe = redis.pipeline()
    try:
        ori_exchange_id = redis.get(FISH_EXCHANGE_ID_COUNT)
        exchange_id = redis.incr(FISH_EXCHANGE_ID_COUNT)
        exchange_info['exchange_id'] = exchange_id
        pipe.hincrby(user_table, 'exchange_ticket', -int(needTicket))
        pipe.hincrby(reward_table, 'reward_per_stock', -1)
        #设置兑换表
        pipe.set(FISH_EXCHANGE_TABLE % (exchange_id), exchange_info)
        #写入兑换记录列表
        pipe.lpush(FISH_EXCHANGE_LIST, exchange_id)
        #写入用户兑换记录表
        pipe.lpush(FISH_USER_EXCHANGE_LIST % (uid), exchange_id)
        #写入兑换记日期索引表
        pipe.lpush(FISH_USER_EXCHANGE_DATE % (dateStr), exchange_id)
        #写入状态索
        pipe.lpush(FISH_USER_EXCHANGE_STATUS_LIST % (0), exchange_id)
    except Exception, e:
        redis.set(FISH_EXCHANGE_ID_COUNT, ori_exchange_id)
        reward_per_stock = convert_util.to_int(
            redis.hget(reward_table, 'reward_per_stock'))
        log_util.debug('[try do_reward_exchange] exchange error reason[%s]' %
                       (e))
        return {
            'code': -4004,
            'msg': '数据错误',
            'needTicket': reward_need_ticket,
            'rewardStock': reward_per_stock
        }
Пример #14
0
def do_onWeChatPay4TX(redis, session):
    """
    发起微信支付接口
    """
    curTime = datetime.now()
    orderSwitch = convert_util.to_int(
        redis.hget(FISH_CONSTS_CONFIG, 'wechat_switch'))

    sid = request.forms.get('sid', '').strip()
    goodsId = request.forms.get('id', '').strip()
    ip = web_util.get_ip()

    SessionTable, account, uid, verfiySid = getInfoBySid(redis, sid)
    check_code, check_msg, user_table = check_session_verfiy(
        redis, '/fish/checkOrder/', SessionTable, account, sid, verfiySid)
    log_util.debug('[try checkOrder] check_code[%s] check_msg[%s]' %
                   (check_code, check_msg))
    if int(check_code) < 0:
        if check_code == -4:
            return {'code': check_code, 'msg': check_msg, 'osid': sid}
        return {'code': check_code, 'msg': check_msg}

    group_id = redis.hget(user_table, 'parentAg')

    # goodsId = redis.get(GOODS_NAME2NUM%(goodsName))
    goods_table = GOODS_TABLE % (goodsId)
    cards, goodsName, present_card, goodsPrice = redis.hmget(
        goods_table, ('cards', 'name', 'present_cards', 'price'))
    #判断金币价格
    # goodsPrice = getGoodsMoney(redis,group_id,cards)
    if not redis.exists(goods_table):
        log_util.error('[try goods][error] goods[%s] is not found.' %
                       (goodsName))
        return {'code': -1, 'msg': 'goods not found'}

    log_util.debug('[try goods] player cards[%s] goodsPrice[%s].' %
                   (cards, goodsPrice))

    goodsId2OrderId = GOODS_NUM4FISH % (goodsId)
    orderIndex = redis.incr(goodsId2OrderId)
    if orderIndex >= 10000000000:
        redis.set(goodsId2OrderId, 0)
        orderIndex = redis.incr(goodsId2OrderId)
    outTradeNo = getOutTradeNo(goodsId, orderIndex)

    # data = (player, goodsBody, totalPrice, outTradeNo, goodsCount, goodsId, goodsName, goodsCards)
    # order2weixin(data) *data
    urlRes = urlparse(request.url)
    serverIp = urlRes.netloc.split(':')[0]

    nonceStr = wechat_util.tx_wechat_order_nonce()
    signDict = {
        'appid': APPID_FISH,
        'mch_id': MCH_ID_FISH,
        'nonce_str': nonceStr,
        'body': goodsName,
        'out_trade_no': outTradeNo,
        'total_fee': int(float(goodsPrice) * 100),
        'spbill_create_ip': ip,
        'notify_url': NOTIFY_URL_FISH % (serverIp),
        'trade_type': TRADE_TYPE
    }

    #print payment params
    log_util.debug('[%s][onWechatPay][info] payParams[%s]' %
                   (curTime, signDict))

    # signList = packSignDict2List(signDict)
    # sign = getSign4TX(signList)
    sign = wechat_util.gen_sign4fish(signDict)

    orderStr = packSignDict2XML(signDict, sign)
    url = 'https://api.mch.weixin.qq.com/pay/unifiedorder'
    resultDict = wechat_util.get_xml_message(url, orderStr)
    log_util.debug('wxPay url[%s] data[%s] sign[%s] signDict[%s]' %
                   (url, orderStr, sign, signDict))
    log_util.debug('resultDict: %s' % resultDict)

    if not resultDict:
        log_util.error('[%s][onWechatPay][error] resultDict[%s]' %
                       (curTime, resultDict))
        return {'code': -1, 'msg': '微信支付失败'}

    if resultDict['return_code'] != 'SUCCESS':
        try:
            log_util.debug('[%s][onWechatPay][error] resultDict[%s]' %
                           (curTime, resultDict['return_msg']))
        except:
            pass
        return {'code': -1, 'msg': '微信支付未开启'}

    prepayID = resultDict['prepay_id']
    package = 'Sign=WXPay'
    timeStamp = int(time.time())
    # signList = [
    # 'appid=%s'%(APPID_FISH),
    # 'partnerid=%s'%(MCH_ID_FISH),
    # 'prepayid=%s'%(prepayID),
    # 'package=%s'%(package),
    # 'noncestr=%s'%(nonceStr),
    # 'timeStamp=%s'%(timeStamp),
    # ]
    signList = {
        'appid': APPID_FISH,
        'partnerid': MCH_ID_FISH,
        'prepayid': prepayID,
        'package': package,
        'noncestr': nonceStr,
        'timeStamp': timeStamp
    }
    sign = wechat_util.gen_sign4fish(signList)
    sign = '1'

    pipe = redis.pipeline()
    # pipe.set(PENDING4ACCOUNT%(player.account, totalPrice, goodsBody), outTradeNo)
    orderTable = ORDER_TABLE4FISH % (outTradeNo)
    pipe.hmset(
        orderTable, {
            'time': timeStamp,
            'sign': sign,
            'nonceStr': nonceStr,
            'prepayID': prepayID,
            'name': goodsName,
            'body': "123",
            'money': int(float(goodsPrice) * 100),
            'startTime': timeStamp,
            'account': account,
            'num': goodsId,
            'type': 'pending',
            'roomCards': cards,
            'presentCards': present_card
        })
    pipe.sadd(PENDING_ORDER4FISH, outTradeNo)
    pipe.lpush(ORDER_NUM_LIST4FISH, outTradeNo)
    pipe.sadd(PLAYER_ORDER4FISH % (account), outTradeNo)

    pipe.lpush(DAY_ORDER4FISH % (curTime.strftime("%Y-%m-%d")), outTradeNo)
    pipe.lpush(DAY_PENDING_ORDER4FISH % (curTime.strftime("%Y-%m-%d")),
               outTradeNo)
    pipe.expire(orderTable, 1 * 60 * 60)
    pipe.execute()

    #发送成功信息
    app_prepay_info = {
        'partnerid': MCH_ID_FISH,
        'prepayid': prepayID,
        'noncestr': nonceStr,
        'paySign': sign,
        'timestamp': str(timeStamp),
        'appid': APPID_FISH,
        'package': 'Sign=WXPay',
    }
    data = {
        'partnerId': str(MCH_ID_FISH),
        'prepayID': str(prepayID),
        'nonceStr': nonceStr,
        'sign': sign,
        'outTradeNo': outTradeNo,
        'curTime': curTime.strftime("%Y-%m-%d %H:%M:%S"),
        'timeStamp': str(timeStamp),
        'sub_appid': APPID_FISH,
        'app_prepay_info': app_prepay_info
    }

    log_util.debug("[try order succeed] data %s" % data)
    log_util.debug("[try order succeed] account[%s] outTradeNo[%s]." %
                   (account, outTradeNo))
    return {'code': 0, 'data': data}