def process_payment_with_shared_info(request): """ 购买完成后进行分享链接的相关处理 如果请求信息中没有相应的分享链接信息,那么不进行任何处理,。 否则该分享链接带来的购买量+1 """ member_shared_url_info = get_followed_member_shared_url_info(request) if not member_shared_url_info: return try: from django.db import connection, transaction cursor = connection.cursor() cursor.execute('update member_shared_url_info set leadto_buy_count=leadto_buy_count+1 where id = %d' % member_shared_url_info.id) transaction.commit_unless_managed() #计算成功后清除请求中携带的分享链接信息 remove_shared_info(request) except: notify_message = u"更新分享链接带来的购买量失败,分享链接id:{}, cause:\n{}".format( member_shared_url_info.id, unicode_full_stack() ) watchdog_warning(notify_message)
def update_app_asyc(self, app): #先对比版本号看是否需要进行实际的更新操作 if not self.__app_has_new_version(app): #如果距离上次代码没有更新,那么不进行任何操作 warning_msg = u"app:{}没有最新版本".format(app.__unicode__()) watchdog_warning(warning_msg, app.owner.id) return app.update_status(CustomizedappStatus.UPDATING) #否则,需要先进行uninstall操作, 然后进行部署操作 #最后进行load操作 self.stop_app(app) app_full_path = self.__get_app_full_path(app) update_task_defer = app_tasks.remove_and_deploy_app(app, app_full_path) update_task_defer.add_callbacks( self.__update_callback, callback_args=(app, self.__get_latest_release_version(app)) ) self.__add_task_defer_err_callback( app, AppOps.UPDATE, update_task_defer ) return update_task_defer
def send_template_message_for_not_paid_order(webapp_owner_id, member_id, template_data): if _is_member_subscribed(member_id): # 会员已经取消关注 return True user_profile = UserProfile.objects.get(user_id=webapp_owner_id) user = user_profile.user if template_data and user_profile: mpuser_access_token = _get_mpuser_access_token(user) if mpuser_access_token: try: weixin_api = get_weixin_api(mpuser_access_token) social_account = member_model_api.get_social_account_by_member_id( member_id) if social_account and social_account.openid: template_data['touser'] = social_account.openid result = weixin_api.send_template_message(template_data, True) return True except: notify_message = u"发送模板消息异常, cause:\n{}".format( unicode_full_stack()) watchdog_warning(notify_message) return False else: return False return True
def send_order_template_message(webapp_id, order_id, send_point): user_profile = UserProfile.objects.get(webapp_id=webapp_id) user = user_profile.user template_message = get_template_message_by(user, send_point) from mall.models import Order order = Order.objects.get(id=order_id) if order and user_profile and template_message and template_message.template_id: mpuser_access_token = _get_mpuser_access_token(user) if mpuser_access_token: try: weixin_api = get_weixin_api(mpuser_access_token) message = _get_order_send_message_dict(user_profile, template_message, order, send_point) result = weixin_api.send_template_message(message, True) #_record_send_template_info(order, template_message.template_id, user) # if result.has_key('msg_id'): # UserSentMassMsgLog.create(user_profile.webapp_id, result['msg_id'], MESSAGE_TYPE_TEXT, content) return True except: notify_message = u"发送模板消息异常, cause:\n{}".format( unicode_full_stack()) watchdog_warning(notify_message) return False else: return False return True
def send_weixin_template_message(webapp_owner_id, member_id, model, send_point): if _is_member_subscribed(member_id): # 会员已经取消关注 return True user_profile = UserProfile.objects.get(user_id=webapp_owner_id) user = user_profile.user template_message = get_template_message_by(user_profile.user, send_point) if not template_message: return False template_message.send_point = send_point # return _get_send_message_dict(user_profile, member_id, model, template_message) if model and user_profile and template_message and template_message.template_id: mpuser_access_token = _get_mpuser_access_token(user) if mpuser_access_token: try: weixin_api = get_weixin_api(mpuser_access_token) message = _get_send_message_dict(user_profile, member_id, model, template_message) result = weixin_api.send_template_message(message, True) #_record_send_template_info(order, template_message.template_id, user) return True except: notify_message = u"发送模板消息异常, cause:\n{}".format( unicode_full_stack()) watchdog_warning(notify_message) return False else: return False return True
def get_templates(user): """ 从微信获取商家在公众号中配置的所有模板消息 @param owner_id: @return: """ mpuser_access_token = _get_mpuser_access_token(user) if mpuser_access_token: weixin_api = get_weixin_api(mpuser_access_token) try: result = weixin_api.get_all_template_messages(True) template_list = result['template_list'] user_update_list = [] for t in template_list: user_update_list.append( UserHasTemplateMessages( owner_id=user.id, template_id=t['template_id'], title=t['title'], primary_industry=t['primary_industry'], deputy_industry=t['deputy_industry'], content=t['content'])) UserHasTemplateMessages.objects(owner_id=user.id).delete() UserHasTemplateMessages.objects.insert(user_update_list) print result, 'asdfsgsf' except Exception, e: print e notify_message = u"获取模板列表异常, cause:\n{}".format( unicode_full_stack()) watchdog_warning(notify_message)
def serve(request, args): event_specific_data = args['event_specific_data'] order_order_id = event_specific_data['order_order_id'] #记录日志 mall_api.record_operation_log(order_order_id, u'客户', u'支付') mall_api.record_status_log(order_order_id, u'客户', mall_models.ORDER_STATUS_NOT, mall_models.ORDER_STATUS_PAYED_NOT_SHIP) webapp_id = request.user_profile.webapp_id webapp_user = request.webapp_user order = mall_models.Order.objects.get(order_id=order_order_id) #支付完成之后的webapp_user操作 try: webapp_user.complete_payment(request, order) except: alert_message = u"post_pay_order service: 调用webapp_user.complete_payment失败, cause:\n{}".format(unicode_full_stack()) if hasattr(request, 'user'): watchdog_alert(alert_message, type='WEB', user_id=str(request.user.id)) else: watchdog_alert(alert_message, type='WEB') #发送模板消息 try: template_message_api.send_order_template_message(order.webapp_id, order.id, 0) except: alert_message = u"post_pay_order service: 发送模板消息失败, cause:\n{}".format(unicode_full_stack()) watchdog_warning(alert_message) #todo zhaolei 需要优化,这样写不容易排错 from webapp.handlers import event_handler_util from utils import json_util event_data = {'order':json.dumps(order.to_dict(),cls=json_util.DateEncoder)} event_handler_util.handle(event_data, 'send_order_email')
def _read_file(file_url): data = [] error_rows = [] import csv file_path = os.path.join(settings.PROJECT_HOME, '..', file_url) with open(file_path) as csvfile: reader = csv.reader(csvfile, delimiter=':', quotechar='|') for row in reader: try: if len(row) > 0: item = dict() row = row[0].split(',') if not (len(row[0]) or len(row[1]) or len(row[2])): continue item['order_id'] = row[0].decode('gbk') item['express_company_name'] = row[1].decode('gbk') item['express_number'] = row[2].decode('gbk') data.append(item) except: error_rows.append(', '.join(row)) # print(', '.join(row)) csvfile.close() if len(error_rows) > 0: alert_message = u"bulk_shipments批量发货 读取文件错误的行, error_rows:{}".format( error_rows) watchdog_warning(alert_message) return data, error_rows
def _get_integral_strategy_by_webappid(self, webapp_id): try: return IntegralStrategySttings.objects.get(webapp_id=webapp_id) except: notify_message = u"根据webapp_id获取积分策略失败, webapp_id={}".format( webapp_id) watchdog_warning(notify_message) return None
def __clean_file(file_url): import os try: file_path = os.path.join(settings.PROJECT_HOME, '..', file_url) os.remove(file_path) except: alert_message = u"__clean_file cause:\n{}".format(unicode_full_stack()) watchdog_warning(alert_message)
def get_member_by_member_token(member_token): if member_token is None or len(member_token) == 0: return None try: return Member.objects.get(token=member_token) except: notify_message = u"根据token获取会员信息失败,可能会员已被删除,会员token={}, cause:\n{}".format( member_token, unicode_full_stack()) watchdog_warning(notify_message) return None
def send_message_to_member(rule, member_id): #给用户发优惠券提示 try: model_data = { "coupon_name": u'%s' % rule.name, "invalid_date": u'%s至%s有效' % (rule.start_date.strftime("%Y-%m-%d"), rule.end_date.strftime("%Y-%m-%d")) } template_message_api.send_weixin_template_message(rule.owner_id, member_id, model_data, template_message_model.COUPON_ARRIVAL_NOTIFY) except: alert_message = u"ship_order 发送模板消息失败, cause:\n{}".format(unicode_full_stack()) watchdog_warning(alert_message)
def get_material_news_info(material_id): try: material_id = int(material_id) news = list( News.objects.filter(material_id=material_id, is_active=True)) return news except: notify_message = u"渠道扫描异常 get_material_news_info error, cause:\n{}".format( unicode_full_stack()) watchdog_warning(notify_message) return None
def create_channel_qrcode_has_memeber(user_profile, member, ticket, is_new_member): try: channel_qrcodes = ChannelQrcodeSettings.objects.filter( ticket=ticket, owner_id=user_profile.user_id) print("channel_qrcodes: {}, ticket: {}, owner_id: {}".format( channel_qrcodes, ticket, user_profile.user_id)) if channel_qrcodes.count() > 0: channel_qrcode = channel_qrcodes[0] if channel_qrcode.bing_member_id == member.id: return if (is_new_member is False) and channel_qrcode.re_old_member == 0: return if ChannelQrcodeHasMember.objects.filter( channel_qrcode=channel_qrcode, member=member).count() == 0: ChannelQrcodeHasMember.objects.filter(member=member).delete() ChannelQrcodeHasMember.objects.create( channel_qrcode=channel_qrcode, member=member, is_new=is_new_member) else: return #如果没有会员扫该二维码的记录信息,创建记录并发奖,否则不进行操作 if ChannelQrcodeToMemberLog.objects.filter( channel_qrcode=channel_qrcode, member=member).count() == 0: if member: prize_info = PrizeInfo.from_json( channel_qrcode.award_prize_info) award(prize_info, member, CHANNEL_QRCODE) try: ChannelQrcodeToMemberLog.objects.create( channel_qrcode=channel_qrcode, member=member) except: pass try: if channel_qrcode.grade_id > 0: # updated by zhu tianqi,修改为会员等级高于目标等级时不降级,member_id->member Member.update_member_grade(member, channel_qrcode.grade_id) if channel_qrcode.tag_id > 0: MemberHasTag.add_tag_member_relation( member, [channel_qrcode.tag_id]) except: notify_message = u"渠道扫描异常update_member_grade error, cause:\n{}".format( unicode_full_stack()) watchdog_warning(notify_message) except: notify_message = u"渠道扫描异常create_channel_qrcode_has_memeber error, cause:\n{}".format( unicode_full_stack()) watchdog_warning(notify_message)
def contains_emojicons(unicode_or_utf8str_with_decoded_emojicons, is_hex_str=False): global ALL_EMOJICONS_UTF8_PRREFIX_SET if unicode_or_utf8str_with_decoded_emojicons is None: return False if isinstance(unicode_or_utf8str_with_decoded_emojicons, unicode): utf8str_with_decoded_emojicons = unicode_or_utf8str_with_decoded_emojicons.encode( 'utf-8') else: utf8str_with_decoded_emojicons = unicode_or_utf8str_with_decoded_emojicons __build_all_emojicons_utf8_prefix_set() if is_hex_str: hex_str = utf8str_with_decoded_emojicons #E59388681020 else: hex_str = byte_to_hex(utf8str_with_decoded_emojicons) #E59388681020 if len(utf8str_with_decoded_emojicons) <= 2: return False if len(hex_str) % 2 != 0: watchdog_warning(u"hex_str长度不正确,hex_str:{}".format(hex_str)) return False max_index = len(hex_str) part_start_index = 0 emojicon_utf8_part_index = -1 for index in xrange(0, max_index, 2): if emojicon_utf8_part_index == -1: maybe_prefix = hex_str[index:index + 2] else: maybe_prefix = hex_str[emojicon_utf8_part_index:index + 2] if not ALL_EMOJICONS_UTF8_PRREFIX_SET.has_key(maybe_prefix): if index > 2 and emojicon_utf8_part_index >= 0: maybe_emojiconutf8 = hex_str[emojicon_utf8_part_index:index] if UTF82EMOJIICONS.has_key(maybe_emojiconutf8): return True else: if emojicon_utf8_part_index == -1: emojicon_utf8_part_index = index if emojicon_utf8_part_index != -1: maybe_emojiconutf8 = hex_str[emojicon_utf8_part_index:] if UTF82EMOJIICONS.has_key(maybe_emojiconutf8): return True return False
def get_member_binded_social_account(member): if member is None: return None try: member_social_account_relation = MemberHasSocialAccount.objects.get( member=member) return member_social_account_relation.account except: notify_message = u"根据会员信息从数据库获取绑定的社会化账号信息失败,会员id:{}, cause:\n{}".format( member.id, unicode_full_stack()) watchdog_warning(notify_message) return None
def create_pay_feedback(request): wxpay_feedback = WxpayFeedback(request) feedback_post_data_soup = wxpay_feedback.get_feedback_data_soup() if feedback_post_data_soup is not None: try: pay_feedback_record = PayFeedback.create_by_post_data_soup(feedback_post_data_soup) warning_msg = u"微信支付维权, 维权id:{}".format(pay_feedback_record.id) except: warning_msg = u"创建微信支付维权记录失败,维权信息:\n{}, cause:\n{}\n请求信息:\n{}"\ .format(feedback_post_data_soup.__str__(), unicode_full_stack(), request.META) watchdog_warning(warning_msg) return HttpResponse("success")
def create_pay_warning_notify(request): wxpay_warning_notify = WxpayWarningNotify(request) notify_post_data_soup = wxpay_warning_notify.get_notify_data_soup() if notify_post_data_soup is not None: try: warning_notify_record = PayWarningNotify.create_by_post_data_soup(notify_post_data_soup) warning_msg = u"微信支付告警通知, 通知id:{}".format(warning_notify_record.id) except: warning_msg = u"创建微信支付告警通知记录失败,告警通知:\n{}, cause:\n{}"\ .format(notify_post_data_soup.__str__(), unicode_full_stack()) watchdog_warning(warning_msg) return HttpResponse("success")
def _get_binding_member_info_by_binding_member_id(binding_member_id): try: member_infos = ShengjingBindingMemberInfo.objects.filter( binding_id=binding_member_id) if member_infos.count() > 0: return member_infos[0] else: notify_message = u"根据binding_member_id没有获取盛景BindingMemberInfo会员信息,ShengjingBindingMemberId = {}".format( binding_member_id) watchdog_warning(notify_message) return None except: notify_message = u"根据binding_member_id获取盛景BindingMemberInfo会员信息,ShengjingBindingMemberId = {}, cause:\n{}".format( binding_member_id, unicode_full_stack()) watchdog_warning(notify_message) return None
def _get_binding_member_by_member_id(member_id): try: binding_members = ShengjingBindingMember.objects.filter( member_id=member_id) if binding_members.count() > 0: return binding_members[0] else: notify_message = u"根据member_id没有到一条获取盛景BindingMember会员,member_id={}".format( member_id) watchdog_warning(notify_message) return None except: notify_message = u"根据member_id获取盛景BindingMember会员信息失败,member_id={}, cause:\n{}".format( member_id, unicode_full_stack()) watchdog_warning(notify_message) return None
def send_message(self): try: message = self._get_message_dict() if message is None: return False, u"message dict错误" mpuser_access_token = self._get_mpuser_access_token(self.user) weixin_api = get_weixin_api(mpuser_access_token) result = weixin_api.send_template_message(message, True) return True, result except: notify_message = u"shengjing发送模板消息异常, cause:\n{}".format( unicode_full_stack()) watchdog_warning(notify_message, self.shengjing_params.WATCHDOG_TYPE_SHENGJING) return False, unicode_full_stack()
def get_social_account(request): social_account = get_request_social_account(request) if social_account: return social_account social_account_session_key = request.COOKIES.get( member_settings.SOCIAL_ACCOUNT_TOKEN_SESSION_KEY, None) if social_account_session_key: try: return SocialAccount.objects.get(token=social_account_session_key) except: notify_message = u"从数据库读取社会化账号信息失败,社交账户信息:('token':{}), cause:\n{}".format( social_account_session_key, unicode_full_stack()) watchdog_warning(notify_message) return None else: return None
def _update_mpuser_access_token(access_token): assert (access_token) new_token_info = _get_new_token_info(access_token) if None == new_token_info: return if not new_token_info.has_key(ACCESS_TOKEN_ATTR): watchdog_warning( u"failed to update access token for user({}), response:\n{}". format(access_token.mpuser.username, json.dumps(new_token_info))) else: new_access_token = new_token_info[ACCESS_TOKEN_ATTR].strip() expires_span = new_token_info[ACCESS_TOKEN_EXPIRES_IN_ATTR] _update_access_token_record(access_token, new_access_token, expires_span)
def _send_email(user, emails, content_described, content): """ 发送邮件 :param user: :param emails: :param content_described: :param content: :return: """ try: for email in emails.split('|'): if email.find('@') > -1: sendmail(email, content_described, content) except: notify_message = u"发送邮件失败user_id({}), cause:\n{}".format( user.id, unicode_full_stack()) watchdog_warning(notify_message)
def log_js_error(request): content = request.POST.get('content', '') message = request.POST.get('message', '') user_agent = request.META['HTTP_USER_AGENT'] try: user_id = request.user.id except: user_id = 0 try: member_info = u'\nrequest.member.id = {}\n\n'.format(request.member.id) except: member_info = u'' watchdog_warning( u"***** Client Javascript Exception (%s) *****\n%s[UserAgent]: %s\n%s" % (message, member_info, user_agent, content), 'JS', str(user_id)) return create_response(200).get_response()
def create_vote(request): created_vote = None try: vote_options_json_str = request.POST["vote_options"] vote_options = decode_json_str(vote_options_json_str) is_non_member = int(request.POST.get("is_non_member", 0)) created_vote = Vote.objects.create( owner=request.user, name=request.POST["name"].strip(), detail=request.POST["detail"].strip(), award_prize_info=request.POST['prize_info'].strip(), is_non_member=is_non_member, show_style=int(request.POST.get('show_style', '1')), ) for vote_option in vote_options: vote_option = VoteOption.objects.create( vote_id=created_vote.id, name=vote_option['name'].strip(), pic_url=vote_option.get('pic_url', ''), ) response = create_response(200) response.data.vote_id = created_vote.id except: alert_msg = u"创建投票信息失败, cause:\n {}".format(unicode_full_stack()) watchdog_error(alert_msg, user_id=request.user.id) #创建投票选项失败,需要把创建成功的投票选项和投票全部删除 if created_vote is not None: try: created_vote.delete() except: alert_msg = u"删除投票信息失败, cause:\n {}".format( unicode_full_stack()) watchdog_warning(alert_msg, user_id=request.user.id) response = create_response(500) response.innerErrMsg = unicode_full_stack() return response.get_response()
def send_mass_text_message_with_openid_list(user_profile, openid_list, content, log_id=None, group_id=0): user = user_profile.user if len(openid_list) > 0 and content != None and content != '' and user: mpuser_access_token = _get_mpuser_access_token(user) if mpuser_access_token: mesage = TextMessage(openid_list, content) weixin_api = get_weixin_api(mpuser_access_token) if log_id: sent_log = UserSentMassMsgLog.objects.filter(id=log_id).first() else: sent_log = UserSentMassMsgLog.create(user_profile.webapp_id, '', MESSAGE_TYPE_TEXT, content, group_id) try: result = weixin_api.send_mass_message(mesage, True) #增加群发任务失败处理 sent_log.msg_id = result['msg_id'] sent_log.message_type = MESSAGE_TYPE_TEXT sent_log.message_content = content if result['errcode'] != 0: sent_log.status = 'send fail code: %d' % result['errcode'] if result['errcode'] == -1: #微信系统繁忙,则稍后重试 sent_log.save() return False sent_log.save() return True except: notify_message = u"群发文本消息异常send_mass_message, cause:\n{}".format( unicode_full_stack()) print notify_message watchdog_warning(notify_message) sent_log.status = 'send failed' sent_log.save() return False else: return False return True
def delete_mass_message(user_profile, msg_id): user = user_profile.user if msg_id != None and msg_id != '' and user: mpuser_access_token = _get_mpuser_access_token(user) if mpuser_access_token: weixin_api = get_weixin_api(mpuser_access_token) try: result = weixin_api.delete_mass_message(msg_id.strip()) if result.has_key('errmsg') and result['errmsg'] == 'ok': UserSentMassMsgLog.objects.filter( webapp_id=user_profile.webapp_id, msg_id=msg_id).update(status='delete') return True except: notify_message = u"删除群发消息异常delete_mass_message, cause:\n{}".format( unicode_full_stack()) print notify_message watchdog_warning(notify_message) return False return False
def api_post(request): """更新商品排序 Args: category_id: product_id: position: """ try: category_id = request.POST.get('category_id') product_id = request.POST.get('product_id') position = request.POST.get('position') category_has_product = mall_models.CategoryHasProduct.objects.get( category_id=category_id, product_id=product_id) category_has_product.move_to_position(position) response = create_response(200) return response.get_response() except: watchdog_warning(u"更新商品分组商品排序失败, cause:\n{}".format( unicode_full_stack())) response = create_response(500) return response.get_response()
def create_new_channel_qrcode_has_memeber(user_profile, member, ticket, is_new_member): try: print '==========999999999999==========' new_channel_qrcodes = MemberChannelQrcode.objects.filter( ticket=ticket, owner_id=user_profile.user_id) if new_channel_qrcodes.count() > 0: new_channel_qrcode = new_channel_qrcodes[0] #用户自己扫自己的码直接返回 if new_channel_qrcode.member_id == member.id: return qrcode_award = MemberChannelQrcodeAwardContent.objects.get( owner_id=user_profile.user_id) if MemberChannelQrcodeHasMember.objects.filter( member_channel_qrcode=new_channel_qrcode, member=member).count() == 0: MemberChannelQrcodeHasMember.objects.create( member_channel_qrcode=new_channel_qrcode, member=member, is_new=is_new_member) else: return if member: _add_award_to_member(user_profile, qrcode_award.scanner_award_type, qrcode_award.scanner_award_content, member, CHANNEL_QRCODE) _add_award_to_member(user_profile, qrcode_award.share_award_type, qrcode_award.share_award_content, new_channel_qrcode.member, BRING_NEW_CUSTOMER_VIA_QRCODE) except: notify_message = u"渠道扫描异常create_channel_qrcode_has_memeber error, cause:\n{}".format( unicode_full_stack()) watchdog_warning(notify_message)