| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933 |
- using Common.Constant;
- using log4net;
- using Microsoft.AspNetCore.Mvc;
- using SicboSub.Web.Helpers;
- using SicboSub.Web.Models;
- using System.Configuration;
- using System.Diagnostics;
- namespace SicboSub.Web.Controllers
- {
- public class HomeController : BaseController
- {
- private static readonly ILog log = LogManager.GetLogger(typeof(HomeController));
- private readonly ILogger<HomeController> _logger;
- private readonly IConfiguration _configuration;
- public HomeController(ILogger<HomeController> logger, IConfiguration configuration)
- {
- _logger = logger;
- _configuration = configuration;
- }
- public String GetParameter(String key)
- {
- return _configuration.GetSection(key).Value ?? "";
- }
- /// <summary>
- /// Lấy config value
- /// </summary>
- /// <summary>
- /// Trang chủ - Yêu cầu Token để truy cập
- /// Nếu chưa login và không có token URL -> Redirect về trang chủ Sicbo (RedirectUrl)
- /// Nếu có token -> Login -> Success: load trang, Fail: Redirect
- /// </summary>
- /// <summary>
- /// Helper to load exchange config server-side
- /// </summary>
- private async Task<List<ExchangeConfigItem>> LoadExchangeConfigInternal()
- {
- try
- {
- string token = GetToken();
- var request = new ExchangeConfigReq
- {
- lang = GetLanguage()
- };
- var url = GetParameter("Url") + ApiUrlConstant.ExchangeConfigLoadUrl;
- var resData = await DotnetLib.Rest.RestHandler.SendPostWithAuthen(
- log,
- url,
- request,
- token,
- token,
- "",
- GetLanguage()
- );
- if (resData != null)
- {
- ExchangeConfigRes response = new ExchangeConfigRes(resData.data);
- if (response.errorCode == CommonErrorCode.Success && response.data != null)
- {
- return response.data;
- }
- }
- }
- catch (Exception ex)
- {
- log.Error("LoadExchangeConfigInternal: Exception", ex);
- }
- return new List<ExchangeConfigItem>();
- }
- /// <summary>
- /// Helper to load packages server-side
- /// </summary>
- private async Task<List<PackageInfo>> LoadPackagesInternal()
- {
- try
- {
- string token = GetToken();
- var request = new PackageLoadReq
- {
- lang = GetLanguage(),
- pageNumber = 0,
- pageSize = 100
- };
- var url = GetParameter("Url") + ApiUrlConstant.PackageLoadUrl;
- var resData = await DotnetLib.Rest.RestHandler.SendPostWithAuthen(
- log,
- url,
- request,
- token,
- token,
- "",
- GetLanguage()
- );
- if (resData != null)
- {
- PackageLoadRes response = new PackageLoadRes(resData.data);
- if (response.errorCode == CommonErrorCode.Success && response.data != null)
- {
- return response.data
- .Where(p => !string.IsNullOrEmpty(p.productName) && p.productName.StartsWith("CHARGE"))
- .OrderBy(p => p.fee)
- .ToList();
- }
- }
- }
- catch (Exception ex)
- {
- log.Error("LoadPackagesInternal: Exception", ex);
- }
- return new List<PackageInfo>();
- }
- /// <summary>
- /// Helper to reload account info (refresh session data)
- /// </summary>
- private async Task ReloadAccountInfo()
- {
- try
- {
- var token = GetToken();
- if (!string.IsNullOrEmpty(token))
- {
- var request = new AccountInfoReq
- {
- msisdn = GetMsisdn(),
- lang = GetLanguage()
- };
- var url = GetParameter("Url") + ApiUrlConstant.UserInfoUrl;
- // Gọi API xác thực/lấy thông tin
- var resData = await DotnetLib.Rest.RestHandler.SendPostWithAuthen(
- log,
- url,
- request,
- token,
- token,
- "",
- GetLanguage()
- );
-
- if (resData != null)
- {
- AccountInfoRes response = new AccountInfoRes(resData.data);
- if (response.errorCode == CommonErrorCode.Success && response.data != null)
- {
- // Update Session
- HttpContext.Session.SetComplexData("winCoin", response.data.winCoin);
- HttpContext.Session.SetComplexData("betCoin", response.data.betCoin);
-
- var currentUser = HttpContext.Session.GetComplexData<TokenLoginData>("userInfo");
- if(currentUser != null) {
- currentUser.winCoin = response.data.winCoin;
- currentUser.betCoin = response.data.betCoin;
- currentUser.isRegistered = response.data.isRegistered;
- if(response.data.regPkg != null) {
- currentUser.regPkg = new RegInfoData {
- RegisterId = response.data.regPkg.RegisterId,
- Msisdn = response.data.regPkg.Msisdn,
- ProductName = response.data.regPkg.ProductName,
- RegisterTime = response.data.regPkg.RegisterTime,
- NumberSpin = response.data.regPkg.NumberSpin,
- Status = response.data.regPkg.Status,
- ExpireTime = response.data.regPkg.ExpireTime,
- Renew = response.data.regPkg.Renew
- };
- } else {
- currentUser.regPkg = null;
- }
- HttpContext.Session.SetComplexData("userInfo", currentUser);
- }
- HttpContext.Session.SetComplexData("isRegistered", response.data.isRegistered);
- }
- }
- }
- }
- catch(Exception ex)
- {
- log.Error("ReloadAccountInfo: Error", ex);
- }
- }
- public async Task<IActionResult> Index()
- {
- // 1. Kiểm tra nếu đã đăng nhập từ trước
- if (IsAuthenticated())
- {
- // Refresh account info as requested
- await ReloadAccountInfo();
- // Setup ViewData và hiển thị
- ViewData["IsAuthenticated"] = true;
- ViewData["Msisdn"] = GetMsisdn();
- ViewData["WinCoin"] = HttpContext.Session.GetComplexData<decimal?>("winCoin") ?? 0;
- ViewData["BetCoin"] = HttpContext.Session.GetComplexData<decimal?>("betCoin") ?? 0;
-
- // Load packages server-side
- var packages = await LoadPackagesInternal();
- HttpContext.Session.SetComplexData("Packages", packages); // Store in session as requested
-
- // Load exchange config server-side
- var exchangeConfigs = await LoadExchangeConfigInternal();
- HttpContext.Session.SetComplexData("ExchangeConfig", exchangeConfigs);
- return View();
- }
- // 2. Nếu chưa đăng nhập, kiểm tra Token trên URL
- // Debug logging
- log.Info($"Index: Request QueryString: {Request.QueryString}");
- var tokenKeys = Request.Query.Keys;
- log.Info($"Index: Query Keys: {string.Join(", ", tokenKeys)}");
-
- var token = Request.Query["token"].FirstOrDefault();
- log.Info($"Index: Token extracted: '{token}'");
- if (!string.IsNullOrEmpty(token))
- {
- log.Info($"Index: Token found in URL, attempting login...");
- HttpContext.Session.GetComplexData<string?>("tokenRedirect");
- HttpContext.Session.SetComplexData("tokenRedirect", token);
- try
- {
- // Tạo request
- var request = new TokenLoginReq
- {
- token = token,
- language = GetLanguage()
- };
- var url = GetParameter("Url") + ApiUrlConstant.AuthLoginUrl;
- // Gọi API xác thực
- var resData = await DotnetLib.Rest.RestHandler.SendPostWithAuthen(
- log,
- url,
- request,
- token,
- token,
- "",
- GetLanguage()
- );
- // Parse response
- if (resData != null)
- {
- TokenLoginRes response = new TokenLoginRes(resData.data);
-
- if (response.errorCode == CommonErrorCode.Success)
- {
- // Login thành công -> Lưu Session
- CreateAuthToken();
- HttpContext.Session.SetComplexData("token", token);
- HttpContext.Session.SetComplexData("msisdn", response.data?.msisdn);
- HttpContext.Session.SetComplexData("winCoin", response.data?.winCoin);
- HttpContext.Session.SetComplexData("betCoin", response.data?.betCoin);
- HttpContext.Session.SetComplexData("userInfo", response.data);
- HttpContext.Session.SetComplexData("isRegistered", response.data?.isRegistered);
- log.Info($"Index: Login success, MSISDN = {response.data?.msisdn}");
- // Redirect lại Index để xóa token khỏi URL (và để lọt vào check IsAuthenticated ở trên)
- return RedirectToAction("Index");
- }
- else
- {
- log.Warn($"Index: Login failed - {response.message}");
- }
- }
- }
- catch (Exception ex)
- {
- log.Error("Index: Login exception", ex);
- }
- }
- // 3. Nếu chạy đến đây nghĩa là: Chưa Login Session VÀ (Không có token HOẶC Login Token thất bại)
- // ==> Redirect về trang nguồn (sicbo.vn)
- return RedirectToLogin(_configuration);
- }
- public async Task<IActionResult> Play()
- {
- var token = "";
- // 1. Kiểm tra nếu đã đăng nhập từ trước
- if (IsAuthenticated())
- {
- token = HttpContext.Session.GetComplexData<string>("tokenRedirect");
- log.Info($"Play: token = "+ token);
- }
- var url = GetParameter("RedirectUrl") + "/?token=" + token;
- log.Info($"PlayUrl: url = " + url);
- ClearCache();
- // Không gọi ClearCache() để giữ session login khi user quay lại
- return Redirect(url);
- }
- public IActionResult Privacy()
- {
- if (!IsAuthenticated()) return RedirectToLogin(_configuration);
- return View();
- }
- /// <summary>
- /// Helper to load play history
- /// </summary>
- private async Task<List<PlayHistoryItem>> LoadPlayHistoryInternal()
- {
- try
- {
- var token = GetToken();
- // 3 days ago
- var fromDate = DateTime.Now.AddDays(-3).ToString("dd/MM/yyyy 00:00:00");
- var toDate = DateTime.Now.ToString("dd/MM/yyyy 23:59:59");
- var request = new PlayHistoryReq
- {
- msisdn = GetMsisdn(),
- lang = GetLanguage(),
- fromDate = fromDate,
- toDate = toDate,
- pageNumber = 0,
- pageSize = 100
- };
- var url = GetParameter("Url") + ApiUrlConstant.PlayHistoryUrl;
- var resData = await DotnetLib.Rest.RestHandler.SendPostWithAuthen(
- log,
- url,
- request,
- token,
- token,
- "",
- GetLanguage()
- );
- if (resData != null)
- {
- PlayHistoryRes response = new PlayHistoryRes(resData.data);
- if (response.errorCode == CommonErrorCode.Success && response.data != null)
- {
- return response.data;
- }
- }
- }
- catch (Exception ex)
- {
- log.Error("LoadPlayHistoryInternal: Error", ex);
- }
- return new List<PlayHistoryItem>();
- }
- /// <summary>
- /// Helper to load purchase history
- /// </summary>
- private async Task<List<PurchaseHistoryItem>> LoadPurchaseHistoryInternal()
- {
- try
- {
- var token = GetToken();
- // 30 days ago for purchase history
- var fromDate = DateTime.Now.AddDays(-30).ToString("dd/MM/yyyy 00:00:00");
- var toDate = DateTime.Now.ToString("dd/MM/yyyy 23:59:59");
- var request = new PurchaseHistoryReq
- {
- msisdn = GetMsisdn(),
- lang = GetLanguage(),
- fromDate = fromDate,
- toDate = toDate,
- pageNumber = 0,
- pageSize = 20
- };
- var url = GetParameter("Url") + ApiUrlConstant.PurchaseHistoryUrl;
- var resData = await DotnetLib.Rest.RestHandler.SendPostWithAuthen(
- log,
- url,
- request,
- token,
- token,
- "",
- GetLanguage()
- );
- if (resData != null)
- {
- PurchaseHistoryRes response = new PurchaseHistoryRes(resData.data);
- if (response.errorCode == CommonErrorCode.Success && response.data != null)
- {
- return response.data;
- }
- }
- }
- catch (Exception ex)
- {
- log.Error("LoadPurchaseHistoryInternal: Error", ex);
- }
- return new List<PurchaseHistoryItem>();
- }
- /// <summary>
- /// Helper to load exchange history
- /// </summary>
- private async Task<List<ExchangeHistoryItem>> LoadExchangeHistoryInternal()
- {
- try
- {
- var token = GetToken();
- // 30 days ago
- var fromDate = DateTime.Now.AddDays(-30).ToString("dd/MM/yyyy 00:00:00");
- var toDate = DateTime.Now.ToString("dd/MM/yyyy 23:59:59");
- var request = new ExchangeHistoryReq
- {
- msisdn = GetMsisdn(),
- lang = GetLanguage(),
- fromDate = fromDate,
- toDate = toDate,
- pageNumber = 0,
- pageSize = 20
- };
- var url = GetParameter("Url") + ApiUrlConstant.ExchangeHistoryUrl;
- var resData = await DotnetLib.Rest.RestHandler.SendPostWithAuthen(
- log,
- url,
- request,
- token,
- token,
- "",
- GetLanguage()
- );
- if (resData != null)
- {
- ExchangeHistoryRes response = new ExchangeHistoryRes(resData.data);
- if (response.errorCode == CommonErrorCode.Success && response.data != null)
- {
- return response.data;
- }
- }
- }
- catch (Exception ex)
- {
- log.Error("LoadExchangeHistoryInternal: Error", ex);
- }
- return new List<ExchangeHistoryItem>();
- }
- public async Task<IActionResult> History()
- {
- if (!IsAuthenticated()) return RedirectToLogin(_configuration);
-
- var gameHistory = await LoadPlayHistoryInternal();
- // User requested: "history prize then pass its msisdn and it is Daily prize"
- var prizeHistory = await LoadRankingInternal("DAILY", GetMsisdn());
- var purchaseHistory = await LoadPurchaseHistoryInternal();
- var exchangeHistory = await LoadExchangeHistoryInternal();
-
- var model = new HistoryViewModel
- {
- GameHistory = gameHistory,
- PrizeHistory = prizeHistory,
- PurchaseHistory = purchaseHistory,
- ExchangeHistory = exchangeHistory
- };
-
- ViewData["Msisdn"] = GetMsisdn();
- return View(model);
- }
- public IActionResult Winner()
- {
- if (!IsAuthenticated()) return RedirectToLogin(_configuration);
- return View();
- }
- /// <summary>
- /// Helper to load ranking history
- /// </summary>
- /// <summary>
- /// Helper to load ranking history
- /// </summary>
- private async Task<List<RankingHistoryItem>> LoadRankingInternal(string rankType, string msisdn = null, string specificDate = null)
- {
- try
- {
- var token = GetToken();
- // Calculate date range based on rankType
- string fromDate = "";
- string toDate = DateTime.Now.ToString("dd/MM/yyyy");
- if (!string.IsNullOrEmpty(specificDate))
- {
- if (rankType == "MONTHLY")
- {
- // Expected input: yyyy-MM
- if (DateTime.TryParseExact(specificDate, "yyyy-MM", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out DateTime parsedMonth))
- {
- var firstDay = new DateTime(parsedMonth.Year, parsedMonth.Month, 1);
- var lastDay = firstDay.AddMonths(1).AddDays(-1);
-
- fromDate = firstDay.ToString("dd/MM/yyyy 00:00:00");
- toDate = lastDay.ToString("dd/MM/yyyy 23:59:59");
- }
- else
- {
- // Fallback try basic parsing
- if (DateTime.TryParse(specificDate, out DateTime parsed)) {
- var firstDay = new DateTime(parsed.Year, parsed.Month, 1);
- var lastDay = firstDay.AddMonths(1).AddDays(-1);
- fromDate = firstDay.ToString("dd/MM/yyyy 00:00:00");
- toDate = lastDay.ToString("dd/MM/yyyy 23:59:59");
- }
- }
- }
- else
- {
- // DAILY - Exact Date
- // Convert yyyy-MM-dd to dd/MM/yyyy HH:mm:ss
- // Input expected: yyyy-MM-dd (from HTML5 date input)
- if (DateTime.TryParseExact(specificDate, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out DateTime parsedDate))
- {
- fromDate = parsedDate.ToString("dd/MM/yyyy 00:00:00");
- toDate = parsedDate.ToString("dd/MM/yyyy 23:59:59");
- }
- else
- {
- // Fallback: try to just append time if it looks like a date
- fromDate = specificDate + " 00:00:00";
- toDate = specificDate + " 23:59:59";
- }
- }
- }
- else
- {
- if (rankType == "DAILY")
- {
- // 7 days ago
- fromDate = DateTime.Now.AddDays(-7).ToString("dd/MM/yyyy 00:00:00");
- toDate = DateTime.Now.ToString("dd/MM/yyyy 23:59:59");
- }
- else if (rankType == "MONTHLY")
- {
- // 3 months ago
- fromDate = DateTime.Now.AddMonths(-3).ToString("dd/MM/yyyy 00:00:00");
- toDate = DateTime.Now.ToString("dd/MM/yyyy 23:59:59");
- }
- }
- var request = new RankingHistoryReq
- {
- msisdn = msisdn, // Pass specific msisdn or null/empty
- lang = GetLanguage(),
- rankType = rankType,
- fromDate = fromDate,
- toDate = toDate,
- pageNumber = 0,
- pageSize = 20
- };
-
- var url = GetParameter("Url") + ApiUrlConstant.RankingHistoryUrl;
-
- var resData = await DotnetLib.Rest.RestHandler.SendPostWithAuthen(
- log,
- url,
- request,
- token,
- token,
- "",
- GetLanguage()
- );
-
- if (resData != null)
- {
- RankingHistoryRes response = new RankingHistoryRes(resData.data);
- if (response.errorCode == CommonErrorCode.Success && response.data != null)
- {
- return response.data;
- }
- }
- }
- catch(Exception ex)
- {
- log.Error($"LoadRankingInternal ({rankType}): Error", ex);
- }
- return new List<RankingHistoryItem>();
- }
- public async Task<IActionResult> DailyRanking(string date = null)
- {
- if (!IsAuthenticated()) return RedirectToLogin(_configuration);
-
- // For Global Daily Ranking, we don't pass MSISDN implies global list
- var data = await LoadRankingInternal("DAILY", null, date);
- ViewData["RankingType"] = "DAILY";
- ViewData["SelectedDate"] = date;
- return View(data);
- }
- public async Task<IActionResult> MonthlyRanking(string date = null)
- {
- if (!IsAuthenticated()) return RedirectToLogin(_configuration);
-
- var data = await LoadRankingInternal("MONTHLY", null, date);
- ViewData["RankingType"] = "MONTHLY";
- ViewData["SelectedDate"] = date;
- return View(data);
- }
- public async Task<IActionResult> Account()
- {
- if (!IsAuthenticated()) return RedirectToLogin(_configuration);
- // Refresh account info to get latest balance
- await ReloadAccountInfo();
- // Get user info from session
- var userInfo = HttpContext.Session.GetComplexData<TokenLoginData>("userInfo");
-
- ViewData["UserInfo"] = userInfo;
- ViewData["Msisdn"] = GetMsisdn();
- ViewData["WinCoin"] = HttpContext.Session.GetComplexData<decimal?>("winCoin") ?? 0;
- ViewData["BetCoin"] = HttpContext.Session.GetComplexData<decimal?>("betCoin") ?? 0;
-
- // TODO: Retrieve actual values for Today/Month from API when available
- ViewData["TotalValueToday"] = 0;
- ViewData["TotalValueMonth"] = 0;
- return View();
- }
- /// <summary>
- /// Đăng xuất
- /// </summary>
- public IActionResult Logout()
- {
- ClearCache();
- return RedirectToLogin(_configuration);
- }
- [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
- public IActionResult Error()
- {
- return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
- }
- /// <summary>
- /// Đăng ký gói (Register)
- /// </summary>
- [HttpPost]
- public async Task<IActionResult> Register()
- {
- // 1. Check Authentication (server-side check)
- if (!IsAuthenticated())
- {
- return Json(new { errorCode = CommonErrorCode.UnauthorizedAccess, message = "Unauthorized" });
- }
- try
- {
- // 2. Prepare request data
- string? msisdn = GetMsisdn();
- string? token = GetToken();
- // Default package for daily registration
- string packageCode = GetParameter("PackageCodeDaily");
- // Default fallback if config missing
- if (string.IsNullOrEmpty(packageCode)) packageCode = "SICBO_DAY";
- var request = new RegisterReq
- {
- msisdn = msisdn,
- packageCode = packageCode,
- lang = GetLanguage()
- };
- // 3. Call API
- var url = GetParameter("Url") + ApiUrlConstant.RegisterUrl;
-
- var resData = await DotnetLib.Rest.RestHandler.SendPostWithAuthen(
- log,
- url,
- request,
- token,
- token,
- "",
- GetLanguage()
- );
- // 4. Handle Response
- if (resData != null)
- {
- RegisterRes response = new RegisterRes(resData.data);
-
- if (response.errorCode == CommonErrorCode.Success)
- {
- // Refresh info to get latest balance
- await ReloadAccountInfo();
-
- // Update response data with latest session info
- if (response.data == null) response.data = new RegisterData();
-
- response.data.winCoin = HttpContext.Session.GetComplexData<decimal?>("winCoin");
- response.data.betCoin = HttpContext.Session.GetComplexData<decimal?>("betCoin");
- return Json(response);
- }
- else
- {
- return Json(new { errorCode = response.errorCode, message = response.message });
- }
- }
-
- return Json(new { errorCode = CommonErrorCode.Error, message = "System Error" });
- }
- catch (Exception ex)
- {
- log.Error("Register: Exception", ex);
- return Json(new { errorCode = CommonErrorCode.SystemError, message = "Exception" });
- }
- }
- /// <summary>
- /// Mua thêm lượt (Buy More)
- /// </summary>
- [HttpPost]
- public async Task<IActionResult> BuyMore([FromBody] BuyMoreReq reqBody)
- {
- // 1. Check Authentication
- if (!IsAuthenticated())
- {
- return Json(new { errorCode = CommonErrorCode.UnauthorizedAccess, message = "Unauthorized" });
- }
- try
- {
- // 2. Prepare Request
- string msisdn = GetMsisdn();
- string token = GetToken();
-
- var request = new BuyMoreReq
- {
- msisdn = msisdn,
- packageCode = reqBody.packageCode,
- lang = GetLanguage()
- };
- // 3. Call API
- var url = GetParameter("Url") + ApiUrlConstant.BuyMoreUrl;
-
- var resData = await DotnetLib.Rest.RestHandler.SendPostWithAuthen(
- log,
- url,
- request,
- token,
- token,
- "",
- GetLanguage()
- );
- // 4. Handle Response
- if (resData != null)
- {
- BuyMoreRes response = new BuyMoreRes(resData.data);
- if (response.errorCode == CommonErrorCode.Success)
- {
- // Refresh info to get latest balance
- await ReloadAccountInfo();
- // Update response data with latest session info
- if (response.data == null) response.data = new BuyMoreData();
- response.data.winCoin = HttpContext.Session.GetComplexData<decimal?>("winCoin");
- response.data.betCoin = HttpContext.Session.GetComplexData<decimal?>("betCoin");
-
- return Json(response);
- }
- else
- {
- return Json(new { errorCode = response.errorCode, message = response.message });
- }
- }
- return Json(new { errorCode = CommonErrorCode.Error, message = "System Error" });
- }
- catch (Exception ex)
- {
- log.Error("BuyMore: Exception", ex);
- return Json(new { errorCode = CommonErrorCode.SystemError, message = "Exception" });
- }
- }
- /// <summary>
- /// Request Withdraw OTP
- /// </summary>
- [HttpPost]
- public async Task<IActionResult> RequestWithdrawOtp([FromBody] ExchangeRequestOtpReq reqBody)
- {
- if (!IsAuthenticated())
- {
- return Json(new { errorCode = CommonErrorCode.UnauthorizedAccess, message = "Unauthorized" });
- }
- try
- {
-
- string msisdn = GetMsisdn();
- string token = GetToken();
-
- var request = new ExchangeRequestOtpReq
- {
- msisdn = msisdn,
- configId = reqBody.configId,
- lang = GetLanguage()
- };
- // Call API
- var url = GetParameter("Url") + ApiUrlConstant.ExchangeRequestOtpUrl;
-
- var resData = await DotnetLib.Rest.RestHandler.SendPostWithAuthen(
- log,
- url,
- request,
- token,
- token,
- "",
- GetLanguage()
- );
- if (resData != null)
- {
- ExchangeRequestOtpRes response = new ExchangeRequestOtpRes(resData.data);
- return Json(new { errorCode = response.errorCode, message = response.message, data = response.data });
- }
-
- return Json(new { errorCode = CommonErrorCode.Error, message = "System Error" });
- }
- catch (Exception ex)
- {
- log.Error("RequestWithdrawOtp: Exception", ex);
- return Json(new { errorCode = CommonErrorCode.SystemError, message = "Exception" });
- }
- }
- /// <summary>
- /// Confirm Withdraw OTP
- /// </summary>
- [HttpPost]
- public async Task<IActionResult> ConfirmWithdrawOtp([FromBody] ExchangeVerifyOtpReq reqBody)
- {
- // 1. Check Authentication
- if (!IsAuthenticated())
- {
- return Json(new { errorCode = CommonErrorCode.UnauthorizedAccess, message = "Unauthorized" });
- }
- try
- {
- string msisdn = GetMsisdn();
- string token = GetToken();
-
- var request = new ExchangeVerifyOtpReq
- {
- msisdn = msisdn,
- otpCode = reqBody.otpCode,
- lang = GetLanguage()
- };
- // Call API
- var url = GetParameter("Url") + ApiUrlConstant.ExchangeVerifyOtpUrl;
-
- var resData = await DotnetLib.Rest.RestHandler.SendPostWithAuthen(
- log,
- url,
- request,
- token,
- token,
- "",
- GetLanguage()
- );
- if (resData != null)
- {
- ExchangeVerifyOtpRes response = new ExchangeVerifyOtpRes(resData.data);
- if (response.errorCode == CommonErrorCode.Success)
- {
- // Refresh Account Info
- await ReloadAccountInfo();
-
- // Get updated fields
- var winCoin = HttpContext.Session.GetComplexData<decimal?>("winCoin");
- var betCoin = HttpContext.Session.GetComplexData<decimal?>("betCoin");
- return Json(new { errorCode = response.errorCode, message = response.message, data = new { winCoin, betCoin } });
- }
-
- return Json(new { errorCode = response.errorCode, message = response.message, data = response.data });
- }
-
- return Json(new { errorCode = CommonErrorCode.Error, message = "System Error" });
- }
- catch (Exception ex)
- {
- log.Error("ConfirmWithdrawOtp: Exception", ex);
- return Json(new { errorCode = CommonErrorCode.SystemError, message = "Exception" });
- }
- }
- /// <summary>
- /// Lấy danh sách gói cước (Packages)
- /// </summary>
- [HttpPost]
- public async Task<IActionResult> GetPackages()
- {
- // 1. Check Authentication
- if (!IsAuthenticated())
- {
- return Json(new { errorCode = CommonErrorCode.UnauthorizedAccess, message = "Unauthorized" });
- }
- var packages = await LoadPackagesInternal();
- return Json(new { errorCode = CommonErrorCode.Success, data = packages });
- }
- }
- }
|