Пример #1
0
    def POST(self):
        actv = None
        with get_connection('qf_marketing') as db:
            actv = db.select_one(
                    table= 'activity',
                    where= {
                        'id': self.validator.data['coupon_id'],
                    },
                    fields= 'id, create_mchnt_id, status, create_time')
        if not actv:
            raise ParamError('活动不存在')

        if actv['create_mchnt_id'] != str(self.user.userid):
            if actv['create_mchnt_id'] == str(self.get_big_uid()):
                raise ParamError('此活动为总账户创建,你无法执行修改~')
            raise ParamError('暂无修改此活动的权限')

        # 已经进行的活动不能删除
        now = datetime.datetime.now()
        notify_datetime = get_notify_datetime(actv['create_time'])
        if not now < notify_datetime:
                raise ParamError('不能删除已经进行的红包推广活动!')

        if actv['status'] != 3:
            try:
                act = Activity(id=actv['id'], status=3,
                               src='qpos')
                thrift_callex(config.QF_MARKETING_SERVERS, QFMarketing,
                              'activity_change', act)
            except:
                log.warn(traceback.format_exc())
                raise ThirdError('关闭活动失败')

        return self.write(success({}))
Пример #2
0
    def POST(self):
        actv = None
        with get_connection('qf_marketing') as db:
            actv = db.select_one(table='activity',
                                 where={
                                     'id': self.validator.data['id'],
                                     'src': ACTIVITY_SRC
                                 },
                                 fields='id, create_mchnt_id, status')
        if not actv:
            raise ParamError('活动不存在')

        if actv['create_mchnt_id'] != str(self.user.userid):
            if actv['create_mchnt_id'] == str(self.get_big_uid()):
                raise ParamError('此活动为总账户创建,你无法执行修改~')
            raise ParamError('暂无修改此活动的权限')

        if actv['status'] != COUPON_RULE_STATUS_CLOSE:
            try:
                act = Activity(id=actv['id'],
                               status=COUPON_RULE_STATUS_CLOSE,
                               src=ACTIVITY_SRC)
                thrift_callex(config.QF_MARKETING_SERVERS, QFMarketing,
                              'activity_change', act)
            except:
                log.warn(traceback.format_exc())
                raise ThirdError('关闭活动失败')

        return self.write(success({}))
Пример #3
0
    def POST(self):
        params = self.req.inputjson()

        # 获取customer_id
        customer_id = None
        try:
            customer_id = self.get_cid()
        except:
            if self.check_ip():
                cid = hids.decode(params.get('cid'))
                customer_id = cid[0] if cid else None
        if not customer_id:
            raise SessionError('用户未登录')

        # 消费者进行认证
        # 将更新商户member_tag
        if params.get('mode') == 'submit':
            userids = hids.decode(params.get('userid'))
            if userids:
                self.add_tag(userids[0], customer_id, 'submit',
                             MemDefine.MEMBER_SRC_SUBMIT)

        fields = ['nickname', 'cname', 'mobile', 'birthday']
        update_data = {i: params[i] for i in fields if params.get(i)}
        if 'birthday' in update_data:
            profile = get_profile(customer_id)
            if profile['birthday']:
                raise ParamError('已经设置了生日信息')

        # 更新消费者信息
        if update_data:
            thrift_callex(config.OPENUSER_SERVER, QFCustomer, 'profile_update',
                          customer_id, tcProfile(**update_data))

        return success({})
Пример #4
0
def push_msg2(content, str_extra, to, apptypes=None, platforms=None, mode=3):
    """
    推送消息
    :param content: 消息内容
    :param str_extra: 消息自定义参数,由set_custom生成
    :param to: 用户ID(字符串类型)的列表
    :param apptypes: app类型
                301(好近公司账号dev版),
                302(好近公司账号appstore版),Android和wp为302
                311(好近企业账号dev版),
                312(好近企业账号分发版)。
    :param platforms: 平台,
                0:IOS
                1:Android
                2:Windows Phone
    :param mode: 推送模式,
                0: SEND_MODE_ALL, 所有用户
                1: SEND_MODE_GROUP, 按groupid推送
                2: SEND_MODE_MOBILE, 按手机号推送
                3: SEND_MODE_USERID, 按用户id推送
    :return:
    """
    if not apptypes:
        apptypes = [301, 302, 312, 311]
    if not platforms:
        platforms = [0, 1, 2]
    thrift_callex(MSGPUSH2_SERVER, MsgPush, 'pushmsg2', apptypes, platforms,
                  mode, content, str_extra, to)
Пример #5
0
    def POST(self):

        cate = self.get_cate()

        params = self.req.input()
        sub_mchnt_id = params.get('shopid', '')
        try:
            userid = self.user.userid
            sub_mchnt_id = int(sub_mchnt_id)
            if not sub_mchnt_id:
                raise ParamError("子商户错误")
            else:
                if cate == "bigmerchant":
                    subids = get_linkids(userid)
                    if sub_mchnt_id not in subids:
                        raise ParamError("非大商户的子商户")
        except:
            log.warn('sub merchant error : %s ' % traceback.format_exc())
            raise ParamError("无法识别子商户")

        try:
            thrift_callex(config.APOLLO_SERVERS, ApolloServer, 'unbindRelation', int(userid), int(sub_mchnt_id), 'merchant')
        except:
            log.warn('user ({userid}) remove sub merchant({sub_mchnt_id}) error : {reason}'.format(userid=userid, sub_mchnt_id = sub_mchnt_id, reason = traceback.format_exc()))
            return self.write(error(QFRET.THIRDERR))
        return self.write(success(data={}))
Пример #6
0
    def signup(self,
               userprofile,
               recommenduid=None,
               recommendtype=1,
               allow_exist=True):
        '''
        用户注册接口
        params:
            userprofile: UserProfile, 用户信息
        return:
            userid : str, 用户id; None, 注册失败
            respmsg : str, 如果注册失败, 返回的提示信息将放在里面放回
        '''
        userid = None
        try:
            try:
                if recommenduid:
                    userid = thrift_callex(self.server, ApolloServer,
                                           'registerUserWithRecommend',
                                           userprofile, recommenduid,
                                           recommendtype)
                else:
                    userid = thrift_callex(self.server, ApolloServer,
                                           'registerUser', userprofile)
            except ApolloException, e:
                log.debug('signup error: %s' % e)
                if e.respcd == ApolloRet.APOLLO_ERR_USER_EXIST:
                    if not allow_exist:
                        return None, '商户已经注册'

                    mobile, user_cates = userprofile.user.mobile, [
                        _.__dict__ for _ in (userprofile.user.userCates or [])
                    ]
                    user = self.user_by_mobile(mobile)
                    userid = user['uid']

                    add_user_cates = set([
                        i['code'] for i in user_cates
                    ]) - set([i['code'] for i in user['userCates']])
                    if add_user_cates:
                        log.warn('%s need add user_cates: %s' %
                                 (userid, add_user_cates))
                        user_cate_names = {
                            i['code']: i['name']
                            for i in user_cates
                        }
                        add_user_cates = [
                            UserCate(code=i, name=user_cate_names[i])
                            for i in add_user_cates
                        ]
                        self.set_user_category(userid, add_user_cates)

                    return userid, mapping.get(e.respcd, '未知错误')

            else:
Пример #7
0
 def _check_user(self, username, password):
     try:
         thrift_callex(config.APOLLO_SERVERS, ApolloServer, 'checkUser',
                       username, password)
     except ApolloException, e:
         if e.respcd == ApolloRet.APOLLO_ERR_USER_NOT_EXIST:
             raise ParamError('该账号未注册')
         elif e.respcd == ApolloRet.APOLLO_ERR_PASSWD:
             raise ParamError('账号、密码不匹配')
         else:
             raise ParamError('验证失败,请稍候再试')
Пример #8
0
def get_customer_info(cid):
    # 获取openid
    openid = thrift_callex(config.OPENUSER_SERVER, OpenUser,
            'get_openids_by_user_ids', config.OPENUSER_APPID, [cid, ])[0]

    # 获取profile
    spec = json.dumps({'id': cid})
    profile = thrift_callex(config.OPENUSER_SERVER, OpenUser,
            'get_profiles', config.OPENUSER_APPID, spec)[0]

    return {'openid': openid, 'nickname': profile.nickname}
Пример #9
0
    def edit_cate(self):
        self.valid_list = [
            ('cate_code', '标签代码'),
        ]
        self.manual_list = [
            ('cate_name', '标签名称'), ('status', '状态'),
            ('remark', '标签解释'),
        ]
        values = self.build_args()
        where = {'cate_code': values['cate_code']}
        status_before = None
        remark_before = ''
        cate_name = ''

        cate_info_before_ret = {}
        with get_connection('qf_user') as db:
            cate_info_before_ret = db.select_one('user_category',
                where = {
                    'cate_code': values['cate_code'],
                    'userid': TagDef.VIRTUAL_USER_ID,
                },
                fields = 'status, cate_name, remark'
            )
        if not cate_info_before_ret:
            raise ParamError('当前修改标签不存在')
        status_before = cate_info_before_ret.get('status')
        remark_before = cate_info_before_ret.get('remark')
        cate_name_before = cate_info_before_ret.get('cate_name')

        # 原来的状态和更改的状态相同则不改状态
        if (values.get('remark') != remark_before or
                values.get('cate_name') != cate_name_before):
            tmp = {}
            tmp['code'] = values.get('cate_code')
            if values.get('cate_name'):
                tmp['name'] = values.get('cate_name')
            if values.get('remark'):
                tmp['remark'] = values.get('remark')
            update_cate = UserCate(**tmp)
            ret = thrift_callex(config.APOLLO_SERVERS, ApolloServer, 'setCategoryByCode', values.get('cate_code'), update_cate)
            if ret != 0:
                raise ParamError('error')
        if values.get('status') != status_before:
            update_cate = UserCate(
                code = values.get('cate_code'),
                name = values.get('cate_name'),
                status = values.get('status'),
                remark = values.get('remark')
            )
            ret = thrift_callex(config.APOLLO_SERVERS, ApolloServer, 'setUsersCategory', [TagDef.VIRTUAL_USER_ID], [update_cate])
            if ret != 0:
                raise ParamError('error')
        return self.write(success({}))
Пример #10
0
    def create_coupon(cls, user_id, lower_price, coupon_price, expire_days):
        today = datetime.date.today()
        title = "店铺会员红包"

        total_amt = 0
        with get_connection_exception('qf_mchnt') as conn:
            where = dict(userid=user_id)
            result = conn.select_one('member', where=where, fields="count(1) as count")
            total_amt = max(result['count'] * coupon_price, coupon_price)

        userid = str(user_id)
        use_rule = [['amt', '>=', lower_price]]
        rule_args = CouponRule()
        rule_args.src = 'qpos'
        rule_args.mchnt_id = userid
        rule_args.title = title
        rule_args.amt_max = coupon_price
        rule_args.amt_min = coupon_price
        rule_args.use_rule = json.dumps(use_rule)
        rule_args.status = 2
        rule_args.start_time  = int(time.mktime((today + datetime.timedelta(days = 1)).timetuple()))
        rule_args.expire_time = int(time.mktime((today + datetime.timedelta(days = expire_days+1)).timetuple()))
        rule_id = None
        try:
            rule_id = thrift_callex(config.QF_MARKETING_SERVERS, QFMarketing, 'coupon_rule_create', rule_args)
            log.warn('create coupon rule id: %s', rule_id)
        except ServerError as e:
            log.error('coupon_rule_create failure: %s, %s', e.code, e.msg)
            raise

        create_args = Activity()
        create_args.src = 'qpos'
        create_args.mchnt_id = userid
        create_args.type = 3
        create_args.title = title
        create_args.total_amt = total_amt
        create_args.xx_type = 1
        create_args.status = 2
        create_args.obtain_award_num = 1
        create_args.obtain_xx_id = rule_id
        create_args.rule = json.dumps([])
        create_args.start_time = date_to_tstamp(today+datetime.timedelta(days=1))
        create_args.expire_time = int(time.mktime((today + datetime.timedelta(days = expire_days+1)).timetuple()))

        try:
            activity_id = thrift_callex(config.QF_MARKETING_SERVERS, QFMarketing, 'activity_create', create_args)
            log.warn('create activity id: %s', activity_id)
        except ServerError as e:
            log.error('activity_create failure: %s, %s', e.code, e.msg)
            raise

        return
Пример #11
0
 def tag_user(self):
     self.valid_list = [
         ('cate_codes', '标签'), ('userids' ,'商户ID'), ('status', '状态')
     ]
     values = self.build_args()
     with get_connection_exception('qf_user') as db:
         cate_map_list = db.select(
             fields = ['cate_code', 'cate_name', 'remark'],
             table = 'user_category',
             where = {'userid': TagDef.VIRTUAL_USER_ID}
         )
         cate_map = {i['cate_code']: (i['cate_name'], i['remark'])
                 for i in cate_map_list}
     categories = []
     for userid in values['userids']:
         for cate_code in values['cate_codes']:
             tmp = UserCate(
                 code = cate_code,
                 name = unicode_to_utf8(cate_map.get(cate_code, ('', ''))[0]),
                 status = values['status'],
                 ctime = datetime.datetime.now().strftime(DATETIME_FMT),
                 remark = unicode_to_utf8(cate_map.get(cate_code, ('', ''))[1]),
             )
             categories.append(tmp)
     ret = thrift_callex(config.APOLLO_SERVERS, ApolloServer, 'setUsersCategory',
             list(values['userids']), categories)
     if ret != 0:
         raise ParamError('内部错误')
     return self.write(success({}))
Пример #12
0
def check_smscode(code, mobile, mode=0):
    '''验证验证码

    通过captcha服务验证验证码

    Params:
        code: 验证码
        mobile: 手机号
        mode: 0 验证后不删除, 1:验证后删除code, 2:验证后删除ucode下的所有code

    '''
    try:
        ret = thrift_callex(config.CAPTCHA_SERVERS,
                            CaptchaServer,
                            'captcha_check_ex',
                            code=code,
                            mode=mode,
                            ucode=mobile,
                            src=config.CAPTCHA_SRC)
        if not ret:
            return True

    except:
        log.warn(traceback.format_exc())

    return False
Пример #13
0
    def GET(self):
        ret = {}
        userid = int(self.user.userid)
        avg_stat = stat = None
        try:
            stat = json.loads(thrift_callex(config.DATAS_SERVERS, activiquer,
                              'activiq', 'zhenduan', str(userid)))[0]
        except:
            log.debug(traceback.format_exc())
            avg_stat = self.get_avg_stat()
            stat = {}

        # 同行业
        ret['avg'] = {}
        for field in ('cat_avg_amt', 'cat_rcg_rate', 'cat_retention_rate'):
            if field in stat:
                ret['avg'][field] = stat[field]
            elif field in avg_stat:
                ret['avg'][field] = avg_stat[field]

        # 店铺信息
        ret['stat'] = {}
        if stat:
            ret['stat'] = {k:v for k, v in stat.iteritems()}

        # 店铺名
        if 'nickname' in ret['stat']:
            ret['shopname'] = ret['stat']['nickname']
        else:
            user = apcli.user_by_id(userid) or {}
            log.debug(user)
            ret['shopname'] = user.get('shopname') or ''

        return self.write(success(ret))
Пример #14
0
    def _create_coupon(self, data):
        c = {}
        c['status'] = 2
        c['src'] = ACTIVITY_SRC
        c['mchnt_id'] = data['userid']
        c['title'] = data['title']
        c['amt_max'], c['amt_min'] = data['amt_max'], data['amt_min']
        c['start_time'], c['expire_time'] = data['start_time'], data[
            'expire_time']
        c['use_rule'] = json.dumps([['amt', '>=', data['use_limit_amt']]])
        c['profile'] = CouponRuleProfile(
            **{
                'mchnt_limit': 2,
                'effect_type': 2,
                'effect_offset': data['coupon_offset'],
                'effect_len': data['coupon_lifetime']
            })

        try:
            coupon = CouponRule(**c)
            cid = thrift_callex(config.QF_MARKETING_SERVERS, QFMarketing,
                                'coupon_rule_create', coupon)
        except:
            log.warn('create coupon error: %s' % traceback.format_exc())
            raise ThirdError('调用创建红包接口失败')

        return cid
Пример #15
0
 def msg_send(self, msg_type, msg):
     req_args = KFMsg()
     req_args.appid = self.appid
     req_args.openid = self.openid
     req_args.msg_type = msg_type
     req_args.msg_content = json.dumps(msg)
     return thrift_callex(self.server, QFMP, 'msg_send', req_args)
Пример #16
0
    def get_members(self):
        members = self.get_members_ext(self.validator.data['filter_key'])
        if not members:
            return []

        cids = [i['customer_id'] for i in members]
        profiles, tags = {}, {}
        if cids:
            spec = json.dumps({'user_id': cids})
            try:
                profiles = thrift_callex(config.OPENUSER_SERVER, QFCustomer, 'get_profiles',
                                         config.OPENUSER_APPID, spec)
                profiles = {i.user_id:i.__dict__ for i in profiles}
            except:
                log.warn('get openuser_info error:%s' % traceback.format_exc())
                raise ThirdError('获取消费者信息失败')

            tags = self.get_tags(cids)
            tags_dict = {flag.keys()[0]:flag.values()[0]
                    for flag in config.MEMBER_FLAGS}

        for m in members:
            customer_id = m['customer_id']
            info = profiles.get(customer_id,{})
            m['avatar'] = info.get('avatar') or config.HJ_AVATAR
            m['gender'] = info.get('gender', 1)
            m['nickname'] = info.get('nickname') or customer_id
            m['last_txdtm'] = tstamp_to_str(m['last_txdtm'])
            m['tag'] = tags[customer_id]
            mem_tags = tags[customer_id]
            m['tag'] = [tag for tag in mem_tags
                         if tag in tags_dict]
            m['is_auth'] = 1 if 'submit' in tags[customer_id] else 0
            m['customer_id'] = hids.encode(customer_id)
        return members
Пример #17
0
    def get_customers(self, actv):
        ret = {'customers': [], 'customer_num': 0}

        members = []
        with get_connection('qf_mchnt') as db:
            where = {'activity_id': int(actv['id'])}
            members = db.select('member_pt',
                                fields='customer_id',
                                where=where,
                                other='order by utime limit 5 offset 0') or []

            ret['customer_num'] = db.select_one('member_pt',
                                                fields='count(*) as num',
                                                where=where)['num']

        cids = [i['customer_id'] for i in members]
        if cids:
            spec = json.dumps({'user_id': cids})
            p = thrift_callex(config.OPENUSER_SERVER, OpenUser, 'get_profiles',
                              config.OPENUSER_APPID, spec)
            p = {i.user_id: i for i in p}
            for i in cids:
                t = (p[i].avatar if i in p else '') or config.HJ_AVATAR
                ret['customers'].append({'avatar': t})

        return ret
Пример #18
0
    def get_customer(actid, **cf):
        '''获取消费者信息'''
        customer_num, info = 0, []
        try:
            # 查询消费者
            where  = {'activity_id':actid, 'status':COUPON_STATUS_USE}
            limit, offset =  cf.get('limit', 5) , cf.get('offset', 0)
            with get_connection_exception('qf_marketing') as db:
                cps = db.select('coupon_bind', fields = 'distinct customer_id', where= where,
                    other = 'order by create_time desc limit %s, %s' % (offset, limit))
            cids, info = [i['customer_id'] for i in cps], []

            # 查询总共有多少消费者
            customer_num = db.select_one('coupon_bind', where = where, fields = 'count(distinct customer_id) as num')['num']

            # 查询消费者信息
            if cids:
                spec = json.dumps({"user_id":cids})
                r = thrift_callex(config.OPENUSER_SERVER, OpenUser, 'get_profiles', config.OPENUSER_APPID, spec)
                r = {str(i.user_id):i for i in r}
                # 处理返回值
                for i in cids:
                    if i in r:
                        info.append({'id':i, 'avatar':r[i].avatar or config.HJ_AVATAR, 'nickname':r[i].nickname})
                    else:
                        info.append({'id':i, 'avatar':config.HJ_AVATAR, 'nickname':i})
        except:
            log.warn('get openuser_info error:%s' % traceback.format_exc())
            if cf.get('raise_ex', ''):
                raise ThirdError('获取消费者信息失败')

        return customer_num, info
Пример #19
0
    def trade_push(self, actv, member, code_info):
        '''推送'''
        customer_id = member['customer_id']
        appid, hj_appid = self.get_appid()
        try:
            p = {}
            p['appid'] = appid
            # 获取openid
            p['openid'] = thrift_callex(config.OPENUSER_SERVER, OpenUser,
                                        'get_openids_by_user_ids', hj_appid, [
                                            customer_id,
                                        ])[0]

            # 店铺名
            user = apcli_ex('findUserBriefById', int(self.user.userid))
            p['shopname'] = user.shopname if user else ''
            p['exchange_num'] = member['exchange_num'] + 1
            p['exchange_pt'] = actv['exchange_pt']
            p['obtain_amt'] = actv['obtain_amt']
            p['busicd'] = 'card_actv_exchange'
            p['goods_amt'] = actv['goods_amt']
            p['goods_name'] = actv['goods_name']
            p['code'] = code_info['code']
            p['customer_id'] = hids.encode(customer_id)
            p['activity_id'] = actv['id']
            p['card_id'] = member['id']
            p = {
                unicode_to_utf8(k): unicode_to_utf8(v)
                for k, v in p.iteritems()
            }

            HttpClient(config.TRADE_PUSH_SERVER).post('/push/v2/push',
                                                      params=p)
        except:
            log.warn('error:%s' % traceback.format_exc())
Пример #20
0
def main():
    actvs = get_actvs()
    if not actvs:
        return

    for actv in actvs:
        members = get_members(actv)
        if not members:
            continue

        dispatch_args = CouponDispatchArgs()
        dispatch_args.src = 'qpos'
        dispatch_args.customer_list = members
        dispatch_args.activity_id = actv['id']
        dispatch_args.mchnt_id = actv['mchnt_id']

        try:
            ret = thrift_callex(config.COUPON_QF_MARKETING_SERVERS,
                    QFMarketing, 'coupon_dispatch', dispatch_args)
            log.info('coupon_dispatch success: args: %s', dispatch_args)
        except Exception as e:
            log.exception('coupon_dispatch failure: %s, args: %s', e, dispatch_args)
            continue

        if ret:
            log.warn('dispatch failure: %s', ret)
        else:
            log.info('coupon_dispatch success: activity: %d', actv['id'])
Пример #21
0
    def GET(self):
        d = {k: v.strip() for k, v in self.req.input().iteritems()}
        mobile = d.get('mobile')
        mode = d.get('mode', 'signup')

        # 验证信息
        self.check(mobile, mode)

        # 获取验证码
        try:
            smsexpires = config.SMS_CODE_RULE.get('expires', 6 * 50)
            smslength = config.SMS_CODE_RULE.get('length', 6)
            smsmode = config.SMS_CODE_RULE.get('mode', 1)
            limit_time = config.SMS_CODE_RULE.get('limit_time', 60)
            code = thrift_callex(config.CAPTCHA_SERVERS,
                                 CaptchaServer,
                                 'captcha_get_ex',
                                 ucode=mobile,
                                 src=config.CAPTCHA_SRC,
                                 expires=smsexpires,
                                 length=smslength,
                                 mode=smsmode,
                                 limit_time=limit_time)
            log.debug('获取验证码:%s' % code)
        except CaptchaException, e:
            raise ParamError(str(e.respmsg))
Пример #22
0
    def GET(self):
        cids = self.req.input().get('customer_id') or ''
        cids = [cid for cid in cids.split(',') if cid.strip()]

        customer_ids = []
        for cid in cids:
            if cid.strip():
                try:
                    customer_ids.append(hids.decode(cid)[0])
                except:
                    pass
        if not customer_ids:
            return self.write(success({'info': []}))

        infos = []
        try:
            spec = json.dumps({'user_id': customer_ids})
            profiles = thrift_callex(config.OPENUSER_SERVER, OpenUser,
                                     'get_profiles', config.OPENUSER_APPID,
                                     spec)
            profiles = {i.user_id: i.__dict__ for i in profiles}
        except:
            log.warn('get openuser_info error:%s' % traceback.format_exc())
        for customer_id in customer_ids:
            if customer_id in profiles:
                profile = profiles[customer_id]
                info = {
                    i: profile[i] or ''
                    for i in ('avatar', 'gender', 'nickname')
                }
                info['gender'] = info['gender'] or 3
                info['customer_id'] = hids.encode(customer_id)
                infos.append(info)

        return self.write(success({'info': infos}))
Пример #23
0
def is_trade_settle(fund_server, userid, busicd, chnl_termid, chnl_mchntid):
    '''
        交易是否需要结算
        这个接口如果调用很频繁,建议自己缓存验证,因为大部分情况下它需要调用三次,才能拿到结果
    '''
    # 构造请求数据
    req_data = FundConfigArgs()    
    req_data.state = 1 
    req_data.iscompare = 2 
    req_data.page = 1 
    req_data.maxnum = 2
    req_data.busicds = [busicd, ]
    # 根据userid验证交易是否需要结算
    req_data.val_type = 3
    req_data.vals = [str(userid), ]
    log.debug('find fund req_data:%s', req_data)
    resp_data = thrift_callex(fund_server, FundService, 'findfund', req_data)
    log.info('find fund resp_data:%s', resp_data)
    if not resp_data:
        raise Exception, 'call findfund failed'
    if resp_data.records and len(resp_data.records) > 0:
        log.info('trade not need deal because of userid')
        return False
    # 根据通道商户号(chnl_termid)验证交易是否需要结算
    req_data.val_type = 2
    req_data.vals = [str(chnl_termid), ]
    log.debug('find fund req_data:%s', req_data)
    resp_data = thrift_callex(fund_server, FundService, 'findfund', req_data)
    log.info('find fund resp_data:%s', resp_data)
    if not resp_data:
        raise Exception, 'call findfund failed'
    if resp_data.records and len(resp_data.records) > 0:
        log.info('trade not need deal because of chnl termid')
        return False
    # 根据通道商户id(chnl_mchntid)验证交易是否需要结算
    req_data.val_type = 1
    req_data.vals = [str(chnl_mchntid), ]
    log.debug('find fund req_data:%s', req_data)
    resp_data = thrift_callex(fund_server, FundService, 'findfund', req_data)
    log.info('find fund resp_data:%s', resp_data)
    if not resp_data:
        raise Exception, 'call findfund failed'
    if resp_data.records and len(resp_data.records) > 0:
        log.info('trade not need deal because of chnl mchntid')
        return False
    # 需要结算
    return True
Пример #24
0
 def reply_query_location(self, key=None, page_curr=1, page_size=20):
     '''
         地理位置的文本回复
         key:  LocationKey的类变量
         page_curr: 分页查询时的页数
         page_size: 分页查询时每页显示的数量
         如果这里出现异常,直接抛出去,调用方需要捕获
         返回结果中,extitle, extail, exlink开头,为解析push_txt后的数据
     '''
     #log.debug('key:%s', key)
     if isinstance(key, str):
         key = [
             key,
         ]
     if not key:
         key = LOCATION_KEY._KEYS
     # 拼接请求参数
     page = PageQuery()
     page.num = page_curr
     page.size = page_size
     req_args = ReplyQuery()
     req_args.appid = self.appid
     req_args.mp_keys = key
     req_args.page = page
     # 请求
     log.debug('req_args:%s', req_args)
     resp_data = thrift_callex(self.server, QFMP, 'reply_query', req_args)
     log.info('resp_data:%s', resp_data)
     # 解析数据
     # 如果是文本推送,拆分成title, tail, link
     for item in resp_data.data:
         # 默认的值
         item.extitle = ''
         item.extail = ''
         item.exlink = ''
         if item.push_type != ReplyType.TEXT:
             continue
         # 文本推送,解析推送内容
         push_txt_item = item.push_txt.split(self.LOCATION_SEPARATOR)
         item_cnt = len(push_txt_item)
         if item_cnt == 1:
             item.extitle = push_txt_item[0]
         elif item_cnt == 2:
             item.extitle = push_txt_item[0]
             if push_txt_item[1]:
                 # 解析html数据
                 soup = BeautifulSoup(push_txt_item[1], 'html.parser')
                 a_tag = soup.a
                 if a_tag:
                     item.extail = a_tag.text
                     item.exlink = a_tag['href']
                     # thrift请求,返回值都是utf-8,所以这里也把编码统一为utf-8
                     if isinstance(item.extail, unicode):
                         item.extail = item.extail.encode('utf-8')
                     if isinstance(item.exlink, unicode):
                         item.exlink = item.exlink.encode('utf-8')
                 else:
                     item.extail = push_txt_item[1]
     return resp_data
Пример #25
0
def get_weixin_profile(customer_id):
    ''' 获取微信基本信息'''
    spec = json.dumps({'id': customer_id})
    profiles = thrift_callex(OPENUSER_SERVER, QFCustomer, 'get_profiles',
                             OPENUSER_APPID, spec)
    if not profiles:
        return {}
    return profiles[0].__dict__
Пример #26
0
    def POST(self):
        params = self.req.input()

        code_info = self.get_code_info(params.get('code'))
        req_args = json.dumps({
            'verify_id': code_info['id'],
            'userid': int(self.user.userid)
        })

        try:
            thrift_callex(config.QF_MARKETING_SERVERS, QFMarketing,
                          'verify_actv_verify', req_args)
        except:
            log.warn(traceback.format_exc())
            raise ThirdError('核销失败')

        return success({})
Пример #27
0
def account2_client(func, *args, **kw):
    try:
        return thrift_callex(config.ACCOUNT2_SERVER, Account2, func, *args,
                             **kw)
    except ServerError as e:
        raise ThirdError(e.msg)
    except:
        log.warn(traceback.format_exc())
        raise ThirdError('第三方服务错误')
Пример #28
0
def gen_id():
    '''生成唯一号'''
    try:
        ret = thrift_callex(config.SPRING_SERVERS, Spring, "getid")
        return int(ret)
    except:
        log.error("call Spring error. reason .{0}".format(
            traceback.format_exc()))
        raise
Пример #29
0
def get_member_info(cid):
    spec = json.dumps({"user_id": cid})
    try:
        r = thrift_callex(config.OPENUSER_SERVER, OpenUser, 'get_profiles',
                          config.OPENUSER_APPID, spec)
        log.debug('r:%s' % r)
        return r[0].__dict__
    except:
        log.warn('get openuser_info error:%s' % traceback.format_exc())
Пример #30
0
def call_finance(func, *args, **kwargs):
    log.debug('req finance: %s %s %s', func, args, kwargs)
    try:
        ret = thrift_callex(config.FINANCE_SERVER, Finance, func, *args,
                            **kwargs)
        log.debug('finance ret: %s', ret)
        return ret
    except finance_ttypes.ServerException as e:
        log.warn('finance error: %s', str(e))
        raise