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 __log(self, is_success, url, params, method, failure_type='', failure_msg=''): msg = { 'url': url, 'params': params, 'method': method, 'resource': self.__resource, 'target_service': self.__target_service, 'failure_type': failure_type, 'failure_msg': failure_msg, } resp = self.__resp if resp: msg['http_code'] = resp.status_code if method == 'get': msg['resp_text'] = 'stop_record' else: msg['resp_text'] = self.__json_data else: msg['http_code'] = '' msg['resp_text'] = '' if is_success: watchdog.info(msg, CALL_SERVICE_WATCHDOG_TYPE) else: watchdog.critical(msg, CALL_SERVICE_WATCHDOG_TYPE)
def send_message_to_ding(msg, token=DEFAULT_DING_TOKEN, at_mobiles=[], is_at_all=False): """ 发送钉钉报警信息 """ webhook = u'https://oapi.dingtalk.com/robot/send?access_token=%s' % token text = { "msgtype": "text", "text": { "content": msg }, "at": { "atMobiles": [], "isAtAll": 'false' } } if is_at_all: text["at"]["isAtAll"] = "true" elif len(at_mobiles) > 0: text["at"]["atMobiles"] = at_mobiles watchdog.info('send msg: %s' % text) response = requests.post(webhook, json=text) result = json.loads(response.text) if result['errmsg'] == u'ok': return True return False
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 refund_for_order(order): """ 微众卡退款 """ # 交易类型(支付失败退款:0、普通退款:1) trade_id = mall_models.OrderCardInfo.select().dj_where(order_id=order.order_id).first().trade_id data = { 'trade_id': trade_id, 'trade_type': 1 # 普通退款 } msg = { 'uuid': 'refund_wzcard', 'order_id': order.order_id, 'weizoom_card_money': order.weizoom_card_money } watchdog.info(message=msg, log_type='business_log') resp = Resource.use('card_apiserver').delete({ 'resource': 'card.trade', 'data': data }) return resp
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 api_put(request): #驳回 business_id = request.POST.get('id','') reason = request.POST.get('reason','') try: models.Business.objects.filter(id=business_id).update( status = models.UNPASSED, reason = reason ) try: business = models.Business.objects.get(id=business_id) if business.phone: # content = u'%s【微众传媒】' % data = { "content" : { "reason": reason }, "phones": str(business.phone), "sms_code": "SMS_27200001" } rs = send_phone_msg.send_phone_captcha(data) except: watchdog.info(u"发送驳回信息异常 id:%s" % business_id) response = create_response(200) return response.get_response() except: response = create_response(500) response.errMsg = u'该记录不存在,请检查' return response.get_response()
def process_request(self, req, res): #TODO 将这部分放到 lua + nginx中(或者kong中) if '/auth/access_token' in req.path or 'console' in req.path: return access_token = req.params.get('access_token', None) if not access_token: raise redirects.HTTPMiddlewareError({ "errcode": 40003, "errmsg": "invalid access_token" }) app = cache_util.get_cache_wrapper( hashlib.md5(access_token).hexdigest()) if not app: raise redirects.HTTPMiddlewareError({ "errcode": 40003, "errmsg": "invalid access_token" }) req.context['appid'] = json.loads(app)['appid'] req.context['woid'] = json.loads(app)['woid'] req.context['apiserver_access_token'] = json.loads( app)['apiserver_access_token'] req.context['supplier_ids'] = json.loads(app)['supplier_ids'] watchdog.info("auth:woid:%s" % req.context['woid']) watchdog.info("auth:apiserver_access_token:%s" % req.context['apiserver_access_token'])
def get_specific_model(self, model_name): """ 获得特定的商品规格信息 @param [in] model_name: 商品规格名 @return ProductModel对象 注意,这里返回的有可能是被删除的规格,使用者应该通过product_model.is_deleted来判断 """ models = self.models if not models: watchdog.info({ 'msg': u'商品models为空!', 'product_id': self.id, 'product_detail': self.to_dict() }) Product.__fill_model_detail(self.context['corp'], [self], True) models = self.models candidate_models = filter(lambda m: m.name == model_name if m else False, models) if len(candidate_models) > 0: model = candidate_models[0] return model else: candidate_models = filter(lambda m: m.name == model_name if m else False, self.__deleted_models) if len(candidate_models) > 0: model = candidate_models[0] return model else: return None
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 create(args): """ 创建商品评论 """ owner_id = args['webapp_owner'].id logging.info("to create a ProductReview") relation = mall_models.OrderHasProduct.get( id=args['order_has_product_id']) model, created = mall_models.ProductReview.get_or_create( member_id=args['member_id'], order_review=args['order_review'].id, order_id=args['order_id'], owner_id=owner_id, product_id=args['product_id'], order_has_product=relation, product_score=args['product_score'], review_detail=args['review_detail']) logging.info("created model, created={}".format(created)) product_review = ProductReview(model) logging.info("product_review={}".format(product_review.to_dict())) picture_list = args.get('picture_list') if picture_list: logging.info( "saving product review picture list..., picture_list=%s" % picture_list) for picture in list(eval(picture_list)): mall_models.ProductReviewPicture(product_review=model, order_has_product=relation, att_url=picture).save() watchdog.info(u"create_product_review after save img %s" % (picture), \ type="mall", user_id=owner_id) watchdog.info(u"create_product_review end, order_has_product_id is %s" % \ (args['order_has_product_id']), type="mall", user_id=owner_id) return product_review
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 __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 __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 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 process_request(sel, req, resp): if '/user/access_token' in req.path or '/console/' in req.path: watchdog.info( "skipped in WebAppAccountMiddleware. req.path: {}".format( req.path)) return if 'access_token' in req.params: access_token = req.params.get('access_token', None) account_info = AccessToken.get_sys_account( {'access_token': access_token}) if settings.DEBUG: watchdog.debug( 'WebAppOAuthMiddleware:access_token:>>>>>>>>>>>>>%s' % req.params['access_token']) watchdog.debug( 'account_info from access_token>>>>>>>>>>>>:%s' % account_info) if account_info.has_key('errorcode'): raise HTTPMiddlewareError(account_info) woid = account_info['webapp_owner'].id req.context['webapp_owner'] = account_info['webapp_owner'] req.context['webapp_user'] = account_info[ 'system_account'].webapp_user return elif settings.MODE == "develop" or settings.MODE == "test": # 开发测试支持 不传递woid使用jobs用户,不传递openid使用bill_jobs会员 # if not 'woid' in req.params: # return woid = req.params.get('woid') if not woid: woid = account_models.User.select().dj_where( username='******')[0].id openid = req.params.get('openid') if not openid: openid = 'bill_jobs' else: raise ValueError("error access_token") if req.context.has_key('webapp_owner') and req.context.has_key( 'webapp_user'): return #TODO2: 支持开发的临时解决方案,需要删除 openid = 'bill_jobs' #填充webapp_owner webapp_owner = WebAppOwner.get({'woid': woid}) req.context['webapp_owner'] = webapp_owner if openid == 'notopenid': return #填充会员帐号信息 system_account = SystemAccount.get({ 'webapp_owner': webapp_owner, 'openid': openid }) req.context.update({'webapp_user': system_account.webapp_user})
def put(args): order_id = args['order_id'] express_company_name = args['express_company_name'] express_number = args['express_number'] data_mns = [] data = { 'order_id': order_id, 'express_company_name': express_company_name, 'express_number': express_number } resp = Resource.use('zeus').put({ 'resource': 'mall.delivery', 'data': data }) errcode = SYSTEM_ERROR_CODE # 获取app_id传送到mns进行消息处理 pay_log = PayLog.from_order_id({"order_id": order_id}) if pay_log: app_id = pay_log.appid else: watchdog.info( "order paylog is not exits, delivery mns message send failed!! order_id:{}, msg:{}" .format(order_id, unicode_full_stack()), log_type='OPENAPI_ORDER') errcode = DELIVERY_ORDER_HAS_NO_PAYLOG return {'errcode': errcode, 'errmsg': code2msg[errcode]} topic_name = TOPIC['order'] data_mns['order_id'] = order_id data_mns['app_id'] = app_id or '' data_mns['express_company_name'] = express_company_name data_mns['express_number'] = express_number if resp: if resp['code'] == 200: if resp['data']['result'] == 'SUCCESS': errcode = SUCCESS_CODE data = {'errcode': errcode} msgutil.send_message(topic_name, 'delivery_item_shipped', data_mns) return data else: if resp['data']['msg'] == u'不能对当前订单发货': errcode = DELIVERY_ORDER_HAS_MULTIPLE_CHILD_ORDERS elif resp['data']['msg'] == u'订单状态已经改变': errcode = DELIVERY_ORDER_STATUS_ERROR elif resp['data']['msg'] == u'订单不存在': errcode = DELIVERY_ORDER_NOT_EXIST watchdog.info( "delivery failed!! errcode:{}, order_id:{}".format( errcode, order_id), log_type='OPENAPI_ORDER') if errcode == SYSTEM_ERROR_CODE: watchdog.error("delivery failed!! errcode:{}, msg:{}".format( errcode, unicode_full_stack()), log_type='OPENAPI_ORDER') return {'errcode': errcode, 'errmsg': code2msg[errcode]}
def watchdog_js_analysis(message, type='JS_Analysis', user_id='0', db_name='default'): # logging.critical(message_json(user_id, message, type)) watchdog.info(message=message, log_type=type, user_id=user_id, server_name='weapp')
def watchdog_info(message, type='WEB', user_id='0', db_name='default'): """ 用异步方式发watchdog 异步方式调用 weapp.services.send_watchdog_service.send_watchdog() """ watchdog.info(message=message, log_type=type, user_id=user_id, server_name='weapp')
def process_request(sel, req, resp): if '/user/access_token' in req.path or '/console/' in req.path: watchdog.info( "skipped in WebAppAccountMiddleware. req.path: {}".format( req.path)) return corp_id = req.params.get('woid') if not corp_id: corp_id = req.params.get('corp_id') req.context['corp'] = Corporation(corp_id) CorporationFactory.set(req.context['corp'])
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 _poll_response(self): """ 发送快递100 订阅请求,返回成功与否信息 """ # post中的param的json param_json_data = { self.express_params.COMPANY: self.express_company_name, self.express_params.NUMBER: self.express_number, self.express_params.TO: self.area, self.express_params.KEY: self.express_config.app_key, self.express_params.PARAMETERS: { self.express_params.CALLBACK_URL: self._get_api() } } # 将PARAMETERS的json转换为字符串 param_str = json.dumps(param_json_data) json_data = { self.express_params.SCHEMA: self.express_config.schema, self.express_params.PARAM: param_str } # print param_str verified_result = '' try: param_data = urllib.urlencode(json_data) # print '-------------------------------------------' # print param_data # if settings.IS_UNDER_BDD: # from test.bdd_util import WeappClient # bdd_client = WeappClient() # response = bdd_client.post('/tools/api/express/test_kuaidi_poll/?code=1', param_json_data) # verified_result = response.content # else: request = urllib2.Request(self.express_config.get_api_url(), param_data) response = urllib2.urlopen(request) verified_result = response.read() watchdog.info( u"发送快递100 订阅请求 url: {},/n param_data: {}, /n response: {}". format(self.express_config.get_api_url(), param_str, verified_result.decode('utf-8'))) except: watchdog.error(u'发送快递100 订阅请求 失败,url:{},data:{},原因:{}'.format( self.express_config.get_api_url(), param_str, unicode_full_stack())) return verified_result
def send_phone_message(mobile_number, reason, status): if status == account_models.USING: reason = u'应用激活审核通过,可以正常使用' elif status == account_models.STOPED: reason = u'应用已暂停使用' else: reason = u'应用激活申请被驳回,驳回原因:' + reason try: if mobile_number: content = u'%s【微众传媒】' % reason rs = send_phone_msg.send_phone_captcha(phones=str(mobile_number), content=content) except: watchdog.info(u"发送驳回信息异常 id:%s" % customer_id)
def _parse_result(self, result): data = dict() if result is None or len(result) == 0: return data try: data = json.loads(result) watchdog.info(u'从快递100获取订单信息,data{}'.format(result), self.express_config.watchdog_type) except: notify_message = u'解析快递100获取订单信息失败,url:{}, data:{}, 原因:{}'.format( result, data, unicode_full_stack()) watchdog.error(notify_message, self.express_config.watchdog_type) return data
def __acquire_create_order_lock_by_purchase_info(self, purchase_info): """ 使用redis锁避免并发时错误处理 @param locks: @param purchase_info: @return: """ locked_resources = [] self.context['create_order_lock'] = [] webapp_user_id = self.context['webapp_user'].id wzcard_list = [] if purchase_info.coupon_id and purchase_info.coupon_id != '0': # 优惠券锁 locked_resources.append({ 'name': REGISTERED_LOCK_NAMES['coupon_lock'], 'resource': str(purchase_info.coupon_id) }) if purchase_info.order_integral_info or purchase_info.group2integralinfo: locked_resources.append({ 'name': REGISTERED_LOCK_NAMES['integral_lock'], 'resource': str(webapp_user_id) }) # if purchase_info.wzcard_info: # for wzcard in purchase_info.wzcard_info: # wzcard_id = str(wzcard['card_name']) # if wzcard_id not in wzcard_list: # wzcard_list.append(wzcard_id) # locked_resources.append({'name': REGISTERED_LOCK_NAMES['wz_card_lock'], 'resource': str(wzcard['card_name'])}) for locked_resource in locked_resources: redis_lock = RedisLock() acquire_result = redis_lock.lock(locked_resource) if acquire_result: self.context['create_order_lock'].append(redis_lock) else: watchdog.info('acquire_lock_failure,resource:{}'.format( str(locked_resource))) return False return True
def post(args): woid = args['woid'] order_id = args['order_id'] access_token = args['apiserver_access_token'] timestamp = str(long(time.time() * 1000)) data = { 'order_id': order_id, 'timestamp': timestamp, 'woid': woid, u'access_token': access_token, 'action': 'cancel' } resp = Resource.use('apiserver').put({ 'resource': 'mall.refund', 'data': data }) status = 0 code = 0 errcode = SUCCESS_CODE if resp: code = resp["code"] if code == 200: return {'errcode': errcode} if code == 500: msg = resp['data']['msg'] errcode = SUB_ORDER_STATUS_ERROR if msg == u'有子订单的状态不是待发货,不能取消订单': errcode = CANCEL_ORDER_ERROR watchdog.info( "cancel order failed!! errcode:{}, msg:{}".format( errcode, msg), log_type='OPENAPI_ORDER') return {'errcode': errcode, 'errmsg': code2msg[errcode]} else: errcode = SYSTEM_ERROR_CODE watchdog.error("cancel order failed!! errcode:{}, msg:{}".format( errcode, unicode_full_stack()), log_type='OPENAPI_ORDER') return {'errcode': errcode, 'errmsg': code2msg[errcode]}
def __release_order(self, order, price_free_resources, price_related_resources): """ 当订单失败时,释放资源、清除数据库订单记录 1. price_free_resources 2. price_related_resources 3. Order、OrderHasProduct、OrderHasPromotion表 """ # 删除前记录 watchdog.info({ 'uuid': 'delete order', 'order_id': order.order_id, 'id': order.id }) if price_free_resources: self.__release_price_free_resources(price_free_resources) # # 删除Order相关数据库记录 # if order and order.id: # sub_order_ids = [o.id for o in mall_models.Order.select().dj_where(origin_order_id=order.id)] # mall_models.OrderHasPromotion.delete().dj_where(order_id=order.id).execute() # mall_models.OrderHasProduct.delete().dj_where(order_id=order.id).execute() # # if sub_order_ids: # mall_models.OrderHasProduct.delete().dj_where(order_id__in=sub_order_ids).execute() # # mall_models.Order.delete().dj_where(origin_order_id=order.id).execute() # mall_models.Order.delete().dj_where(id=order.id).execute() if order and order.id: # sub_order_ids = [o.id for o in mall_models.Order.select().dj_where(origin_order_id=order.id)] new_webapp_user_id = -order.webapp_user_id mall_models.Order.update( webapp_user_id=new_webapp_user_id).dj_where( origin_order_id=order.id).execute() mall_models.Order.update( webapp_user_id=new_webapp_user_id).dj_where( id=order.id).execute() if price_related_resources: self.__release_price_related_resources(price_related_resources)
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 _poll_response(self): """ 发送快递100 订阅请求,返回成功与否信息 """ # post中的param的json param_json_data = { 'Code': self.express_company_name_kdniao, 'Item': [ { 'No': str(self.express_number), 'Bk': str(self.express.id) }, ] } DataSign = self._encrypt(str(param_json_data)) params = { "RequestData": param_json_data, "EBusinessID": self.Business_id, "RequestType": "1005", "DataSign": DataSign, "DataType": "2" } #将数据处理为RequestData=xxx&DataType=xxx这种格式的 param_str = urllib.urlencode(params) verified_result = '' try: verified_result = post(KdniaoExpressConfig.req_url, param_str) watchdog.info( u"发送快递鸟 订阅请求 url: {},/n param_data: {}, /n response: {}". format(KdniaoExpressConfig.req_url, param_str, verified_result.decode('utf-8')), self.express_config.watchdog_type) except: watchdog.error( u'发送快递鸟 订阅请求 失败,url:{},data:{},原因:{}'.format( KdniaoExpressConfig.req_url, param_str, unicode_full_stack()), self.express_config.watchdog_type) return verified_result
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, ''