def post(self, request): logger.info('web_pay_request_para:' + str(request.POST)) try: user = request.user amount = fmt_two_amount(request.POST.get('amount')) gate_id = request.POST.get('gate_id') request_ip = get_client_ip(request) device_type = split_ua(request)['device_type'] channel = PayOrder.get_bank_and_channel(gate_id)[1] except: logger.exception('third_pay_error') result = {'message': '参数错误'} return self.render_to_response(result) if channel == 'yeepay': result = YeeProxyPay().proxy_pay(user, amount, gate_id, request_ip, device_type) elif channel == 'baopay': result = BaoProxyPay().proxy_pay(user, amount, gate_id, request_ip, device_type) else: result = HuifuPay().pre_pay(request) print 'pay_jump_para' + str(result) return self.render_to_response(result)
def restore(order_id, amount, user): if type(amount) != decimal.Decimal: amount = fmt_two_amount(amount) record = RedPackRecord.objects.filter(user=user, order_id=order_id).first() if not record: return {"ret_code": -1, "message": "redpack not exists"} record.apply_platform = "" record.apply_at = None record.order_id = None record.product_id = None record.save() event = record.redpack.event rtype = event.rtype rule_value = event.amount # deduct = event.amount deduct = _calc_deduct(amount, rtype, rule_value, event) if rtype == "interest_coupon": logger.info(u"%s--%s 退回加息券 %s" % (event.name, record.id, timezone.now())) return {"ret_code": 1, "deduct": deduct} else: logger.info(u"%s--%s 退回账户 %s" % (event.name, record.id, timezone.now())) return {"ret_code": 0, "deduct": deduct}
def deduct_calc(amount, redpack_amount): if not amount or not redpack_amount: return {"ret_code": 30181, "message": u"金额错误"} try: float(amount) float(redpack_amount) except: return {"ret_code": 30182, "message": u"金额格式不正确"} t5 = fmt_two_amount(amount) * decimal.Decimal('0.005') redpack_amount = fmt_two_amount(redpack_amount) real_deduct = fmt_two_amount(0) if t5 >= redpack_amount: real_deduct = redpack_amount else: real_deduct = t5 real_deduct = real_deduct.quantize(decimal.Decimal('0.01'), rounding=decimal.ROUND_HALF_DOWN) return {"ret_code": 0, "deduct": real_deduct}
def consume(redpack, amount, user, order_id, device_type, product_id): amount = fmt_two_amount(amount) record = RedPackRecord.objects.filter(user=user, id=redpack).first() redpack = record.redpack event = redpack.event device_type = _decide_device(device_type) start_time, end_time = get_start_end_time(event.auto_extension, event.auto_extension_days, record.created_at, event.available_at, event.unavailable_at) if not record: return {"ret_code": 30171, "message": u"优惠券不存在"} if record.order_id or record.product_id: return {"ret_code": 30172, "message": u"优惠券已使用"} if redpack.status == "invalid": return {"ret_code": 30173, "message": u"优惠券已作废"} if not start_time < timezone.now() < end_time: return {"ret_code": 30174, "message": u"优惠券不可使用"} if amount < event.invest_amount: return { "ret_code": 30175, "message": u"投资金额不满足优惠券规则%s" % event.invest_amount } if event.apply_platform != "all" and ( event.apply_platform != device_type or (event.give_platform == 'app' and device_type not in ('ios', 'android'))): return { "ret_code": 30176, "message": u"此优惠券只能在%s平台使用" % event.apply_platform } rtype = event.rtype rule_value = event.amount if event.rtype != 'interest_coupon': deduct = _calc_deduct(amount, rtype, rule_value, event) else: deduct = 0 record.order_id = order_id record.product_id = product_id record.apply_platform = device_type record.apply_amount = deduct record.apply_at = timezone.now() record.save() return { "ret_code": 0, "message": u"ok", "deduct": deduct, "rtype": event.rtype }
def confirm_pay(self, order_id, business_no=None, sms_code=None, request=None): """ 使用短信验证码,business_no放到数据库中 """ try: if not business_no: business_no = PayInfo.objects.get( order__id=order_id).bao_business_no confirm_pay_para = ConfirmPayPara(order_id, business_no, sms_code) resp_json = confirm_pay_para.post() amount = fmt_two_amount(int(resp_json['succ_amt']) / 100.0) resp_content = resp_json['resp_content'] return self.pay_order.order_after_pay_succcess( amount, order_id, res_content=resp_content, request=request) except PayException, err: return self.pay_order.order_after_pay_error(err, order_id)
def _check_signature(self, message_dict): # check hmac = self.get_hmac(message_dict, 'response') if hmac != message_dict.get('hmac'): raise ThirdPayError(40015, '不合法的第三方支付信息' + str(message_dict)) try: # convert data self.order_id = int(message_dict.get('r6_Order')) self.amount = fmt_two_amount(message_dict.get('r3_Amt')) # 1代表成功,因为只有成功才会回调,所以只会是1 ret_code = int(message_dict.get('r1_Code')) if ret_code == 1: self.ret_code = 0 else: self.ret_code = ret_code self.res_message = '支付成功' self.res_content = str(message_dict) except: raise ThirdPayError(40015, '不合法的第三方支付信息' + str(message_dict))
def php_redpack_restore(order_id, product_id, amount, user): """ 从红包记录获取到使用红包信息 :param order_id: :param product_id: :param amount: :param user: :return: """ if type(amount) != decimal.Decimal: amount = fmt_two_amount(amount) record = RedPackRecord.objects.filter(is_month_product=True, user=user, order_id=order_id, product_id=product_id).first() if not record: return {"ret_code": -1, "message": "redpack not exists"} record.apply_platform = "" record.apply_at = None record.is_month_product = False record.order_id = None record.product_id = None record.save() event = record.redpack.event rtype = event.rtype rule_value = event.amount # deduct = event.amount deduct = _calc_deduct(amount, rtype, rule_value, event) if rtype == "interest_coupon": logger.info(u"user : %s, %s--%s 退回加息券 %s" % (user, event.name, record.id, timezone.now())) return {"ret_code": 1, "deduct": deduct} else: logger.info(u"user : %s, %s--%s 退回账户 %s" % (user, event.name, record.id, timezone.now())) return {"ret_code": 0, "deduct": deduct}
def parse_message(self, message_dict, res_ip): # check signature = self._get_signature(message_dict) if signature != message_dict.get('Md5Sign'): raise ThirdPayError(40015, '不合法的第三方支付信息' + str(message_dict)) try: # convert data self.order_id = int(message_dict.get('TransID')) self.amount = fmt_two_amount( int(message_dict.get('FactMoney')) / 100.0) # 第三方1代表成功 ret_code = int(message_dict.get('Result')) if ret_code == 1: self.ret_code = 0 else: self.ret_code = 1 self.res_message = message_dict.get('resultDesc') self.res_content = str(message_dict) except: logger.exception('不合法的第三方支付信息') raise ThirdPayError(40015, '不合法的第三方支付信息' + str(message_dict)) return self
def pre_pay(self, request, bank=None): """ 汇付天下直接进行邦卡支付,不能够获取验证码 """ if not request.user.wanglibaouserprofile.id_is_valid: return {"ret_code": 20111, "message": "请先进行实名认证"} amount = request.DATA.get("amount", "").strip() card_no = request.DATA.get("card_no", "").strip() input_phone = request.DATA.get("phone", "").strip() gate_id = request.DATA.get("gate_id", "").strip() if not amount or not card_no or not gate_id: return {"ret_code": 20112, 'message': '信息输入不完整'} if len(card_no) > 10 and not input_phone: return {"ret_code": 20112, 'message': '信息输入不完整'} if card_no and len(card_no) == 10: return {'ret_code': 20013, 'message': '卡号格式不正确'} try: float(amount) except: return {"ret_code": 20114, 'message': '金额格式错误'} amount = fmt_two_amount(amount) user = request.user profile = user.wanglibaouserprofile bank = Bank.objects.filter(gate_id=gate_id).first() if not bank or not bank.huifu_bind_code.strip(): return {"ret_code": 201151, "message": "不支持该银行"} if len(card_no) == 10: card = Card.objects.filter(user=user, no__startswith=card_no[:6], no__endswith=card_no[-4:]).first() card_no = card.no else: card = Card.objects.filter(no=card_no, user=user).first() if not card: card = self.bind_card_wlbk(user, card_no, bank, request) if not card: return {"ret_code": -1, "message": '银行卡不存在'} if bank and card and bank != card.bank: return {"ret_code": 201153, "message": "银行卡与银行不匹配"} if card and not card.is_bind_huifu: res = self.open_bind_card(user, bank, card) if res['ret_code'] != 0: return res card.is_bind_huifu = True card.save() try: pay_info = PayInfo() pay_info.amount = amount pay_info.total_amount = amount pay_info.type = PayInfo.DEPOSIT pay_info.status = PayInfo.INITIAL pay_info.user = user pay_info.channel = "huifu_bind" pay_info.request_ip = get_client_ip(request) order = OrderHelper.place_order(user, Order.PAY_ORDER, pay_info.status, pay_info=model_to_dict(pay_info)) pay_info.order = order if card: pay_info.bank = card.bank pay_info.card_no = card.no else: pay_info.bank = bank pay_info.card_no = card_no pay_info.status = PayInfo.PROCESSING pay_info.account_name = profile.name pay_info.save() OrderHelper.update_order(order, user, pay_info=model_to_dict(pay_info), status=pay_info.status) # 充值 req, res = self._card_pay_huifu(user=user, amount=pay_info.amount, card_no=card_no) pay_info.error_code = res['RespCode'] pay_info.error_message = res['ErrMsg'] pay_info.request = req pay_info.response = res pay_info.response_ip = get_client_ip(request) if res['RespCode'] != u'000000': pay_info.save() return {"ret_code": -3, "message": res['ErrMsg']} else: pay_info.fee = self.FEE keeper = MarginKeeper(pay_info.user, pay_info.order.pk) margin_record = keeper.deposit(amount) pay_info.margin_record = margin_record pay_info.status = PayInfo.SUCCESS pay_info.save() rs = {"ret_code": 0, "message": "success", "amount": amount, "margin": margin_record.margin_current} if rs['ret_code'] == 0: device = split_ua(request) try: # fix@chenweibi, add order_id tools.deposit_ok.apply_async(kwargs={"user_id": pay_info.user.id, "amount": pay_info.amount, "device": device, "order_id": order.id}) except: pass # 充值成功后,更新本次银行使用的时间 Card.objects.filter(user=pay_info.user, no=pay_info.card_no).update(last_update=timezone.now()) OrderHelper.update_order(pay_info.order, pay_info.user, pay_info=model_to_dict(pay_info), status=pay_info.status) return rs except Exception, e: message = PayResult.RETRY pay_info.status = PayInfo.FAIL pay_info.error_message = str(e) pay_info.save() OrderHelper.update_order(order, request.user, pay_info=model_to_dict(pay_info), status=pay_info.status) return {"ret_code": "20119", "message": message}
def bind_pay_deposit(request): """ 根据银行设置的支付渠道进行支付渠道的支付 1、获取验证码 2、快捷支付功能 """ logger.error(request.DATA) card_no = request.DATA.get("card_no", "").strip() gate_id = request.DATA.get("gate_id", "").strip() input_phone = request.DATA.get("phone", "").strip() device_type = split_ua(request)['device_type'] ip = util.get_client_ip(request) mode = request.DATA.get('mode', '').strip() user = request.user if user.wanglibaouserprofile.utype == '3': return {"ret_code": 30059, "message": u"企业用户无法请求该接口"} if not user.wanglibaouserprofile.id_is_valid: return {"ret_code": 20111, "message": "请先进行实名认证"} if not card_no and not gate_id: return {"ret_code": 20001, 'message': '信息输入不完整'} if len(card_no) > 10 and (not input_phone or not gate_id): return {"ret_code": 20112, 'message': '信息输入不完整'} user_bind_cards = Card.objects.filter( user=user).filter(Q(is_bind_kuai=True) | Q(is_bind_yee=True)) if len(card_no) > 10 and user_bind_cards.filter(no=card_no).count() == 0 and \ user_bind_cards.filter(~Q(no=card_no)).count() > 0: # 只允许绑一张 return {"ret_code": 20113, 'message': '为确保账户安全,资金同卡进出,不能再绑卡'} if gate_id: bank = Bank.objects.filter(gate_id=gate_id).first() else: if len(card_no) == 10: card = Card.objects.filter(user=user, no__startswith=card_no[:6], no__endswith=card_no[-4:]).first() else: card = Card.objects.filter(no=card_no, user=user).first() if not card: return {"ret_code": 20001, 'message': '信息输入不完整'} bank = card.bank if not bank: return {"ret_code": 20002, "message": "银行ID不正确"} #验证银行卡和银行匹配 if len(card_no) != 10 and bank.cards_info: cardinfo = check_bank_carkinfo(card_no, bank) #返回ret_code为20075的话表示银行卡和银行不匹配 if cardinfo['ret_code'] == 20075: return cardinfo amount = request.DATA.get('amount', '').strip() try: amount = float(amount) amount = util.fmt_two_amount(amount) if amount < 0: raise ValueError() except: return {"ret_code": 20114, 'message': '金额格式错误'} if bank.channel == 'huifu': result = HuifuShortPay().pre_pay(request) return result elif bank.channel == 'yeepay': result = YeeShortPay().pre_pay(request) return result elif bank.channel == 'baopay': res = BaoPayInterface(user, ip, device_type).pre_pay(card_no, amount, input_phone, gate_id, request) return res elif bank.channel == 'kuaipay': stop_no_sms_channel = Misc.objects.filter( key='kuai_qpay_stop_no_sms_channel').first() if stop_no_sms_channel and stop_no_sms_channel.value == '1' and \ len(card_no) == 10 and not request.DATA.get('mode'): # mode != vcode_for_qpay # Modify by hb on 2016-04-28 #return {'ret_code': 201183, return {'ret_code': 201181, 'message': u'该银行支付升级,请更新App版本'} result = KuaiShortPay().pre_pay(user, amount, card_no, input_phone, gate_id, device_type, ip, request, mode=mode) return result else: return {"ret_code": 20004, "message": "请选择支付渠道"}
def withdraw(request): amount = request.DATA.get("amount", "").strip() card_id = request.DATA.get("card_id", "").strip() vcode = request.DATA.get("validate_code", "").strip() if not amount or not card_id: return {"ret_code": 20061, "message": u"信息输入不完整"} user = request.user if not user.wanglibaouserprofile.id_is_valid: return {"ret_code": 20062, "message": u"请先进行实名认证"} if user.wanglibaouserprofile.frozen: return {"ret_code": 20072, "message": u"用户账户已冻结,请联系客服"} try: float(amount) except: return {"ret_code": 20063, 'message': u'金额格式错误'} amount = util.fmt_two_amount(amount) if len(str(amount)) > 20: return {"ret_code": 20064, 'message': u'金额格式错误,大于100元且为100倍数'} margin = user.margin.margin if amount > margin: return {"ret_code": 20065, 'message': u'余额不足'} phone = user.wanglibaouserprofile.phone status, message = validate_validation_code(phone, vcode) if status != 200: # Modify by hb on 2015-12-02 #return {"ret_code": 20066, "message": u"验证码输入错误"} return {"ret_code": 20066, "message": message} card = Card.objects.filter(pk=card_id).first() if not card or card.user != user: return {"ret_code": 20067, "message": u"请选择有效的银行卡"} # 检测银行卡是否在黑名单中 black_list = BlackListCard.objects.filter(card_no=card.no).first() if black_list and black_list.user != user: return {"ret_code": 20072, "message": u'银行卡号异常,请联系客服'} # 检查白名单 white_list = WhiteListCard.objects.filter(user=user, card_no=card.no).first() if not white_list: # 增加银行卡号检测功能,检测多张卡 card_count = Card.objects.filter(no=card.no).count() if card_count > 1: return {"ret_code": 20073, "message": u'银行卡号有多张重复,请联系客服'} # 检测银行卡在以前的提现记录中是否为同一个用户 payinfo_record = PayInfo.objects.filter( card_no=card.no, type='W').order_by('-create_time').first() if payinfo_record: if payinfo_record.user != user: return {"ret_code": 20074, "message": u'银行卡号与身份信息不符,请联系客服'} # 计算提现费用 手续费 + 资金管理费 bank = card.bank uninvested = user.margin.uninvested # 充值未投资金额 # 获取费率配置 fee_misc = WithdrawFee() fee_config = fee_misc.get_withdraw_fee_config() # 检测提现最大最小金额 if amount > fee_config.get('max_amount') or amount <= 0: return {"ret_code": 20068, 'message': u'提现金额超出最大提现限额'} if amount < fee_config.get('min_amount'): if amount != margin: return { "ret_code": 20069, 'message': u'账户余额小于{}时需要一次性提完'.format(fee_config.get('min_amount')) } # 检测银行的单笔最大提现限额,如民生银行 if bank and bank.withdraw_limit: bank_limit = util.handle_withdraw_limit(bank.withdraw_limit) bank_max_amount = bank_limit.get('bank_max_amount', 0) if bank_max_amount: if amount > bank_max_amount: return {"ret_code": 20070, 'message': u'提现金额超出银行最大提现限额'} # 获取计算后的费率 fee, management_fee, management_amount = fee_misc.get_withdraw_fee( user, amount, margin, uninvested) # 实际提现金额 actual_amount = amount - fee - management_fee if actual_amount <= 0: return {"ret_code": 20071, "message": u'实际到账金额为0,无法提现'} pay_info = PayInfo() pay_info.amount = actual_amount pay_info.fee = fee pay_info.management_fee = management_fee pay_info.management_amount = management_amount pay_info.total_amount = amount pay_info.type = PayInfo.WITHDRAW pay_info.user = user pay_info.card_no = card.no pay_info.account_name = user.wanglibaouserprofile.name pay_info.bank = card.bank pay_info.request_ip = util.get_client_ip(request) pay_info.status = PayInfo.ACCEPTED pay_info.channel = "app" try: order = OrderHelper.place_order(user, Order.WITHDRAW_ORDER, pay_info.status, pay_info=model_to_dict(pay_info)) pay_info.order = order keeper = MarginKeeper(user, pay_info.order.pk) margin_record = keeper.withdraw_pre_freeze( amount, uninvested=management_amount) pay_info.margin_record = margin_record pay_info.save() return { "ret_code": 0, 'message': u'提现成功', "amount": amount, "phone": phone, "bank_name": bank.name, "order_id": order.id } except Exception, e: pay_info.error_message = str(e) pay_info.status = PayInfo.FAIL pay_info.save() return {"ret_code": 20065, 'message': u'余额不足'}
def post(self, request): amount = request.DATA.get("amount", "") bank_id = request.DATA.get("bank_id", "") card_id = request.DATA.get("card_id", "") device = rest_utils.split_ua(request) device_type = rest_utils.decide_device(device['device_type']) try: app_version = device['app_version'] except KeyError: app_version = '' if not amount: return Response({"ret_code": 30131, "message": u"请输入金额"}) if device_type == 'pc': if not card_id: return Response({"ret_code": 30141, "message": u"银行卡选择错误"}) else: if not bank_id: if device_type == 'ios' or device_type == 'android': if app_version and app_version < "2.6.3": pass else: return Response({ "ret_code": 30137, "message": u"银行卡选择错误" }) try: float(amount) except: return Response({"ret_code": 30132, 'message': u'金额格式错误'}) if amount <= 0: return Response({"ret_code": 30131, "message": u"请输入金额"}) amount = util.fmt_two_amount(amount) # 计算提现费用 手续费 + 资金管理费 user = request.user margin = user.margin.margin # 账户余额 uninvested = user.margin.uninvested # 充值未投资金额 if amount > margin: return Response({"ret_code": 30139, "message": u"提现金额超出账户可用余额"}) # 获取费率配置 fee_misc = WithdrawFee() fee_config = fee_misc.get_withdraw_fee_config() # 检测提现最大最小金额 max_amount = fee_config.get('max_amount') min_amount = fee_config.get('min_amount') if amount > max_amount: return Response({"ret_code": 30133, 'message': u'提现金额超出最大提现限额'}) if amount < min_amount: if margin > min_amount: return Response({ "ret_code": 30134, 'message': u'提现金额必须大于{}元'.format(min_amount) }) else: if amount != margin: return Response({ "ret_code": 30138, 'message': u'账户余额小于{}元时须一次性提完'.format(min_amount) }) # 检测银行的单笔最大提现限额,如民生银行 withdraw_limit = '' if bank_id and card_id: bank = Bank.objects.filter(code=bank_id.upper()).first() try: card = Card.objects.get(pk=card_id) except Card.DoesNotExist: card = None if bank.id != card.bank.id: return Response({"ret_code": 30140, 'message': u'银行选择错误'}) else: if card: withdraw_limit = card.bank.withdraw_limit elif bank and bank.withdraw_limit: withdraw_limit = bank.withdraw_limit elif card_id and not bank_id: try: card = Card.objects.get(pk=card_id) withdraw_limit = card.bank.withdraw_limit except Card.DoesNotExist: pass elif bank_id and not card_id: bank = Bank.objects.filter(code=bank_id.upper()).first() if bank and bank.withdraw_limit: withdraw_limit = bank.withdraw_limit if withdraw_limit: bank_limit = util.handle_withdraw_limit(withdraw_limit) bank_max_amount = bank_limit.get('bank_max_amount', 0) if bank_max_amount: if amount > bank_max_amount: return Response({ "ret_code": 30135, 'message': u'提现金额超出银行最大提现限额' }) # 获取计算后的费率 fee, management_fee, management_amount = fee_misc.get_withdraw_fee( user, amount, margin, uninvested) actual_amount = amount - fee - management_fee # 实际到账金额 if actual_amount <= 0: return Response({"ret_code": 30136, "message": u'余额不足,提现失败'}) if device_type == 'ios' or device_type == 'android': if app_version and app_version < "2.6.3": fee = fee + management_fee return Response({ "ret_code": 0, "actual_amount": actual_amount, "fee": fee, # 手续费 "management_fee": management_fee, # 管理费 "management_amount": management_amount, # 计算管理费的金额 })
def pre_pay(self, request): """ 获取验证码支付还是直接支付 长卡号获取验证码 短卡号直接支付 """ if not request.user.wanglibaouserprofile.id_is_valid: return {"ret_code": 20111, "message": "请先进行实名认证"} amount = request.DATA.get("amount", "").strip() card_no = request.DATA.get("card_no", "").strip() input_phone = request.DATA.get("phone", "").strip() gate_id = request.DATA.get("gate_id", "").strip() device_type = split_ua(request)['device_type'] if not amount or not card_no: return {"ret_code": 20112, 'message': '信息输入不完整'} if len(card_no) > 10 and (not input_phone or not gate_id): return {"ret_code": 20113, 'message': '卡号格式不正确'} try: float(amount) except: return {"ret_code": 20114, 'message': '金额格式错误'} amount = util.fmt_two_amount(amount) # if amount < 10 or len(str(amount)) > 20: # return {"ret_code": 20115, 'message': '充值须大于等于10元'} if len(str(amount)) > 20: return {"ret_code": 20115, 'message': '充值金额太大'} if amount < 0.009: # 涉及到小数精度,不能用0.01 return {"ret_code": 20115, 'message': '充值金额太小(至少0.01元)'} user = request.user profile = user.wanglibaouserprofile card, bank = None, None if gate_id: bank = Bank.objects.filter(gate_id=gate_id).first() if not bank or not bank.yee_bind_code.strip(): return {"ret_code": 201116, "message": "不支持该银行"} if len(card_no) == 10: card = Card.objects.filter(user=user, no__startswith=card_no[:6], no__endswith=card_no[-4:], is_bind_yee=True).first() else: #card = Card.objects.filter(no=card_no, user=user).first() card = Card.objects.filter(no=card_no, user=user, bank=bank).first() pay_record = PayInfo.objects.filter(card_no=card_no, user=user, bank=bank) if pay_record.filter(error_message__icontains='不匹配'): return {"ret_code":200118, "message":"银行卡与银行不匹配"} if not card: card = self.add_card_unbind(user, card_no, bank, request) if not card and not bank: return {'ret_code': 200117, 'message': '卡号不存在或银行不存在'} #if bank and card and bank != card.bank: #return {"ret_code": 200118, "message": "银行卡与银行不匹配"} # 商户生成的唯一绑卡请求号,最长50位 request_id = '{phone}{time}'.format(phone=profile.phone, time=timezone.now().strftime("%Y%m%d%H%M%S")) if len(card_no) != 10: # 未绑定银行卡,需要先绑定银行卡获取验证码,然后在确认支付 try: # 请求绑定银行卡 res = self._bind_card_request(request, input_phone, card_no, request_id) if res['ret_code'] != 0: # 600326已绑定,600302绑卡数超限 if res['ret_code'] in ['600326', '600302']: self.sync_bind_card(user) return {'ret_code': '20119', 'message': '银行卡已绑定,请返回使用快捷充值'} else: # logger.error(res) return res except Exception, e: logger.error(e.message) return {"ret_code": "20120", "message": '绑定银行卡失败'}
def app_pay(self, request): if not request.user.wanglibaouserprofile.id_is_valid: return {"ret_code":20071, "message":"请先进行实名认证"} amount = request.DATA.get("amount", "").strip() deviceid = request.DATA.get("device_id", "").strip() if not amount or not deviceid: return {"ret_code":20072, 'message':'信息输入不完整'} try: float(amount) except: return {"ret_code":20073, 'message':'金额格式错误'} amount = util.fmt_two_amount(amount) #if amount < 100 or amount % 100 != 0 or len(str(amount)) > 20: if amount < 10 or len(str(amount)) > 20: #return {"ret_code":20074, 'message':'金额格式错误,大于100元且为100倍数'} return {"ret_code":20074, 'message':'充值金额需大于10元'} if amount > 20000: return {"ret_code":20073, 'message':'单笔充值不超过2万,单月不超过5万。如需充值更多金额可以去网站完成。'} terminal = deviceid.split(":") deviceid = terminal[-1] tmpdic = {"imei":0, "mac":1, "uuid":2, "other":3} if terminal[0] in tmpdic: terminaltype = tmpdic[terminal[0]] else: terminaltype = tmpdic['other'] card_id = request.DATA.get("card_id", "") user = request.user #amount_sec = int(amount*100) amount_sec = long(amount*100) useragent = request.META.get("HTTP_USER_AGENT", "noagent").strip() try: pay_info = PayInfo() pay_info.amount = amount pay_info.total_amount = amount pay_info.type = PayInfo.DEPOSIT pay_info.status = PayInfo.INITIAL pay_info.user = user pay_info.channel = "yeepay" if card_id: card = Card.objects.filter(id=card_id, user=user).first() if not card: return {"ret_code":20075, 'message':'选择的银行卡不存在'} pay_info.bank = card.bank pay_info.card_no = card.no pay_info.request_ip = util.get_client_ip(request) order = OrderHelper.place_order(user, Order.PAY_ORDER, pay_info.status, pay_info = model_to_dict(pay_info)) pay_info.order = order pay_info.save() profile = user.wanglibaouserprofile dic = {"merchantaccount":self.MER_ID, "orderid":str(order.id), "transtime":long(time.mktime(pay_info.create_time.timetuple())), "amount":amount_sec, "productcatalog":"18", "productname":"网利宝-APP充值", "identityid":str(user.id), "identitytype":2, "terminaltype":terminaltype, "terminalid":deviceid, "userip":pay_info.request_ip, "userua":useragent, "callbackurl":self.PAY_BACK_RETURN_URL, "fcallbackurl":self.PAY_RETURN_URL, "version":0, "paytypes":"1", "cardno":card_id, "orderexpdate":60} data, encryptkey = self._sign(dic) logger.error("%s" % dic) pay_info.request = str(dic) pay_info.status = PayInfo.PROCESSING pay_info.account_name = profile.name pay_info.save() OrderHelper.update_order(order, user, pay_info=model_to_dict(pay_info), status=pay_info.status) params = {"data":data, "encryptkey":encryptkey, "merchantaccount":self.MER_ID} url = "%s?%s" % (self.PAY_URL, urllib.urlencode(params)) logger.error(url) return {"ret_code":0, "url":url} except Exception, e: logger.error(traceback.format_exc()) message = PayResult.RETRY pay_info.status = PayInfo.FAIL pay_info.error_message = str(e) pay_info.save() OrderHelper.update_order(order, request.user, pay_info=model_to_dict(pay_info), status=pay_info.status) logger.fatal('sign error! order id: ' + str(pay_info.pk) + ' ' + str(e)) return {"ret_code":"20076", "message":message}
encryptkey = request.GET.get("encryptkey", "") data = request.GET.get("data", "") if not encryptkey or not data: return {"ret_code":20081, "message":"params invalid"} try: ybaeskey = self.rsa_base64_decrypt(encryptkey, self.PRIV_KEY) params = json.loads(self.aes_base64_decrypt(data, ybaeskey)) except Exception,e: logger.error(traceback.format_exc()) return {"ret_code":20088, "message":"data decrypt error"} logger.error("%s" % params) amount = util.fmt_two_amount(params['amount']) / 100 if "sign" not in params: return {"ret_code":20082, "message":"params sign not exist"} sign = params.pop("sign") if not self._verify(params, sign): return {"ret_code":20083, "message":"params sign invalid"} if params['merchantaccount'] != self.MER_ID: return {"ret_code":20084, "message":"params merhantaccount invalid"} orderId = params['orderid'] pay_info = PayInfo.objects.filter(order_id=orderId).first() if not pay_info: return {"ret_code":20085, "message":"order not exist"} if pay_info.status == PayInfo.SUCCESS:
def order_after_pay_succcess(self, amount, order_id, res_ip=None, res_content=None, request=None, need_bind_card=False): """ 处理订单和用户的账户 :param amount: :param order_id: :param user_id: :param ip: :param res_content: :return: """ # 参数校验 pay_info = PayInfo.objects.select_for_update().filter( order_id=order_id).first() if not pay_info: # return {"ret_code":20131, "message":"order not exist", "amount": amount} raise ThirdPayError(20131, 'order not exist') if pay_info.status == PayInfo.SUCCESS: return { "ret_code": 0, "message": PayResult.DEPOSIT_SUCCESS, "amount": amount } if fmt_two_amount(pay_info.amount) != fmt_two_amount(amount): raise ThirdPayError(20132, PayResult.EXCEPTION) if pay_info.user_id != pay_info.user_id: raise ThirdPayError(20133, PayResult.EXCEPTION) # 更新pay_info和margin信息 pay_info.error_message = "" if res_content: pay_info.response = res_content if res_ip: pay_info.response_ip = res_ip pay_info.fee = self.FEE keeper = MarginKeeper(pay_info.user, pay_info.order.pk) margin_record = keeper.deposit(amount) pay_info.margin_record = margin_record pay_info.status = PayInfo.SUCCESS pay_info.save() # 更新order信息 # if len(pay_info.card_no) == 10: # Card.objects.filter(user=pay_info.user, no__startswith=pay_info.card_no[:6], no__endswith=pay_info.card_no[-4:]).update(last_update=timezone.now(), is_bind_kuai=True) # else: # Card.objects.filter(user=pay_info.user, no=pay_info.card_no).update(last_update=timezone.now(), is_bind_kuai=True) OrderHelper.update_order(pay_info.order, pay_info.user, pay_info=model_to_dict(pay_info), status=pay_info.status) # 绑卡 if need_bind_card: self.add_card(pay_info.card_no, pay_info.bank, pay_info.user, pay_info.channel) try: user = pay_info.user CoopRegister(request).process_for_recharge(user, order_id) # tools.deposit_ok(request.user.id, amount, pay_info.device, order_id) tools.deposit_ok.apply_async( kwargs={ "user_id": user.id, "amount": amount, "device": pay_info.device, "order_id": order_id }) except: logger.exception('recharge_call_back faile for ' + str(user) + str(order_id)) logger.critical("orderId:%s success" % order_id) rs = { "ret_code": 0, "message": "success", "amount": amount, "margin": margin_record.margin_current, "order_id": order_id } return rs