def search_message(): open_list = get_no_sign() for openid in open_list: user = UserInfo.objects.get(wechat_id=openid) goal = RunningGoal.objects.get(user_id=user.user_id) url = "http://wechat.onmytarget.cn/goal/{}?activity_type=1".format( goal.goal_id) goal_type = goal.goal_type # 目标距离 goal_distance = goal.goal_distance # 单日距离 kilos_day = goal.kilos_day # 目标天数 goal_day = goal.goal_day if goal_type == 1: detail = "在{}天内,每天完成{}公里".format(goal_day, kilos_day) category = "跑步日常模式" else: detail = "在{}天内,一共完成{}公里".format(goal_day, goal_distance) category = "跑步自由模式" end_time = (goal.start_time + timedelta(days=goal_day)).strftime("%m月%d日") data = initiative(openid, url, detail, category) do_push(data)
def delete_read_goal(request): try: user = request.session['user'] if request.POST: activity_type = request.POST['goal_type'] goal_id = request.POST['goal'] if not all([activity_type, goal_id]): return JsonResponse({"status": 403}) print("参数完整") read = ReadingGoal.objects.get(goal_id=goal_id) UserRecord.objects.finish_goal(user=user) # 更新用户的押金 print("开始更新押金") UserInfo.objects.update_deposit( user_id=user.user_id, pay_delta=-(read.guaranty - read.bonus)) print("更新成功") UserInfo.objects.read_handle(user_id=user.user_id, bonus=read.bonus) print("更新用户的余额成功") try: print("开始保存用户的数据") Read_Finish_Save.objects.save_finish(goal_id=goal_id) import time time.sleep(1) except Exception as e: print("记录用户的结束保存信息失败", e) try: ReadingPunchRecord.objects.filter(goal_id=goal_id).delete() ReadingGoal.objects.filter(goal_id=goal_id).delete() except Exception as e: print("删除读书活动失败", e) try: read.update_activity_person() act = Activity.objects.get( activity_id="fac28454e818458f86639e7d40554597") act.bonus_all -= read.guaranty act.save() except Exception as e: print("更新失败", e) # 更新用户的余额 try: url = 'http://wechat.onmytarget.cn/user/index' activate = "阅读" finish_time = timezone.now().strftime('%Y-%m-%d %H:%M') earn_money = str(read.bonus) earn_time = timezone.now().strftime('%Y-%m-%d %H:%M') # 发送模板提醒 data = finish_tem(user.wechat_id, url, activate, finish_time, earn_money, earn_time, str(user.balance)) do_push(data) return JsonResponse({'status': 200}) except Exception as e: print("发送读书模板失败", e) except Exception as e: print("读书结束失败", e) return JsonResponse({"status": 403})
def running_report_handler(request): if request.POST: punch = request.POST['punch'] user = request.session['user'] print("用户{}举报他人".format(user.user_id)) openid = user.wechat_id content = "被举报用户发布了虚假信息" nickname = UserInfo.objects.get(user_id=user.user_id).nickname RunningPunchRecord.objects.report_punch(user_id=user.user_id, punch_id=punch) url = 'http://wechat.onmytarget.cn/' data = report_tem(openid, url, content, nickname) do_push(data) return JsonResponse({'status': 200}) else: return HttpResponseNotFound
def save_openid(): try: obj = search_nosign() for goal in obj: # 判断该用户昨天是否有打卡记录 # 说明不是第一天 if not goal.exist_punch_last_day(): user = goal.user_id openid = UserInfo.objects.get(user_id=user).wechat_id url = 'http://wechat.onmytarget.cn/user/index' goal_day = goal.goal_day kilos_day = goal.kilos_day first = "跑步" target = "在{}天,每天完成{}公里".format(goal_day, kilos_day) nosignday = (timezone.now() - timedelta(days=1)).strftime("%Y-%m-%d") guaranty = goal.guaranty down_payment = goal.down_payment if goal.goal_type == 1: # 每次扣多少钱 money = goal.average # 剩下应该扣多少次 # 当是日常模式的时候 times = int(down_payment) / int(money) if int(guaranty) != 0: deduct = " 保证金¥{}".format(guaranty) else: deduct = " 底金¥{}".format(down_payment / int(times)) surplus = "底金¥{}X{}次".format(money, int(times)) data = field_tem(openid, url, first, target, nosignday, deduct, surplus) if goal.is_first_day: print("first day do nothing ") return else: do_push(data) return JsonResponse({"status": 200}) else: return except Exception as e: pass
def send_attention(): try: #今天的日期是 time_now = timezone.now().strftime("%Y-%m-%d") #查询出所有正在参与的用户的openid sleep = SleepingGoal.objects.filter(status="ACTIVE") if sleep: #找出正在参与且早上没有打卡的用户 for user in sleep: punch = SleepingPunchRecord.objects.filter( user_id=user.user_id, punch_time=time_now) if user.sleep_type == 0: #此时分为昨天打了卡的情况与昨天睡前没有打卡记录的情况 #如果昨天睡前打了卡 if punch: #获取未打卡用户的openid,goaltype for msg in punch.filter(get_up_time__isnull=True): openid = UserInfo.objects.get( user_id=msg.user_id).wechat_id data = morning_attention_temp(openid, "睡眠模式") do_push(data) time.sleep(2) else: #昨天睡前没有打卡,因为今天没有查询到打卡记录 openid = UserInfo.objects.get( user_id=user.user_id).wechat_id data = morning_attention_temp(openid, "睡眠模式") do_push(data) time.sleep(2) elif user.sleep_type == 1: #此时是早起模式 if not punch: #说明没有打卡记录 openid = UserInfo.objects.get( user_id=user.user_id).wechat_id data = morning_attention_temp(openid, "早起模式") do_push(data) time.sleep(2) else: #说明有记录,早起模式的记录是当天创建的,所以一定是打了卡 pass return JsonResponse({"status": 200}) except Exception as e: pass
def order_confirm(request): user = request.session["user"] print("开始确认订单{}".format(user.user_id)) if request.POST: try: response_dict = request.POST order_id = response_dict.get("order_id") goal_id = response_dict.get("goal_id", " ") activity_type = response_dict.get("activity_type", "") print(type(activity_type), activity_type) if activity_type == "1": try: order = UserOrder.objects.filter(order_id=order_id)[0] order.owner_name = response_dict.get("name") order.owner_phone = response_dict.get("phone") order.address = response_dict.get("address") order.area = response_dict.get("area") order.remarks = response_dict.get("remarks", " ") order.is_no_confirm = 1 order.save() order_time = timezone.now().strftime("%Y-%m-%d %H:%M") content = order.order_name user_name = response_dict.get("name") user_address = response_dict.get("address") url = 'http://wechat.onmytarget.cn/user/index' data = order_confirm_temp(user.wechat_id, url, order_time, content, user_name, order.area + " " + user_address) do_push(data) print("发送确认订单信息成功") return JsonResponse({"status": 200}) except Exception as e: print(e) elif activity_type == "2": if goal_id: order = UserOrder.objects.filter(order_id=order_id, goal_id=goal_id)[0] else: order = UserOrder.objects.filter(order_id=order_id)[0] order.owner_name = response_dict.get("name") order.owner_phone = response_dict.get("phone") order.address = response_dict.get("address") order.area = response_dict.get("area") order.remarks = response_dict.get("remarks", " ") print("开始修改数据") order.is_no_confirm = 1 print("修改成功") order.save() print("保存成功", order.is_no_confirm) order_time = timezone.now().strftime("%Y-%m-%d %H:%M") content = order.order_name user_name = response_dict.get("name") user_address = response_dict.get("address") url = 'http://wechat.onmytarget.cn/user/index' data = order_confirm_temp(user.wechat_id, url, order_time, content, user_name, order.area + " " + user_address) do_push(data) print("发送确认订单信息成功") return JsonResponse({"status": 200}) except Exception as e: print(e) return JsonResponse({"status": 201}) # 确认订单成功,开始发送信息 else: return JsonResponse({"status": 201})
def delete_run_goal(request): try: user = request.session['user'] if request.POST: # 删除当前的目标活动并退还钱 activity_type = request.POST['goal_type'] goal_id = request.POST['goal'] goal = RunningGoal.objects.get(goal_id=goal_id) try: # 增加用户的完成次数 UserRecord.objects.finish_goal(user=user) # 用户触发,如果挑战成功则删除目标,退还押金 # 判断用户是否挑战成功 # 更新用户的押金 UserInfo.objects.update_deposit( user_id=user.user_id, pay_delta=-(goal.guaranty + goal.down_payment)) # 查询用户的额外收益 extra = UserInfo.objects.get(user_id=user.user_id) # 查询用户当前的额外收益 price = decimal.Decimal(goal.guaranty) + decimal.Decimal( goal.down_payment) + decimal.Decimal( goal.bonus) + decimal.Decimal(goal.extra_earn) # 将用户获取的收益存入余额 UserInfo.objects.save_balance( user_id=user.user_id, price=price, bonus=decimal.Decimal(goal.bonus), extra_earn=decimal.Decimal(goal.extra_earn)) except Exception as e: print(e) # 用户结算之后就将用户的所有信息放进记录存储表中 try: print("开始保存用户的数据") Running_Finish_Save.objects.save_finish(goal_id=goal_id) import time time.sleep(1) except Exception as e: print("记录用户的结束保存信息失败", e) # 删除用户的目标 RunningGoal.objects.delete_goal(goal_id) # 用户的目标结束之后,更新参加人数跟奖金池,系数 try: goal.update_activity_person() act = Activity.objects.get( activity_id="32f2a8dbe89d43c7b9ecfea19947b057") act.bonus_all -= (goal.guaranty + goal.down_payment) act.save() except Exception as e: print("更新失败", e) url = 'http://wechat.onmytarget.cn/user/index' activate = "跑步" finish_time = timezone.now().strftime('%Y-%m-%d %H:%M') earn_money = str(goal.guaranty + goal.down_payment) # money = Running_Finish_Save.objects.get(user_id=user.user_id,settle_time=timezone.now().strftime('%Y-%m-%d')).bonus money = Running_Finish_Save.objects.filter( user_id=user.user_id, settle_time=timezone.now().strftime('%Y-%m-%d')) if money: earn_money = money[0].bonus earn_time = ( goal.start_time + timedelta(days=goal.goal_day)).strftime('%Y-%m-%d %H:%M') balance = str(UserInfo.objects.get(user_id=user.user_id).balance) # 发送模板提醒 data = finish_tem(user.wechat_id, url, activate, finish_time, str(earn_money), earn_time, balance) do_push(data) return JsonResponse({'status': 200}) else: return JsonResponse({'status': 403}) except Exception: return JsonResponse({"status": 403})
def wechat_pay_back(request): if settings.DEBUG: goal_id = request.POST['goal'] user = request.session['user'] transaction_id = str(uuid.uuid4()) trade_data = { "device_info": "DEBUG", "openid": "o0jd6wk8OK77nbVqPNLKG-2urQxQ", "trade_type": "JSAPI", "trade_state": "SUCCESS", "bank_type": "DEBUG", "total_fee": 1, "cash_fee": 1, "fee_type": "CNY", "transaction_id": transaction_id, "out_trade_no": uuid.uuid4(), "time_end": 23456, "result_code": "SUCCESS" } UserTrade.objects.create_trade(goal_id=goal_id, trade_data=trade_data) # 更新用户的押金信息 UserInfo.objects.update_deposit(user_id=user.user_id, pay_delta=float(trade_data['total_fee']) / 100) # 当支付成功后,将attach中的goal取出来, 设其为活跃状态 from on.activities.base import Goal sub_models = get_son_models(Goal) for sub_model_key in sub_models: sub_model = sub_models[sub_model_key] goal = sub_model.objects.filter(user_id=user.user_id).filter(goal_id=goal_id).filter(status='PENDING') if goal: # 如果找到了用户该类型的goal,将其设置为活跃状态 goal = goal.first() goal.status = 'ACTIVE' goal.save() # 更新对应活动的奖金池与参与人数 goal.update_activity(user_id=user.user_id) # 如果是阅读活动,则需要在支付完成后新建一个发货订单 if sub_model_key == ReadingGoal.__name__: UserOrder.objects.create_reading_goal_order(user_id=user.user_id, order_name=goal.book_name, order_money=goal.price, order_image=goal.imageurl) return JsonResponse({'status': 200}) # 微信支付回调接口,此时支付成功,可以将流水记录写入数据库 else: try: res = payClient.parse_payment_result(request.body) xml_str = "<xml><return_code><![CDATA[{0}]]></return_code></xml>".format(res['result_code']) except Exception as e: logger.error(e) return HttpResponseNotFound else: try: user = UserInfo.objects.get_user_by_openid(res['openid']) goal_id = res['attach'] print(goal_id, type(goal_id), "订单里面查出来的id") # 把支付的结果写入交易表中 if not UserTrade.objects.exist_trade(res['transaction_id']): UserTrade.objects.create_trade(goal_id=goal_id, trade_data=res) # 当支付成功后,将attach中的goal取出来, 设其为活跃状态 from on.activities.base import Goal sub_models = get_son_models(Goal) for sub_model_key in sub_models: sub_model = sub_models[sub_model_key] goal = sub_model.objects.filter(user_id=user.user_id, goal_id=goal_id, status='PENDING') # TODO if goal: goal = goal.first() print("如果找到了用户该类型的goal,将其设置为活跃状态") try: print("将用户的状态设置为活跃") sub_model.objects.filter(user_id=user.user_id, goal_id=goal_id, status='PENDING').update(status="ACTIVE") print("设置成功") except Exception as e: print("状态修改失败", e) # 更新用户的余额信息 print("更新用户的余额信息") try: user = UserInfo.objects.get(user_id=user.user_id) user.balance -= decimal.Decimal((goal.deserve_price - goal.reality_price)) user.save() except Exception as e: print(e) # # 更新用户的押金信息 deposit = goal.guaranty + goal.down_payment UserInfo.objects.update_deposit(user_id=user.user_id, pay_delta=decimal.Decimal(deposit)) # 更新对应活动的奖金池与参与人数 if goal.activity_type == "1": goal.update_activity(user_id=user.user_id) # activate = Activity.objects.get(activity_type=1) # activate.bonus_all += decimal.Decimal(10) # activate.save() try: income_handle(res["openid"], goal.activity_type) except Exception as e: print(e) # 构造模板 openid = res["openid"] goal_content = "恭喜你成功报名参加活动" activate = "跑步活动" # date_time = time.strftime('%Y年%m月%d日', time.localtime(time.time())) start_time = timezone.now().strftime('%m月%d日') end_time = (timezone.now() + timedelta(days=goal.goal_day)).strftime('%m月%d日') date_time = "{}-{}(±1天)".format(start_time, end_time) url = 'http://wechat.onmytarget.cn/' data = send_tem(openid, url, goal_content, activate, date_time) print("用户{}支付成功,当前用户id:{}".format(user.nickname, user.user_id)) print("开始发送模板") do_push(data) # 支付成功,删除用户未支付成的所有记录 try: failed = RunningGoal.objects.filter(user_id=user.user_id, status="PENDING") failed.delete() except Exception as e: print(e, '删除记录未成功') if goal.activity_type == "2": try: active = Activity.objects.get(activity_id='fac28454e818458f86639e7d40554597') active.active_participants += 1 active.save() with connection.cursor() as cursor: resp = cursor.execute( """DELETE FROM on_readinggoal WHERE user_id=%s AND `status`='PENDING'""", [user.user_id]) except Exception as e: print("删除订单中的pending失败,{}".format(e)) print("支付成功,开始创建订单") try: print(goal.goal_id, goal.goal_type, goal.price) read_goal = ReadingGoal.objects.get(goal_id=goal_id) UserOrder.objects.create_reading_goal_order(user_id=user.user_id, order_name=read_goal.book_name, order_money=read_goal.price, order_image=read_goal.imageurl, goal_id=read_goal.goal_id ) print("订单创建成功") except Exception as e: print(e, "订单未创建成功") try: income_handle(res["openid"], goal.activity_type) except Exception as e: print(e) if goal.activity_type == "0": try: # 更新了奖金池的总系数 goal.update_activity(user_id=user.user_id) activity = Activity.objects.get(activity_id="a5a0206fb2aa4e8995263c7ab0afa1b5") activity.active_participants += 1 activity.save() with connection.cursor() as cursor: resp = cursor.execute( """DELETE FROM on_sleepinggoal WHERE user_id=%s AND `status`='PENDING'""", [user.user_id]) print(resp) try: income_handle(res["openid"], goal.activity_type) except Exception as e: print(e) openid = res["openid"] goal_content = "恭喜你成功报名参加活动" activate = "作息" # date_time = time.strftime('%Y年%m月%d日', time.localtime(time.time())) start_time = timezone.now().strftime('%m月%d日') end_time = (timezone.now() + timedelta(days=goal.goal_day)).strftime('%m月%d日') if goal.goal_day <= 21: date_time = "{}-{}".format(start_time, end_time) else: date_time = "无限期" url = 'http://wechat.onmytarget.cn/' data = send_tem(openid, url, goal_content, activate, date_time) print("用户{}支付成功,当前用户id:{}".format(user.nickname, user.user_id)) print("开始发送模板") do_push(data) except Exception as e: print(e) if goal.activity_type == "3": pass else: pass break except Exception as e: logger.error(e) return HttpResponse(xml_str)
def transfer_to_person(request): try: user = request.session['user'] print("当前用户的user_id:{}".format(user.user_id)) if settings.DEBUG: price = 100 else: # 从前端传过来的提现金额 price = int(100 * decimal.Decimal(request.POST['price'])) balance = UserInfo.objects.get(user_id=user.user_id).balance assert price == int(100 * balance) if price < 100: # 201 错误码代表最小提取1.00元 return JsonResponse({'status': 201}) else: if settings.DEBUG: data = payClient.transfer.transfer(user_id='o0jd6wk8OK77nbVqPNLKG-2urQxQ', amount=100, desc="用户{0}发起提现".format(user.user_id), check_name="NO_CHECK") else: print("用户{}开始发起提现".format(user.user_id)) # 检查用户现在的余额是多少 user_balance_now = UserInfo.objects.get(user_id=user.user_id) # 提现金额必须等于现在的金额,否则无法提现 print("用户现在的余额是多少{}".format(user_balance_now.balance)) data = payClient.transfer.transfer(user_id=user.wechat_id, amount=price, desc="用户{0}发起提现".format(user.user_id), check_name="NO_CHECK") print("用户开始发起提现,提款成功的状态码{}".format(data['result_code'])) user_balance_now.balance = 0 user_balance_now.save() print("开始判断提款状态吗") if data['result_code'] == 'SUCCESS': print(data['result_code'], '提款成功的状态码') print(user.wechat_id, price, data, user.user_id, "每一项数据") try: newUserWithdraw.objects.create( user_id=user.user_id, openid=user.wechat_id, amount=price, partner_trade_no=data["partner_trade_no"], payment_no=data["payment_no"] ) except Exception as e: print("创建体现记录失败", e) # 更新用户的余额 user_info = UserInfo.objects.get(user_id=user.user_id) user_info.balance = 0 user_info.save() print(user_info.balance, "测试现在用户的余额") price = "%.2f" % (price / 100) print(price, "用户现在的金额") # 查询当前余额 withdraw_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) url = 'http://wechat.onmytarget.cn/' # 构造模板发送模板 data = Withdraw_temp(user.wechat_id, url, price, 0, withdraw_time) do_push(data) return JsonResponse({'status': 200}) else: print(data['result_code'], '若是提款失败的状态码') logger.error("用户{0}发起提现".format(user.user_id)) logger.error(data) # 说明付款失败,联系客服处理 return JsonResponse({'status': 401}) except AssertionError as a: print("表示用户现在提现的金额与余额不匹配") return JsonResponse({'status': 403}) except Exception as e: logger.error(str(e)) return JsonResponse({'status': 401})
def delete_goal(request): try: user = request.session['user'] if request.method == "POST": # 删除当前的目标活动并退还钱 activity_type = request.POST['goal_type'] goal_id = request.POST['goal'] delete_map = { RunningGoal.get_activity(): RunningGoal, ReadingGoal.get_activity(): ReadingGoal, SleepingGoal.get_activity(): SleepingGoal } for goal_type in delete_map.keys(): if activity_type == goal_type: goal_class = delete_map[goal_type] goal = goal_class.objects.get(goal_id=goal_id) # 增加用户的完成次数 # if goal.status == "SUCCESS": UserRecord.objects.finish_goal(user=user) # 用户触发,如果挑战成功则删除目标,退还押金 # 判断用户是否挑战成功 # if goal.refund_to_user(user.wechat_id): # 更新用户的押金 UserInfo.objects.update_deposit( user_id=user.user_id, pay_delta=-(goal.guaranty + goal.down_payment)) # 更新目前的奖金池 obj = Activity.objects.get( activity_type=goal.activity_type) obj.bonus_all -= (goal.guaranty + goal.down_payment) obj.save() # 获取邀请了多少好友 num = UserInvite.objects.filter( user_id=request.session["user"].user_id).count() # 用户获取收益的百分比 add_up = num * 0.5 + 1 if add_up >= 10: add_up = 10 # 查询用户的额外收益 extra = UserInfo.objects.get(user_id=user.user_id) # 查询用户当前的额外收益 Run = RunningGoal.objects.get(user_id=user.user_id) extra_earn = Run.extra_earn print(extra_earn) price = decimal.Decimal(Run.guaranty) + decimal.Decimal( Run.down_payment) + decimal.Decimal( Run.bonus * decimal.Decimal(add_up)) + decimal.Decimal( extra.extra_money) # 将用户获取的收益存入余额 # 查询现在用户的保证金跟底金 UserInfo.objects.save_balance(user_id=user.user_id, price=price) # openid = str(UserInfo.objects.get(user_id=user.user_id).wechat_id) # 删除用户的目标 goal_class.objects.delete_goal(goal_id) openid = user.wechat_id url = 'http://wechat.onmytarget.cn/user/index' activate = "跑步" finish_time = timezone.now().strftime('%Y-%m-%d %H:%M') earn_money = str(goal.guaranty + goal.down_payment) earn_time = (goal.start_time + timedelta( days=goal.goal_day)).strftime('%Y-%m-%d %H:%M') balance = str( UserInfo.objects.get(user_id=user.user_id).balance) # 发送模板提醒 data = finish_tem(openid, url, activate, finish_time, earn_money, earn_time, balance) do_push(data) return JsonResponse({'status': 200}) ''' if activity_type == RunningGoal.get_activity(): # 获取相应的goal,准备退款给用户 goal = RunningGoal.objects.get(goal_id=goal_id) # 增加用户的完成次数 if goal.status == "SUCCESS": UserRecord.objects.finish_goal(user=user) if goal.refund_to_user(user.wechat_id): RunningGoal.objects.delete_goal(goal_id) return JsonResponse({'status': 200}) else: return JsonResponse({'status':403}) elif activity_type == SleepingGoal.get_activity(): goal = SleepingGoal.objects.get(goal_id=goal_id) UserRecord.objects.finish_goal(user=user) if goal.refund_to_user(user.wechat_id): SleepingGoal.objects.delete_goal(goal_id) return JsonResponse({'status': 200}) else: return JsonResponse({'status': 403}) elif activity_type == ReadingGoal.get_activity(): goal = ReadingGoal.objects.get(goal_id=goal_id) UserRecord.objects.finish_goal(user=user) if goal.refund_to_user(user.wechat_id): ReadingGoal.objects.delete_goal(goal_id) return JsonResponse({'status': 200}) else: return JsonResponse({'status': 403}) ''' else: return JsonResponse({'status': 404}) except Exception: return HttpResponseNotFound else: return JsonResponse({'status': 200})
def wechat_pay_back(request): if settings.DEBUG: goal_id = request.POST['goal'] user = request.session['user'] transaction_id = str(uuid.uuid4()) trade_data = { "device_info": "DEBUG", "openid": "o0jd6wk8OK77nbVqPNLKG-2urQxQ", "trade_type": "JSAPI", "trade_state": "SUCCESS", "bank_type": "DEBUG", "total_fee": 1, "cash_fee": 1, "fee_type": "CNY", "transaction_id": transaction_id, "out_trade_no": uuid.uuid4(), "time_end": 23456, "result_code": "SUCCESS" } UserTrade.objects.create_trade(goal_id=goal_id, trade_data=trade_data) # 更新用户的押金信息 UserInfo.objects.update_deposit(user_id=user.user_id, pay_delta=float(trade_data['total_fee']) / 100) # 当支付成功后,将attach中的goal取出来, 设其为活跃状态 from on.activities.base import Goal sub_models = get_son_models(Goal) for sub_model_key in sub_models: sub_model = sub_models[sub_model_key] goal = sub_model.objects.filter(user_id=user.user_id).filter(goal_id=goal_id).filter(status='PENDING') if goal: # 如果找到了用户该类型的goal,将其设置为活跃状态 goal = goal.first() goal.status = 'ACTIVE' goal.save() # 更新对应活动的奖金池与参与人数 goal.update_activity(user_id=user.user_id) # 如果是阅读活动,则需要在支付完成后新建一个发货订单 if sub_model_key == ReadingGoal.__name__: UserOrder.objects.create_reading_goal_order(user_id=user.user_id, order_name=goal.book_name, order_money=goal.price, order_image=goal.imageurl) return JsonResponse({'status': 200}) # 微信支付回调接口,此时支付成功,可以将流水记录写入数据库 else: try: res = payClient.parse_payment_result(request.body) xml_str = "<xml><return_code><![CDATA[{0}]]></return_code></xml>".format(res['result_code']) except Exception as e: logger.error(e) return HttpResponseNotFound else: try: user = UserInfo.objects.get_user_by_openid(res['openid']) goal_id = res['attach'] # 把支付的结果写入交易表中 if not UserTrade.objects.exist_trade(res['transaction_id']): UserTrade.objects.create_trade(goal_id=goal_id, trade_data=res) # 当支付成功后,将attach中的goal取出来, 设其为活跃状态 from on.activities.base import Goal sub_models = get_son_models(Goal) for sub_model_key in sub_models: sub_model = sub_models[sub_model_key] goal = sub_model.objects.filter(user_id=user.user_id).filter(goal_id=goal_id).filter( status='PENDING') # TODO if goal: # 如果找到了用户该类型的goal,将其设置为活跃状态 goal = goal.first() goal.status = 'ACTIVE' goal.save() # 更新用户的余额信息 user = UserInfo.objects.get(user_id=user.user_id) user.balance -= decimal.Decimal((goal.deserve_price - goal.reality_price)) user.save() # # 更新用户的押金信息 deposit = goal.guaranty + goal.down_payment UserInfo.objects.update_deposit(user_id=user.user_id, pay_delta=float(deposit)) # 更新对应活动的奖金池与参与人数 goal.update_activity(user_id=user.user_id) obj = RunningGoal.objects.get(user_id="100101") obj.activate_deposit += decimal.Decimal(10) obj.down_payment += decimal.Decimal(10) obj.save() activate = Activity.objects.get(activity_type=1) activate.bonus_all += decimal.Decimal(10) activate.save() # 构造模板 openid = res["openid"] goal_content = "恭喜你成功报名参加活动" activate = "跑步活动" # date_time = time.strftime('%Y年%m月%d日', time.localtime(time.time())) start_time = timezone.now().strftime('%m月%d日') end_time = (timezone.now() + timedelta(days=goal.goal_day)).strftime('%m月%d日') date_time = "{}-{}(±1天)".format(start_time, end_time) url = 'http://wechat.onmytarget.cn/' data = send_tem(openid, url, goal_content, activate, date_time) print("用户{}支付成功,当前用户id:{}".format(user.nickname,user.user_id)) print("开始发送模板") do_push(data) # 如果是阅读活动,则需要在支付完成后新建一个发货订单 if sub_model_key == ReadingGoal.__name__: UserOrder.objects.create_reading_goal_order(user_id=user.user_id, order_name=goal.book_name, order_money=goal.price, order_image=goal.imageurl) break except Exception as e: logger.error(e) # pass return HttpResponse(xml_str)
def transfer_to_person(request): try: user = request.session['user'] if settings.DEBUG: price = 100 else: #从前端传过来的提现金额 price = int(100 * float(request.POST['price'])) print(price,"用户传递到后台的金额*100显示") balance = UserInfo.objects.get(user_id=user.user_id).balance assert price == int(100 * balance) if price < 100: # 201 错误码代表最小提取1.00元 return JsonResponse({'status': 201}) else: if settings.DEBUG: data = payClient.transfer.transfer(user_id='o0jd6wk8OK77nbVqPNLKG-2urQxQ', amount=100, desc="用户{0}发起提现".format(user.user_id), check_name="NO_CHECK") else: print("用户{}开始发起提现".format(user.user_id)) #检查用户现在的余额是多少 user_balance_now = UserInfo.objects.get(user_id=user.user_id).balance #提现金额必须等于现在的金额,否则无法提现 assert price == int(100 * user_balance_now) print("用户现在的余额是多少{}".format(user_balance_now)) # if user_balance_now>0: data = payClient.transfer.transfer(user_id=user.wechat_id, amount=price, desc="用户{0}发起提现".format(user.user_id), check_name="NO_CHECK") print("用户开始发起提现,提款成功的状态码{}".format(data['result_code'])) if data['result_code'] == 'SUCCESS': print(data['result_code'],'提款成功的状态码') UserWithdraw.objects.create_withdraw(openid=user.wechat_id, amount=price, trade_data=data, user_id = user.user_id) # 更新用户的余额 user_balance = UserInfo.objects.clear_balance(user_id=user.user_id) print("用户") price = "%.2f" % (price / 100) print(price) # 查询当前余额 withdraw_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) url = 'http://wechat.onmytarget.cn/' # 构造模板发送模板 data = Withdraw_temp(user.wechat_id, url, price, 0, withdraw_time) do_push(data) return JsonResponse({'status': 200}) else: print(data['result_code'], '若是提款失败的状态码') logger.error("用户{0}发起提现".format(user.user_id)) logger.error(data) # 说明付款失败,联系客服处理 return JsonResponse({'status': 401}) except AssertionError as a: return JsonResponse({'status': 403}) except Exception as e: logger.error(str(e)) return JsonResponse({'status': 401})
def test_template(): #openid,goal_type data = morning_attention_temp("o0jd6wgPxXAFK9aifqR858FOWDV0", "无限") do_push(data) return JsonResponse({"status": 200})
def running_sign_in_api(request): user = request.session["user"] """ 跑步签到后端 API :param request: :return: """ """获取随机数""" random = request.POST["random"] try: resp = send_img.delay(user.user_id, random, user.wechat_id, "1") print("第{}张图片的发送结果{}".format(random, resp)) except Exception as e: print(e) logger.error(e) """获取对应的目标的goal id""" goal_id = request.POST.get('goal', ' ') distance = float(request.POST.get('distance', 0)) print(distance, "从前端获取传递的距离") goal = RunningGoal.objects.get(goal_id=goal_id) """获取前端传递的两个路径""" file_filepath = request.POST.get("file_filepath") file_refpath = request.POST.get("file_refpath") """获取当前的时间""" punch_time = timezone.now() """存储一段话""" document = request.POST.get("document", " ") # 如果是日常模式打卡,则规定distance必须为日常距离 # if goal.goal_type: # distance = goal.kilos_day """将打卡记录存储到数据库中,增加一段话""" punch = RunningPunchRecord.objects.create(goal=goal, voucher_ref=file_refpath, voucher_store=file_filepath, distance=distance, record_time=punch_time, document=document) goal.add_distance += distance goal.save() """增加用户的完成天数""" UserRecord.objects.update_finish_day(user=user) if not goal.goal_type: goal.left_distance -= distance goal.save() if punch: try: # 将用户的打卡天数加一 goal.punch_day += 1 goal.save() print("用户{}打卡成功".format(user.user_id)) if goal.goal_type == 1: first = "在{}天内,每日完成{}公里".format(goal.goal_day, goal.kilos_day) else: first = "在{}天内,一共完成{}公里".format(goal.goal_day, goal.goal_distance) # 发送打卡成功模板提醒 punch_time = timezone.now().strftime("%m-%d") # 用户的开始时间是多少 start_time = RunningGoal.objects.get(goal_id=goal.goal_id).start_time print(start_time, "用户的开始时间") end_time = start_time + timedelta(days=goal.goal_day) print("用户的结束时间", end_time) print(end_time.strftime("%Y-%m")) url = 'http://wechat.onmytarget.cn/' days = '{}/{}'.format(goal.punch_day, goal.goal_day) punch_day = "{}到{}".format(start_time.strftime('%m-%d'), end_time.strftime("%m-%d")) data = punch_success(user.wechat_id, url, first, punch_time, punch_day, days) print("{}用户开始打卡".format(user.user_id)) do_push(data) except Exception as e: print(e) logger.error(e) return JsonResponse({"status": 200})
def running_sign_in_api(request): print("用户开始打卡") print(111111111111111111111111111111) user = request.session["user"] """ 跑步签到后端 API :param request: :return: """ """获取对应的目标的goal id""" goal_id = request.POST.get('goal', ' ') distance = float(request.POST.get('distance', 0)) goal = RunningGoal.objects.get(goal_id=goal_id) # 从前端接收传递过来的base64 base_64 = request.POST.get("base_64", "") # 将base64的前面去掉 """获取当前的时间""" punch_record_time = timezone.now() """存储一段话""" document = request.POST.get("document", " ") # """获取User的WechatID""" user_wechat_id = request.session['user'].wechat_id """存储图片""" # User 名字加随机字符串 fileName = user_wechat_id + "_" + "{}".format( user.user_id) + "_" + random_string(16) + ".jpg" print(fileName) """保存图片""" bash_str = "".join(base_64).split(",")[1] imgdata = base64.b64decode(bash_str) # 文件的实际存储路径 """将打卡记录存储到数据库中,增加一段话""" punch = RunningPunchRecord.objects.create_record( goal, filename=fileName, distance=distance, punch_record_time=punch_record_time, base64_str=imgdata, document=document) print("打卡成功") goal.add_distance += distance goal.save() """增加用户的完成天数""" UserRecord.objects.update_finish_day(user=user) times = UserRecord.objects.get(user=user) if punch: if goal.goal_type == 1: first = "在{}天内,每日完成{}公里".format(goal.goal_day, goal.kilos_day) else: first = "在{}天内,一共完成{}公里".format(goal.goal_day, goal.goal_distance) # 发送打卡成功模板提醒 punch_time = time.strftime('%m月%d日', time.localtime(time.time())) end_time = (RunningGoal.objects.get(user_id=user.user_id).start_time + timedelta(days=goal.goal_day)).strftime('%m月%d日') url = 'http://wechat.onmytarget.cn/' # first = "在{}天内,每日完成{}公里".format(goal.goal_day, goal.kilos_day) days = '{}/{}'.format(times.finish_days, goal.goal_day) punch_day = "{}-{}".format(goal.start_time.strftime('%m月%d日'), end_time) data = punch_success(user.wechat_id, url, first, punch_time, punch_day, days) print("{}用户开始打卡".format(user.user_id)) do_push(data) return HttpResponse(200)