def payment_qrcode(request): try: weixin, weixin_payment_image, weixin_shop_assistant_image = userpaymentmethodmanager.load_weixin_info( request.user) if request.method == 'POST': form = UserPaymentMethodForm(request.POST, request.FILES, instance=weixin_payment_image) if form.is_valid(): form.save() weixin, weixin_payment_image, weixin_shop_assistant_image = userpaymentmethodmanager.load_weixin_info( request.user) else: messages.error(request, "输入有错误,请检查") return render( request, 'trading/paymentmethod/weixin.html', { 'user': request.user, 'weixin': weixin, 'payment_provider': weixin.provider.code if weixin is not None else PAYMENTMETHOD_WEIXIN, 'weixin_payment_image': weixin_payment_image, 'weixin_shop_assistant_image': weixin_shop_assistant_image }) except Exception as e: error_msg = 'sell_axfund hit exception' logger.exception(error_msg) return errorpageview.show_error(request, ERR_CRITICAL_IRRECOVERABLE, '系统遇到问题,请稍后再试。。。{0}'.format(error_msg))
def listusertransactions(request): try: username = request.user.username userId = request.user.id trans = ordermanager.get_user_transactions(userId, 'AXFund') pending_trans = [] transactions = [] for tran in trans: if tran.status == 'PENDING': pending_trans.append(create_trans_list_item(tran, 'AXFund')) else: transactions.append(create_trans_list_item(tran, 'AXFund')) accountinfo = useraccountinfomanager.get_user_accountInfo( request.user, 'AXFund', True) return render( request, 'trading/translist.html', { 'pending_trans': pending_trans, 'transactions': transactions, 'useraccountInfo': accountinfo }) except Exception as e: error_msg = '出售美基金遇到错误: {0}'.format(sys.exc_info()[0]) logger.exception(error_msg) return errorpageview.show_error(request, ERR_CRITICAL_IRRECOVERABLE, '系统遇到问题,请稍后再试。。。{0}'.format(error_msg))
def confirm_payment(request): try: if request.method == 'POST': order_id = request.POST['order_id'] keyword = request.POST['search_keyword'] ordermanager.confirm_purchase_order(order_id, request.user.username) messages.success(request, '确认付款,交易完成') useraccountInfo = useraccountinfomanager.get_user_accountInfo( request.user, 'AXFund') request.session[REQ_KEY_USERACCOUNTINFO] = useraccountInfo.tojson() buyorders = ordermanager.search_orders(keyword, None, None) else: return HttpResponseBadRequest('确认买单只能允许POST') return render( request, 'trading/admin/transmanagement.html', { 'useraccountInfo': useraccountInfo, REQ_KEY_USERNAME: request.user.username, 'search_keyword': keyword, 'buyorders': buyorders, 'bootstrap_datepicker': True }) except Exception as e: error_msg = '确认付款遇到错误: {0}'.format(sys.exc_info()[0]) logger.exception(error_msg) return errorpageview.show_error(request, ERR_CRITICAL_IRRECOVERABLE, '系统遇到问题,请稍后再试。。。{0}'.format(error_msg))
def confirm_payment(request): try: order_id = request.POST['order_id'] ordermanager.confirm_purchase_order(order_id, request.user.username) messages.success(request, '确认付款,交易完成') return redirect('sellorder') except Exception as e: error_msg = '确认付款遇到错误: {0}'.format(sys.exc_info()[0]) logger.exception(error_msg) return errorpageview.show_error(request, ERR_CRITICAL_IRRECOVERABLE, '系统遇到问题,请稍后再试。。。{0}'.format(error_msg))
def testpaymentqrcode(request): # TO DO: pass down request.user to controller. err_msg = {} try: if request.method == 'GET': if 'api_key' not in request.GET: err_msg['status'] = 'ERROR_MISSING_API_KEY' err_msg['message'] = '你的请求没有包含API KEY' return HttpResponseBadRequest(json.dumps(err_msg, ensure_ascii=False)) api_key = request.GET['api_key'] externaluserId = request.GET['externaluserId'] auth_token = request.GET['auth_token'] auth_check_url = request.GET['auth_check_url'] signature = request.GET['signature'] secret = None try: api_account = APIUserAccount.objects.get(apiKey=api_key) secret = api_account.secretKey except APIUserAccount.DoesNotExist: api_key = settings.QRCODE_TEST_API_KEY secret = settings.QRCODE_TEST_API_SECRET #err_msg['status'] = 'ERROR_API_KEY_NOTFOUND' #err_msg['message'] = '你的请求中的API KEY不存在' #return HttpResponseNotFound(json.dumps(err_msg, ensure_ascii=False)) if not validate_signature(api_key, externaluserId, secret, signature): err_msg['status'] = 'ERROR_SIGNATURE_NOTMATCH' err_msg['message'] = '你的请求签名不符' return HttpResponseBadRequest(json.dumps(err_msg, ensure_ascii=False)) user_payment_methods = userpaymentmethodmanager.get_user_payment_methods(request.user.id) return render(request, 'trading/paymentmethod/qrcode_client.html', { 'user_payment_methods':user_payment_methods, 'api_key': api_key, 'auth_token': auth_token, 'auth_check_url': auth_check_url, 'externaluserId': externaluserId, 'key': secret, 'signature': signature, 'payment_proxy': settings.QRCODE_TEST_PAYMENTPROXY }) else: return HttpResponseNotAllowed(['GET']) except Exception as e: error_msg = 'testpaymentqrcode' logger.exception(error_msg) return errorpageview.show_error(request, ERR_CRITICAL_IRRECOVERABLE, '系统遇到问题,请稍后再试。。。{0}'.format(error_msg))
def payment_method(request): # TO DO: pass down request.user to controller. try: if request.method == 'GET': payment_providers = userpaymentmethodmanager.get_payment_providers( ) user_payment_methods = userpaymentmethodmanager.get_user_payment_methods( request.user.id) return render( request, 'trading/update_payment_method.html', { 'user_payment_methods': user_payment_methods, 'payment_providers': payment_providers }) else: str_val = request.POST['payment_method_id'] payment_method_id = int(str_val) if len(str_val) > 0 else 0 payment_provider = request.POST['payment_provider'] account = request.POST['account'] client_id = request.POST['client_id'] client_secret = request.POST['client_secret'] has_error = False if len(payment_provider) == 0: has_error = True messages.error(request, '请选择支付方式') elif len(account) == 0 and len(client_id) == 0: has_error = True messages.error(request, '请输入您的账号或Client_ID') elif len(client_id) != 0 and len(client_secret) == 0: has_error = True messages.error(request, '请输入您的Client_Secret') if has_error: return redirect('paymentmethods') record = UserPaymentMethodView(payment_method_id, request.user.id, payment_provider, '', account, '', client_id, client_secret) userpaymentmethodmanager.create_update_user_payment_method( record, request.user.username) return redirect('accountinfo') except Exception as e: error_msg = 'sell_axfund hit exception' logger.exception(error_msg) return errorpageview.show_error(request, ERR_CRITICAL_IRRECOVERABLE, '系统遇到问题,请稍后再试。。。{0}'.format(error_msg))
def sell_axfund(request): try: sitesettings = context_processor.settings(request)['settings'] accountinfo = useraccountinfomanager.get_user_accountInfo( request.user, 'AXFund') if len(accountinfo.paymentmethods) == 0: messages.error(request, '请先注册支付方式再挂卖单') return redirect('accountinfo') if len(accountinfo.paymentmethods[0].account_at_provider) == 0: messages.error(request, '请先注册支付账号再挂卖单') return redirect('accountinfo') if request.method == 'POST': request_source = request.POST['request_source'] # this indicate that the request come from submit # order instead of refresh a response page of previous # order if len(request_source) > 0: order_command = read_order_input(request) if order_command.total_units - accountinfo.available_balance < 0: ordermanager.create_sell_order(order_command, request.user.username) messages.success(request, '您的卖单已经成功创建') else: messages.error(request, '卖单数量不可以高于可用余额') sellorders, buyorders = ordermanager.get_orders_by_user( request.user.id) if request.method == 'POST': return redirect('sellorder') else: return render( request, 'trading/mysellorder.html', { 'sellorders': sellorders, 'buyorders': buyorders, 'settings': sitesettings, 'useraccountInfo': accountinfo }) except Exception as e: error_msg = '出售美基金遇到错误: {0}'.format(sys.exc_info()[0]) logger.exception(error_msg) return errorpageview.show_error(request, ERR_CRITICAL_IRRECOVERABLE, '系统遇到问题,请稍后再试。。。{0}'.format(error_msg))
def redeem(request): try: if request.method == 'POST': userid = request.user.id toaddr = request.POST['toaddress'] amount = float(request.POST['quantity']) crypto = request.POST['crypto'] logger.info( '[{0}] redeem request: amount{1} toaddress {2} crypto {3}'. format(request.user.username, amount, toaddr, crypto)) if not redeemmanager.check_send_to_address(crypto, toaddr): logger.info( '[{0}] redeem request: Failed the address check'.format( request.user.username)) messages.error(request, "您的提币地址属于交易平台注入地址,请修改您的提币地址") return redirect('accountinfo') logger.info('[{0}] redeem request: Pass the address check'.format( request.user.username)) redeem_cmd = RedeemItem(userid, toaddr, amount, crypto) axfd_tool = get_coin_utils(crypto) redeemmanager.redeem(redeem_cmd, request.user.username, axfd_tool) return redirect('accountinfo') else: return HttpResponseBadRequest( 'The method can not be GET for redeem') except ValueError as ve: if ve.args[0].startswith(VE_REDEEM_EXCEED_LIMIT): logger.error(ve.args[0]) messages.error(request, "您的提币数量大于您现有的基金可使用余额,请从新输入提币数量") return redirect('accountinfo') elif ve.args[0].startswith(VE_ILLEGAL_BALANCE): logger.error(ve.args[0]) messages.error(request, "请检查您的余额是否正确再尝试提币") return redirect('accountinfo') except Exception as e: error_msg = '[{0}] 提币遇到错误: {1}'.format(request.user.username, sys.exc_info()[0]) logger.exception(error_msg) return errorpageview.show_error(request, ERR_CRITICAL_IRRECOVERABLE, '系统遇到问题,请稍后再试。。。{0}'.format(error_msg))
def accountinfo(request): try: useraccountInfo = useraccountinfomanager.get_user_accountInfo( request.user, 'AXFund') weixin, weixin_payment_image, weixin_shop_assistant_image = userpaymentmethodmanager.load_weixin_info( request.user) request.session[REQ_KEY_USERACCOUNTINFO] = useraccountInfo.tojson() return render( request, 'trading/myaccount.html', { 'useraccountInfo': useraccountInfo, REQ_KEY_USERNAME: request.user.username, 'weixin': weixin, 'weixin_payment_image': weixin_payment_image, 'weixin_shop_assistant_image': weixin_shop_assistant_image }) except Exception as e: error_msg = '用户主页显示遇到错误: {0}'.format(sys.exc_info()[0]) logger.exception(error_msg) return errorpageview.show_error(request, ERR_CRITICAL_IRRECOVERABLE, '系统遇到问题,请稍后再试。。。{0}'.format(error_msg))
def cancel_sell_order(request): try: username = request.user.username userId = request.user.id if request.method == 'POST': orderid = request.POST['order_id'] ordermanager.cancel_sell_order(userId, orderid, 'AXFund', username) return redirect('sellorder') except ValueError as ve: if ve.args[0] == "ORDER_USED_OR_LOCKED_CANCELLED": logger.exception("Cancel hit exception: {0} ".format(ve.args[0])) messages.error(request, "您选择的卖单有待完成买单,或在锁定,取消状态") return redirect('sellorder') else: raise except Exception as e: error_msg = '撤销美基金卖单遇到错误: {0}'.format(sys.exc_info()[0]) logger.exception(error_msg) return errorpageview.show_error(request, ERR_CRITICAL_IRRECOVERABLE, '系统遇到问题,请稍后再试。。。{0}'.format(error_msg))
def show_active_sell_orders(request): try: logger.debug("get show show_active_sell_orders request") username = request.user.username status = None sellorders = ordermanager.get_all_open_seller_order_exclude_user( request.user.id) accountinfo = useraccountinfomanager.get_user_accountInfo( request.user, 'AXFund') return render( request, 'trading/purchase.html', { 'sellorders': sellorders, REQ_KEY_USERNAME: username, 'useraccountInfo': accountinfo, 'previous_call_status': status }) except Exception as e: error_msg = '显示现有卖单出现错误: {0}'.format(sys.exc_info()[0]) logger.exception(e) return errorpageview.show_error(request, ERR_CRITICAL_IRRECOVERABLE, '系统遇到问题,请稍后再试。。。{0}'.format(error_msg))
def external_address(request): try: externaladdress = None if request.method == 'GET': # if there's id parameter, this is view/update request, # query the object first and show if 'id' in request.GET: id = 0 id_str = request.GET['id'] if len(id_str) > 0: id = int(id_str) logger.info('Get user {0}\'s external address by {1}'.format( request.user.username, id)) externaladdress = useraccountinfomanager.get_user_externaladdr_by_id(id) else: externaladdress = None return render(request, 'trading/update_external_address.html', { 'user_external_address': externaladdress }) else: id = 0 id_str = request.POST['id'] if len(id_str) > 0: id = int(id_str) address = request.POST['address'] alias = request.POST['alias'] crypto = request.POST['crypto'] if len(crypto) == 0: crypto = 'AXFund' externaladdress = UserExternalWalletAddressInfo(id, request.user.id, alias, address, crypto) if not useraccountinfomanager.create_update_externaladdr( externaladdress, request.user.username): messages.error(request, "您的提币地址属于交易平台注入地址,请修改您的提币地址") return redirect('accountinfo') except Exception as e: error_msg = '添加/修改提币抵制遇到错误: {0}'.format(sys.exc_info()[0]) logger.exception(error_msg) return errorpageview.show_error(request, ERR_CRITICAL_IRRECOVERABLE, '系统遇到问题,请稍后再试。。。{0}'.format(error_msg))
def cancel_purchase(request): try: if request.method == 'POST': buyorderid = request.POST['order_id'] cancelsellorder = request.POST.get('cancelsellorder', 'false') keyword = request.POST['search_keyword'] purchase_order = Order.objects.get(order_id=buyorderid) trade_status = TRADE_STATUS_USERABANDON payment_status = PAYMENT_STATUS_USERABANDON if cancelsellorder == 'true': trade_status = TRADE_STATUS_BADRECEIVINGACCOUNT payment_status = PAYMENT_STATUS_BADRECEIVINGACCOUNT ordermanager.cancel_purchase_order(purchase_order, trade_status, payment_status, request.user) useraccountInfo = useraccountinfomanager.get_user_accountInfo( request.user, 'AXFund') request.session[REQ_KEY_USERACCOUNTINFO] = useraccountInfo.tojson() buyorders = ordermanager.search_orders(keyword, None, None) messages.success(request, '确认取消订单,交易完成') else: return HttpResponseBadRequest('撤销买单只能允许POST') return render( request, 'trading/admin/transmanagement.html', { 'useraccountInfo': useraccountInfo, REQ_KEY_USERNAME: request.user.username, 'search_keyword': keyword, 'buyorders': buyorders, 'bootstrap_datepicker': True }) except Exception as e: error_msg = '用户主页显示遇到错误: {0}'.format(sys.exc_info()[0]) logger.exception(error_msg) return errorpageview.show_error(request, ERR_CRITICAL_IRRECOVERABLE, '系统遇到问题,请稍后再试。。。{0}'.format(error_msg))
def gettrans(request): try: useraccountInfo = useraccountinfomanager.get_user_accountInfo( request.user, 'AXFund') request.session[REQ_KEY_USERACCOUNTINFO] = useraccountInfo.tojson() buyorders = None keyword = '' if request.method == 'POST': keyword = request.POST['keyword'] buyorders = ordermanager.search_orders(keyword, None, None) return render( request, 'trading/admin/transmanagement.html', { 'useraccountInfo': useraccountInfo, REQ_KEY_USERNAME: request.user.username, 'search_keyword': keyword, 'buyorders': buyorders, 'bootstrap_datepicker': True }) except Exception as e: error_msg = '用户主页显示遇到错误: {0}'.format(sys.exc_info()[0]) logger.exception(error_msg) return errorpageview.show_error(request, ERR_CRITICAL_IRRECOVERABLE, '系统遇到问题,请稍后再试。。。{0}'.format(error_msg))
def show_purchase_input(request): try: if request.method != 'POST': error_msg = '购买页面不接受GET请求' logger.error( 'show_purchase_input(): receive GET request from {0}'.format( get_client_ip(request))) return errorpageview.show_error( request, ERR_CRITICAL_RECOVERABLE, '系统遇到问题,请稍后再试。。。{0}'.format(error_msg)) username = request.user.username userid = request.user.id useraccountInfo = useraccountinfomanager.get_user_accountInfo( request.user, 'AXFund') if len(useraccountInfo.paymentmethods) == 0: messages.error(request, '请先注册支付方式再购买') return redirect('accountinfo') if len(useraccountInfo.paymentmethods[0].account_at_provider) == 0: messages.error(request, '请先注册支付账号再购买') return redirect('accountinfo') if "owner_user_id" not in request.POST: messages.warning(request, "回到主页再进行操作") return redirect('accountinfo') owner_user_id = request.POST["owner_user_id"] reference_order_id = request.POST["reference_order_id"] paypal_client_id = '' sell_order_payment_method = ordermanager.get_and_update_sell_order_payment_methods( reference_order_id) paypal_client_id = sell_order_payment_method.client_id if sell_order_payment_method and sell_order_payment_method.client_id else '' payment_method = sell_order_payment_method.provider.code if sell_order_payment_method else '' bill_no = payment_account = payment_qrcode_url = '' if not sell_order_payment_method: api_tran = APIUserTransactionManager.get_trans_by_reference_order( reference_order_id) if api_tran is None: raise ValueError('ERR_API_SELLER_NO_API_RECORD') bill_no, payment_method, payment_account, payment_qrcode_url = parseInfo( api_tran) owner_login = request.POST["owner_login"] unit_price = float(request.POST["locked_in_unit_price"]) order_sub_type = request.POST["sub_type"] total_units = 0 if 'quantity' in request.POST: total_units = float(request.POST['quantity']) available_units = float(request.POST["available_units_for_purchase"]) order_currency = request.POST['sell_order_currency'] if order_sub_type == 'ALL_OR_NOTHING': total_units = available_units #owner_payment_methods = ordermanager.get_user_payment_methods(owner_user_id) if not sell_order_payment_method else [ # UserPaymentMethodView(0, # 0, None, # # TODO: the name of the seller payment provider should come from DB # '微信', '', # '', "", "")] #for method in owner_payment_methods: # print ("provider %s has image %s" % (method.provider.name, method.provider_qrcode_image)) buyorder = OrderItem('', userid, username, unit_price, order_currency, total_units, 0, 0.0, 'AXFund', '', '', 'BUY', sub_type=order_sub_type, selected_payment_provider=payment_method, account_at_payment_provider=payment_account) return render( request, 'trading/input_purchase.html', { 'username': username, 'buyorder': buyorder, 'owner_user_id': owner_user_id, 'sub_type': order_sub_type, 'reference_order_id': reference_order_id, 'available_units_for_purchase': available_units, 'paypal_clientId': paypal_client_id, 'order_currency': order_currency }) except ValueError as ve: handleValueError(ve, request) except Exception as e: error_msg = '显示买单出现错误: {0}'.format(sys.exc_info()[0]) logger.exception(e) return errorpageview.show_error(request, ERR_CRITICAL_IRRECOVERABLE, '系统遇到问题,请稍后再试。。。{0}'.format(error_msg))
def create_purchase_order(request): try: logger.debug('create_purchase_order()...') username = request.user.username userid = request.user.id logger.info("Begin process user input for creating purchase order") if request.method == 'POST': reference_order_id = request.POST['reference_order_id'] owner_user_id = int(request.POST["owner_user_id"]) quantity = float(request.POST['quantity']) unit_price = float(request.POST['unit_price']) order_currency = request.POST['order_currency'] seller_payment_provider = request.POST['seller_payment_provider'] logger.debug( 'create_purchase_order(): seller_payment_provider is {0}'. format(seller_payment_provider)) crypto = request.POST['crypto'] total_amount = float(request.POST['total_amount']) buyorder = OrderItem('', userid, username, unit_price, order_currency, quantity, 0, total_amount, crypto, '', '', 'BUY') buyorderid = None try: buyorderid = ordermanager.create_purchase_order( buyorder, reference_order_id, seller_payment_provider, username) except ValueError as ve: if ve.args[0] == 'SELLORDER_NOT_OPEN': messages.error(request, '卖单暂时被锁定,请稍后再试') elif ve.args[0] == 'BUY_EXCEED_AVAILABLE_UNITS': messages.error(request, '购买数量超过卖单余额,请按撤销键然后再试') else: raise #owner_payment_methods = ordermanager.get_user_payment_methods(owner_user_id) #useraccountInfo = useraccountinfomanager.get_user_accountInfo(request.user,'AXFund') return redirect('purchase') if buyorderid is None: raise ValueError('Failed to get purchase order id') if settings.PAYMENT_API_STATUS['heepay'] == 'auto': # read the sitsettings sitesettings = context_processor.settings(request)['settings'] json_response = send_payment_request(sitesettings, seller_payment_provider, buyorder.order_id, total_amount) if json_response and json_response['return_code'] == 'SUCCESS': ordermanager.post_open_payment_order( buyorderid, 'heepay', json_response['hy_bill_no'], json_response['hy_url'], username) qrcode_file = generate_payment_qrcode( 'heepay', json_response, settings.MEDIA_ROOT) return render( request, 'trading/purchase_heepay_qrcode.html', { 'total_units': quantity, 'unit_price': unit_price, 'total_amount': total_amount, 'heepay_qrcode_file': qrcode_file }) elif json_response and json_response[ 'return_msg'] == HEEPAY_ERR_NONEXIST_RECEIVE_ACCOUNT: purchase_order = Order.objects.get(order_id=buyorderid) admin = User.objects.get(username='******') ordermanager.cancel_purchase_order( purchase_order, TRADE_STATUS_BADRECEIVINGACCOUNT, PAYMENT_STATUS_BADRECEIVINGACCOUNT, admin) owner_payment_methods = ordermanager.get_user_payment_methods( owner_user_id) useraccountInfo = useraccountinfomanager.get_user_accountInfo( request.user, 'AXFund') messages.error( request, '向汇钱包下单申请失败:{0}'.format(json_response['return_msg'] if json_response else '系统错误')) return redirect('purchase') else: api_tran = APIUserTransactionManager.get_trans_by_reference_order( reference_order_id) if api_tran is None: raise ValueError('ERR_API_SELLER_NO_API_RECORD') bill_no, payment_method, payment_account, payment_qrcode_url = parseInfo( api_tran) ordermanager.post_open_payment_order(buyorderid, payment_method, bill_no, payment_qrcode_url, username) useraccountInfo = useraccountinfomanager.get_user_accountInfo( request.user, 'AXFund') return render( request, 'trading/purchase_qrcode.html', { 'qrcode_url': payment_qrcode_url, 'total_units': quantity, 'unit_price': unit_price, 'unit_currency': order_currency, 'seller_payment_provider': payment_method, 'seller_payment_provider_account': payment_account, 'total_amount': total_amount }) except Exception as e: error_msg = '创建买单遇到错误: {0}'.format(sys.exc_info()[0]) logger.exception(error_msg) return errorpageview.show_error(request, ERR_CRITICAL_IRRECOVERABLE, '系统遇到问题,请稍后再试。。。{0}'.format(error_msg))