def use(self, order_id, money): """ 使用锦歌饭卡支付 """ trade_time = datetime.now().strftime('%Y%m%d%H%M%S') is_success, trade_id = jinge_api_util.pay(self.card_number, self.card_password, self.token, money, self.mer_id, self.term_id, trade_time) if is_success: watchdog.info( u'use jinge_card: {}, order_id: {}, trade_id: {}, money: {}'. format(self.card_number, order_id, trade_id, money)) third_party_pay_models.JinGeCardLog.create( jinge_card=self.id, price=money, trade_id=trade_id, order_id=order_id, reason=u"下单", balance=self.balance, ) else: watchdog.alert( u'use jinge_card error: {}, order_id: {}, trade_id: {}, money: {}' .format(self.card_number, order_id, trade_id, money)) return is_success, trade_id
def post(args): """ @brief 修改收货地址 @param ship_id @param ship_name @param ship_address @param ship_tel @param area @return {result:True} """ webapp_user = args['webapp_user'] ship_info_id = int(args['ship_id']), new_ship_info = { 'ship_name': args['ship_name'], 'ship_address': args['ship_address'], 'ship_tel': args['ship_tel'], 'area': args['area'] } area = args['area'] if False in map(lambda x:x.isdigit(),area.split('_')): webapp_user_id = args['webapp_user'].id message = u'错误的收货地址地区信息:webapp_user_id:%s,ship_info_id:%s,area:%s' % (webapp_user_id, ship_info_id, area) watchdog.alert(message) return 400, u'错误的收货地址信息' result = webapp_user.modify_ship_info(ship_info_id, new_ship_info) if result: return { 'result': result } else: return 500, ''
def get_card_info_by_phone(phone_number): """ 根据手机号获取用户的饭卡卡号和token """ url = JINGE_HOST + 'checkPhone.json' params = {'phone': phone_number} resp = requests.post(url, data=params) if resp.status_code == 200: try: json_data = json.loads(resp.text) if json_data['ret'] == 1: watchdog.info('get_card_info_by_phone success requests: %s, params: %s, results: %s' % (url, params, json_data)) return { 'card_number': json_data['cardNo'], 'token': json_data['token'], 'name': json_data['vipName'], #员工姓名 'company': json_data['merName'], #公司名称 'mer_id': json_data['merId'], #商户号 'term_id': json_data['termId'] #终端号 }, '' else: return None, json_data['tip'] watchdog.alert('get_card_info_by_phone fail requests: %s, params: %s, resp: %s' % (url, params, resp.content)) except Exception, e: watchdog.alert('get_card_info_by_phone fail requests: %s, params: %s, resp: %s, Exception: %s' % (url, params, resp.content, e))
def put(args): """ 新建收货地址 @param ship_name @param ship_address @param ship_tel @param area @return {'ship_info_id': ship_info_id} """ webapp_user = args['webapp_user'] ship_info = { 'ship_name': args['ship_name'], 'ship_address': args['ship_address'], 'ship_tel': args['ship_tel'], 'area': args['area'] } area = args['area'] if False in map(lambda x:x.isdigit(),area.split('_')): webapp_user_id = args['webapp_user'].id message = u'错误的收货地址地区信息:webapp_user_id:%s,area:%s' % (webapp_user_id, area) watchdog.alert(message) return 400, u'保存失败,错误的收货地址信息' result, ship_info_id = webapp_user.create_ship_info(ship_info) if result: return { 'ship_info_id': ship_info_id } else: return 500, ''
def test_local_handle(): # 测试本地情况的handle from core.handlers.event_handler_util import handle args = { 'GET': { 'get1': 'value1', 'get2': 'value2' }, 'COOKIES': '<cookie>', 'method': 'GET', 'POST': { 'post1': 'value1', 'post2': 'value2' }, 'data': { 'app_id': '123', 'user_id': user_id, 'webppuser_id': webapp_user.id, 'user_profile_id': user_profile_id, 'social_account_id': social_account.id, 'member_id': member.id, 'is_user_from_mobile_phone': False, 'is_user_from_weixin': False, }, 'visit_data': '<visit_data>' } result = handle(args, 'example') watchdog.alert('result: {}'.format(result)) watchdog.error('result: {}'.format(result)) watchdog.info('result: {}'.format(result)) print('result: {}'.format(result))
def set_password(card_number, token, password): """ 首次设置支付密码 """ url = JINGE_HOST + 'setPass.json' try: card_number = card_number.encode('utf-8') token = token.encode('utf-8') except: pass params = { 'cardNo': card_number, 'token': token, 'newPass': password } resp = requests.post(url, data=params) if resp.status_code == 200: try: json_data = json.loads(resp.text) if json_data['ret'] == 1: watchdog.info('set password success requests: %s, params: %s, results: %s' % (url, params, json_data)) return True else: watchdog.alert('set password fail requests: %s, params: %s, resp: %s' % (url, params, resp.content)) except Exception, e: watchdog.alert('set password fail requests: %s, params: %s, resp: %s, Exception: %s' % (url, params, resp.content, e))
def __log(self, is_success, url, params, resp, failure_type='', traceback=''): if failure_type: failure_type = 'APIResourceClient_ERROR:' + failure_type msg = { 'is_success': is_success, 'url': url, 'params': params, 'failure_type': failure_type, 'traceback': traceback } resp = self.resp if resp: msg['http_code'] = resp.status_code msg['resp_text'] = resp.text else: msg['http_code'] = '' msg['resp_text'] = '' if is_success: watchdog.info(msg, CALL_SERVICE_WATCHDOG_TYPE) else: watchdog.alert(msg, CALL_SERVICE_WATCHDOG_TYPE)
def pay(card_number, card_password, token, money, mer_id, term_id, trade_time): """ 支付 """ url = JINGE_HOST + 'cardPay.json' params = { 'cardNo': card_number, 'token': token, 'merId': mer_id, #商户号 'termId': term_id, #终端号 'money': money, 'password': card_password, 'tradeTime': trade_time, #交易时间 } resp = requests.post(url, data=params) if resp.status_code == 200: try: json_data = json.loads(resp.text) if json_data['ret'] == 1: watchdog.info('jinge_card pay success requests: %s, params: %s, results: %s' % (url, params, json_data)) trade_id = json_data['tradeId'] return True, trade_id else: watchdog.alert('jinge_card pay requests: %s, params: %s, resp: %s' % (url, params, resp.content)) except Exception, e: watchdog.alert('jinge_card pay fail requests: %s, params: %s, resp: %s, Exception: %s' % (url, params, resp.content, e))
def __log(self, is_success, url, params, method, failure_type='', failure_msg=''): msg = { 'is_success': is_success, 'url': url, 'params': params, 'method': method, 'failure_type': failure_type, 'failure_msg': failure_msg, } resp = self.__resp if resp: msg['http_code'] = resp.status_code msg['resp_text'] = resp.text else: msg['http_code'] = '' msg['resp_text'] = '' if is_success: watchdog.info(msg, CALL_SERVICE_WATCHDOG_TYPE, server_name=self.service) else: watchdog.alert(msg, CALL_SERVICE_WATCHDOG_TYPE, server_name=self.service)
def put(args): """ openapi 取消订单操作(退款) @param id 商品ID 更改订单状态 """ order_id = args['order_id'] msg = '' try: order = Order.from_id({ 'webapp_user': args['webapp_user'], 'webapp_owner': args['webapp_owner'], 'order_id': order_id }) msg, success = order.refund() info = u"openapi apiserver中修改订单状态失败, order_id:{}, cause:\n{}".format( args['order_id'], msg) watchdog.info(info) if msg: return 500, {'msg': msg, 'success': False} else: return 200, {'msg': msg, 'success': True} except: notify_message = u"openapi apiserver中修改订单状态失败, order_id:{}, cause:\n{}".format( args['order_id'], unicode_full_stack()) watchdog.alert(notify_message) return 500, {'msg': msg, 'success': False}
def supplier_name(self): try: # 非微众系列商家 if not self.context['webapp_owner'].user_profile.webapp_type: return '' # 手动添加的供货商 if self.supplier: supplier = account_model.UserProfile.select().dj_where( user_id=self.supplier).first() if supplier: return supplier.store_name else: supplier = mall_models.Supplier.select().dj_where( id=self.supplier).first() if supplier: print 'still old supplier ........................', self.supplier return supplier.name # 同步的供货商 relation = mall_models.WeizoomHasMallProductRelation.select( ).dj_where(weizoom_product_id=self.id).first() if relation: supplier_name = account_model.UserProfile.select().dj_where( user_id=relation.mall_id).first().store_name else: supplier_name = '' return supplier_name except: watchdog.alert(unicode_full_stack()) return ''
def put(args): """ @warning: 对外网开放的支付接口,只接受从h5支付方式列表发起的货到付款,高风险,改动需慎重 """ webapp_user = args['webapp_user'] webapp_owner = args['webapp_owner'] order_id = args['order_id'].split('-')[0] pay_interface_type = int(args['pay_interface_type']) # 此接口只可使用货到付款 if pay_interface_type != mall_models.PAY_INTERFACE_COD: watchdog.alert('货到付款接口被异常调用,woid:%s,webapp_user_id:%s', (webapp_owner.id, webapp_user.id)) return 500, {} order = Order.from_id({ 'webapp_owner': webapp_owner, 'webapp_user': webapp_user, 'order_id': order_id }) try: is_success, msg = order.pay( pay_interface_type=mall_models.PAY_INTERFACE_COD) except: is_success = False msg = unicode_full_stack() watchdog.alert(msg) return { 'order_id': args['order_id'], 'is_success': is_success, }
def wrapper(*args, **kw): try: return func(*args, **kw) except: watchdog.alert({ 'uuid': 'order_trade_error', 'traceback': unicode_full_stack() })
def get_product_classifications(): try: product_classifications = mall_models.Classification.select().dj_where(status=1) product_classifications = [ProductClassification(classification).to_dict() for classification in product_classifications] return product_classifications except: watchdog.alert(unicode_full_stack()) return False
def __log_exception(self, e=BaseException): if isinstance(e, redis.exceptions.RedisError): exception_type = 'redis_error' else: exception_type = 'other' watchdog.alert( 'redis_lock_error:type:{}.\nunicode_full_stack:{}'.format(exception_type, unicode_full_stack())) self.__redis_error = True return True
def from_member_has_cards(args): """ member_has_cards:MemberHasWeizoomCard models """ member_has_cards = list(args['member_has_cards']) if len(member_has_cards) == 0: return True, [], [] card_number2models = {a.card_number: a for a in member_has_cards} card_numbers_passwords = [ {'card_number': a.card_number, 'card_password': WZCard.__decrypt_password(a.card_password)} for a in member_has_cards] resp = WZCard.get_card_infos({ 'card_infos': card_numbers_passwords }) if resp: card_infos = resp['data']['card_infos'] cards = [] for card in card_infos: card_detail = card.values()[0] card_number = card.keys()[0] member_has_card_model = card_number2models[card_number] cards.append(WZCard(member_has_card_model, card_detail)) cards = sorted(cards, key=lambda x: -x.bound_at) usable_cards = [] unusable_cards = [] _cards = [] for card in cards: if card.status in ('used', 'unused'): usable_cards.append(card) elif card.status in ('empty', 'expired'): _cards.append(card) elif card.status == 'inactive': unusable_cards.append(card) else: watchdog.alert({ 'description': u'Error card status', 'card_number': card.card_number, 'card_status': card.status }) unusable_cards.extend(_cards) return True, usable_cards, unusable_cards else: return False, [], []
def filter_products(self, args): raw_products = args['products'] product_name = filter_invalid_str(args['product_name'], '').strip() products = filter(lambda x: product_name in x['name'], raw_products) try: self.__log_record(product_name) except: msg = unicode_full_stack() watchdog.alert(msg) return products
def get_wapi_lock(lockname, lock_timeout=1): try: conn = DEFAULT_CONN identifier = '1' lockname = 'lk:' + lockname lock_timeout = int(math.ceil(lock_timeout)) if conn.set(name=lockname, value=identifier, nx=True, ex=lock_timeout): return identifier else: return False except: watchdog.alert(unicode_full_stack()) return True
def call_wapi(self, method, app, resource, req, resp): watchdog_client.watchdogClient = watchdog_client.WatchdogClient( settings.SERVICE_NAME) response = { "code": 200, "errMsg": "", "innerErrMsg": "", } resp.status = falcon.HTTP_200 args = {} args.update(req.params) args.update(req.context) args['wapi_id'] = req.path + '_' + req.method param_args = {} param_args['req_params'] = req.params try: raw_response = wapi_resource.wapi_call(method, app, resource, args, req) if type(raw_response) == tuple: response['code'] = raw_response[0] response['data'] = raw_response[1] if response['code'] != 200: response['errMsg'] = response['data'] response['innerErrMsg'] = response['data'] else: response['code'] = 200 response['data'] = raw_response except wapi_resource.ApiNotExistError as e: response['code'] = 404 response['errMsg'] = str(e).strip() response['innerErrMsg'] = unicode_full_stack() except Exception as e: response['code'] = 531 #不要改动这个code,531是表明service内部发生异常的返回码 response['errMsg'] = str(e).strip() response['innerErrMsg'] = unicode_full_stack() msg = {'traceback': unicode_full_stack()} watchdog.alert(msg, 'Error') resp.body = json.dumps(response, default=_default) try: param_args['app'] = app param_args['resource'] = resource param_args['method'] = method param_args.update(json.loads(resp.body)) #param_args.update(simplejson.loads(resp.body)) watchdog.info(param_args, "CALL_API") except: pass
def get(args): """ 获取支付结果页面 @param id 订单order_id """ webapp_user = args['webapp_user'] webapp_owner = args['webapp_owner'] order_id = args['order_id'].split('-')[0] order = Order.from_id({ 'webapp_owner': webapp_owner, 'webapp_user': webapp_user, 'order_id': order_id }) if not order.is_valid(): msg = u'订单({})不存在'.format(order_id) error_msg = u'weixin pay, stage:[get_pay_result], result:{}, exception:\n{}'.format( msg, msg) watchdog.alert(error_msg) return 500, {'msg': error_msg} is_show_red_envelope = False red_envelope_rule_id = 0 red_envelope = webapp_owner.red_envelope if RedEnvelope.can_show_red_envelope(order, red_envelope): # 是可以显示分享红包按钮 is_show_red_envelope = True red_envelope_rule_id = red_envelope['id'] order_config = OrderConfig.get_order_config( {'webapp_owner': webapp_owner}) qrcode_img = webapp_owner.qrcode_img activity_url = '' if order.is_group_buy: activity_url = order.order_group_info[ 'activity_url'] + '&from=pay_result' return { 'is_trade_success': True, 'order': order.to_dict('is_group_buy'), 'is_show_red_envelope': is_show_red_envelope, 'red_envelope_rule_id': red_envelope_rule_id, 'qrcode_img': qrcode_img, 'activity_url': activity_url, 'order_config': order_config }
def get(args): #TODO2: 临时解决方案,后续去除 CachedProduct.webapp_owner = args['webapp_owner'] webapp_owner_id = args['webapp_owner'].id product_id = args['product_id'] member = args.get('member', None) member_grade_id = member.grade_id if member else None try: product = CachedProduct.__get_from_cache(webapp_owner_id, product_id, member_grade_id) if CachedProduct.webapp_owner.mall_type: is_pool_product = mall_models.ProductPool.select().dj_where( woid=webapp_owner_id, product_id=product_id).count() > 0 if product.owner_id != webapp_owner_id and ( not is_pool_product): product.is_deleted = True elif product.owner_id != webapp_owner_id and is_pool_product: pool_product = mall_models.ProductPool.select().dj_where( woid=webapp_owner_id, product_id=product_id).first() if pool_product.status == mall_models.PP_STATUS_ON: product.shelve_type = mall_models.PRODUCT_SHELVE_TYPE_ON elif pool_product.status == mall_models.PP_STATUS_OFF: product.shelve_type = mall_models.PRODUCT_SHELVE_TYPE_OFF else: product.is_deleted = True elif product.owner_id != webapp_owner_id: product.is_deleted = True except: if settings.DEBUG and not settings.IS_UNDER_BDD: raise else: #记录日志 alert_message = u"获取商品记录失败,商品id: {} cause:\n{}".format( product_id, unicode_full_stack()) watchdog.alert(alert_message) #返回"被删除"商品 product = Product() product.is_deleted = True return product
def put(args): """ 微信支付、支付宝回调接口 @return: """ webapp_user = args['webapp_user'] webapp_owner = args['webapp_owner'] order_id = args['order_id'].split('-')[0] if order_id.startswith('vip_'): #如果是会员卡的订单,则特殊处理 order = MemberCardPayOrder.from_order_id({ 'webapp_owner': args['webapp_owner'], 'webapp_user': args['webapp_user'], 'order_id': order_id }) order.pay() is_success = True msg = '' else: #普通商城订单 pay_interface_type = int(args['pay_interface_type']) order = Order.from_id({ 'webapp_owner': webapp_owner, 'webapp_user': webapp_user, 'order_id': order_id }) try: is_success, msg = order.pay( pay_interface_type=pay_interface_type) except: is_success = False msg = unicode_full_stack() watchdog.alert(msg) return { 'order_id': args['order_id'], 'is_success': is_success, 'msg': msg }
def create_ship_info(self, ship_info): """ @param ship_info: 收货地址信息,字典类型 @return ship_info_id """ try: member_models.ShipInfo.update(is_selected=0).where( member_models.ShipInfo.webapp_user_id == self.id).execute() ship_info_id = member_models.ShipInfo.create( webapp_user_id=self.id, ship_tel=ship_info['ship_tel'], ship_address=ship_info['ship_address'], ship_name=ship_info['ship_name'], area=ship_info['area']).id return True, ship_info_id except: msg = unicode_full_stack() watchdog.alert(msg, type='WAPI') return False, 0
def refund(card_number, card_password, token, trade_id, order_id, price): """ 退款 """ url = JINGE_HOST + 'getRefund.json' try: card_number = card_number.encode('utf-8') token = token.encode('utf-8') card_password = card_password.encode('utf-8') trade_id = trade_id.encode('utf-8') except: pass params = { 'cardNo': card_number, 'password': card_password, 'token': token, 'tradeId': trade_id } resp = requests.post(url, data=params) if resp.status_code == 200: try: json_data = json.loads(resp.text) if json_data['ret'] == 1: watchdog.info('jinge_card refund success requests: %s, params: %s, results: %s' % (url, params, json_data)) trade_amount = json_data['tradeAmount'] refund_trade_id = json_data['tradeId'] if trade_amount != price: #如果退款的金额跟消费的金额不一致就往钉钉群里发报警消息 msg = u'锦歌饭卡退款金额与消费金额不一致,\n请求退款金额: {}\n实际退款金额: {}\norder_id: {}\ncard_number: {}\ntrade_id: {}\nrefund_trade_id: {}'.format( price, trade_amount, order_id, card_number, trade_id, refund_trade_id ) ding_util.send_message_to_ding(msg, token=DING_TOKEN, at_mobiles=AT_MOBILES) return True, refund_trade_id, trade_amount else: watchdog.alert('jinge_card refund fail requests: %s, params: %s, resp: %s' % (url, params, resp.content)) except Exception, e: watchdog.alert('jinge_card refund fail requests: %s, params: %s, resp: %s, Exception: %s' % (url, params, resp.content, e))
def post(args): """ 更改订单状态 @todo 目前取消订单和确认收货都是通过此接口,需要分离 """ # if not get_wapi_lock(lockname='order_post_' + str(args['webapp_user'].id), lock_timeout=2): # watchdog.alert('wapi接口被刷,wapi:%s,webapp_user_id:%s' % ('mall.order_post', str(args['webapp_user'].id))) # reason_dict = { # "is_success": False, # "msg": u'请勿短时间连续下单', # "type": "coupon" # 兼容性type # } # return 500, {'detail': [reason_dict]} # 兼容修改价格后订单从支付模块返回的跳转(支付模块会添加edit_money) order_id = args['order_id'].split('-')[0] try: order = Order.from_id({ 'webapp_user': args['webapp_user'], 'webapp_owner': args['webapp_owner'], 'order_id': order_id }) action = args['action'] validate_result, reason = order.validate_order_action(action, args['webapp_user'].id) msg = u"apiserver中修改订单状态失败, order_id:{}, action:{}, cause:\n{}".format(args['order_id'], args['action'], reason) watchdog.info(msg) if not validate_result: return 500, {'msg': reason} if action == 'cancel': order.cancel() elif action == 'finish': order.finish() except: notify_message = u"apiserver中修改订单状态失败, order_id:{}, action:{}, cause:\n{}".format(args['order_id'], args['action'], unicode_full_stack()) watchdog.alert(notify_message) return 500, ''
def select_default_ship(self, ship_id): """ 选择默认收货地址 Args: ship_id: Returns: """ try: # 更新收货地址信息 member_models.ShipInfo.update(is_selected=False).where( member_models.ShipInfo.webapp_user_id == self.id).execute() member_models.ShipInfo.update(is_selected=True).where( member_models.ShipInfo.id == ship_id).execute() return True except: msg = unicode_full_stack() watchdog.alert(msg, type='WAPI') return False
def modify_ship_info(self, ship_info_id, new_ship_info): """ @param ship_info_id: 收货地址id @param new_ship_info: 新信息 @return bool """ try: member_models.ShipInfo.update(is_selected=False).where( member_models.ShipInfo.webapp_user_id == self.id).execute() member_models.ShipInfo.update( ship_tel=new_ship_info['ship_tel'], ship_address=new_ship_info['ship_address'], ship_name=new_ship_info['ship_name'], area=new_ship_info['area'], is_selected=True).dj_where(id=ship_info_id).execute() return True except: msg = unicode_full_stack() watchdog.alert(msg, type='WAPI') return False
def get_balance(card_number, token): """ 查询余额 """ url = JINGE_HOST + 'qurBalance.json' params = { 'cardNo': card_number, 'token': token } resp = requests.post(url, data=params) if resp.status_code == 200: try: json_data = json.loads(resp.text) if json_data['ret'] == 1: watchdog.info('get balance success requests: %s, params: %s, results: %s' % (url, params, json_data)) return json_data['balance'] else: watchdog.alert('get balance fail requests: %s, params: %s, resp: %s' % (url, params, resp.content)) except Exception, e: watchdog.alert('get balance fail requests: %s, params: %s, resp: %s, Exception: %s' % (url, params, resp.content, e))
def get_from_cache(key, on_miss): """ 从cache获取数据,构建对象 """ obj = GET_CACHE(key) if obj or exists_key(key): return obj else: try: fresh_obj = on_miss() if not fresh_obj: return None value = fresh_obj['value'] SET_CACHE(key, value) if 'keys' in fresh_obj: for fresh_key in fresh_obj['keys']: SET_CACHE(fresh_key, value) return value except: if settings.DEBUG: raise else: watchdog.alert(unicode_full_stack()) return None
def microservice_consume(url='', data={}, method='get', timeout=None): _timeout = timeout if timeout else DEFAULT_TIMEOUT try: if method == 'get': resp = requests.get(url, data, timeout=_timeout) elif method == 'post': resp = requests.post(url, data, timeout=_timeout) else: # 兼容架构中的put、delete方法 url = url + '?_method=' + method if '_method' not in url else url resp = requests.post(url, data, timeout=_timeout) if resp.status_code == 200: resp_data = json.loads(resp.text)['data'] try: weizoom_code = json.loads(resp.text)['code'] except: weizoom_code = 10086 # 无法得到正确weizoom_code时的默认值 if weizoom_code == 200: watchdog.info( u'microservice_consume_log,外部接口成功调用日志.code:%s,weizoom_code:%s,url:%s,request_data:%s,resp:%s' % (resp.status_code, weizoom_code, url, str(data), resp.text)) return True, resp_data else: watchdog.alert( u'microservice_consume_alert,外部接口调用错误-wzcode错误状态码.code:%s,weizoom_code:%s,url:%s,request_data:%s,resp:%s' % (resp.status_code, weizoom_code, url, str(data), resp)) raise ResponseCodeException else: watchdog.alert( u'microservice_consume_alert,外部接口调用错误-http错误状态码.code:%s,url:%s,data:%s' % (resp.status_code, url, str(data))) raise ResponseCodeException except BaseException as e: traceback = unicode_full_stack() watchdog.alert(u'外部接口调用错误-异常.url:%s,msg:%s,url:%s ,data:%s' % (url, traceback, url, str(data))) raise Exception(e)