public void SendSignupSMS(string cellphone, int countryId, string possn)
        {
            var country = new CountryComponent().GetById(countryId);

            if (country == null)
            {
                throw new CommonException(10000, Resources.国家不存在);
            }

            var posDac = new POSDAC();

            var pos = posDac.GetBySn(possn);

            if (pos == null)
            {
                throw new GeneralException(Resources.SN码不存在);
            }
            if (pos.Status)
            {
                throw new GeneralException(Resources.POSHasBoundOtherAccount);
            }

            Dictionary <string, string> dic = new Dictionary <string, string>
            {
                { "Cellphone", cellphone },
                { "CountryId", countryId.ToString() },
                { "FiatCurrency", country.FiatCurrency },
                { "PhoneCode", country.PhoneCode }
            };

            var verifier = new FiiiPosRegisterVerifier();

            SecurityVerify.SendCode(verifier, SystemPlatform.FiiiPOS, $"{countryId}{cellphone}", $"{country.PhoneCode}{cellphone}");
            verifier.CacheRegisterModel(SystemPlatform.FiiiPOS, $"{countryId}{cellphone}", dic);
        }
Пример #2
0
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            var isAuth = actionContext.RequestContext.Principal.Identity.IsAuthenticated;

            if (!isAuth)
            {
                return;
            }

            var        identity  = (WebIdentity)actionContext.RequestContext.Principal.Identity;
            WebContext context   = identity.WebContext;
            var        accountId = context.Id;

            var account = new MerchantAccountComponent().GetById(accountId);

            if (account == null)
            {
                throw new ApplicationException(Resources.SystemError);
            }

            var country = new CountryComponent().GetById(account.CountryId);

            if (country == null || !country.Status.HasFlag(CountryStatus.Enable))
            {
                throw new CommonException(ReasonCode.COUNTRY_FORBBIDEN_REQUEST, Resources.SystemError);
            }
        }
Пример #3
0
        public ServiceResult <Dictionary <string, List <string> > > Get()
        {
            var result = new ServiceResult <Dictionary <string, List <string> > >();

            var cpt = new CountryComponent();

            var dic = cpt.GetCustomerService(this.IsZH());

            var CustomerServices = new MasterSettingComponent().GetSettingByGroupName("CustomerService");

            if (CustomerServices != null)
            {
                foreach (var masterSetting in CustomerServices)
                {
                    dic.Add(masterSetting.Name, new List <string> {
                        masterSetting.Value
                    });
                }
            }

            result.Data = dic;

            result.Successful();
            return(result);
        }
Пример #4
0
        public SimpleUserInfoOM GetSimpleUserInfoOM(UserAccount user)
        {
            //var profile = new UserProfileAgent().GetUserProfile(user.Id);
            var country = new CountryComponent().GetById(user.CountryId);
            var fiatId  = new CurrenciesDAC().GetByCode(user.FiatCurrency).ID;

            if (IsNullOrWhiteSpace(user.Nickname))
            {
                user.Nickname = GenerateNickname();
            }

            return(new SimpleUserInfoOM
            {
                Avatar = user.Photo,
                Cellphone = GetMaskedCellphone(country.PhoneCode, user.Cellphone),
                //不再读取profile表
                FullName = user.Nickname,//profile == null ? "" : ((IsNullOrEmpty(profile.FirstName) ? "" : "* ") + profile.LastName),
                Nickname = user.Nickname,
                UserId = user.Id.ToString(),
                IsBaseProfileComplated = true,// profile != null,
                IsLV1Verified = user.L1VerifyStatus == VerifyStatus.Certified,
                HasSetPin = !IsNullOrEmpty(user.Pin),
                SecretKey = user.SecretKey,
                InvitationCode = user.InvitationCode,
                FiatId = fiatId,
                FiatCode = user.FiatCurrency
            });
        }
Пример #5
0
        private string GetUserMastMaskedCellphone(Guid userAccountId)
        {
            var user    = new UserAccountDAC().GetById(userAccountId);
            var country = new CountryComponent().GetById(user.CountryId);

            return(CellphoneExtension.GetMaskedCellphone(country.PhoneCode, user.Cellphone));
        }
Пример #6
0
        public PreTransferOM PreTransfer(UserAccount account, PreTransferIM im)
        {
            var toAccount = new UserAccountDAC().GetByCountryIdAndCellphone(im.ToCountryId, im.ToCellphone);

            if (toAccount == null)
            {
                throw new CommonException(ReasonCode.ACCOUNT_NOT_EXISTS, MessageResources.AccountNotExist);
            }
            if (account.Id == toAccount.Id)
            {
                throw new CommonException(ReasonCode.TRANSFER_TO_SELF, MessageResources.TransferToSelf);
            }
            var country        = new CountryComponent().GetById(im.ToCountryId);
            var profile        = new UserProfileAgent().GetUserProfile(toAccount.Id);
            var cryptoCurrency = new CryptocurrencyDAC().GetById(im.CoinId);
            var fromWallet     = new UserWalletComponent().GetUserWallet(account.Id, im.CoinId);

            return(new PreTransferOM
            {
                ToAvatar = toAccount.Photo ?? Guid.Empty,
                ToAccountName = country.PhoneCode + " " + toAccount.Cellphone,
                ToFullname = profile == null ? "" : ("* " + profile.LastName),
                IsTransferAbled = !toAccount.IsAllowTransfer.HasValue || toAccount.IsAllowTransfer.Value,
                IsProfileVerified = toAccount.L1VerifyStatus == VerifyStatus.Certified,
                CoinId = cryptoCurrency.Id,
                CoinCode = cryptoCurrency.Code,
                MinCount = ((decimal)Math.Pow(10, -cryptoCurrency.DecimalPlace)).ToString("G"),
                CoinDecimalPlace = cryptoCurrency.DecimalPlace.ToString(),
                CoinBalance = (fromWallet == null ? "0" : fromWallet.Balance.ToString(cryptoCurrency.DecimalPlace)),
                FiatCurrency = account.FiatCurrency,
                Price = (GetExchangeRate(account.CountryId, account.FiatCurrency, cryptoCurrency.Code)).ToString(),
                ChargeFee = "0"
            });
        }
Пример #7
0
        /// <summary>
        /// 发送注册验证码
        /// </summary>
        /// <param name="countryId"></param>
        /// <param name="cellphone"></param>
        public void SendRegisterCode(int countryId, string cellphone)
        {
            if (!AccountUseable(countryId, cellphone))
            {
                throw new CommonException(ReasonCode.ACCOUNT_EXISTS, Format(MessageResources.AccountAlreadyExist, cellphone));
            }
            var country = new CountryComponent().GetById(countryId);

            SecurityVerify.SendCode(new RegisterCellphoneVerifier(), SystemPlatform.FiiiPay, $"{countryId}:{cellphone}", $"{country.PhoneCode}{cellphone}");
        }
Пример #8
0
        public ServiceResult <Dictionary <string, List <string> > > CustomerService()
        {
            var result = new ServiceResult <Dictionary <string, List <string> > >();

            var cpt = new CountryComponent();
            var dic = cpt.GetCustomerService(IsZH());

            result.Data = dic;
            return(result);
        }
Пример #9
0
        public void SendModifyCellphoneSMS(Guid accountId, string cellphone)
        {
            MerchantAccount account = new MerchantAccountDAC().GetById(accountId);
            Country         country = new CountryComponent().GetById(account.CountryId);

            //加上区号
            cellphone = $"{country.PhoneCode}{cellphone}";

            SecurityVerify.SendCode(new ModifyCellphoneVerifier(), SystemPlatform.FiiiPOS, account.Id.ToString(), cellphone);
        }
Пример #10
0
        public void SendUpdateCellphoneNewCode(UserAccount user, string newCellphone)
        {
            if (new UserAccountDAC().GetByCountryIdAndCellphone(user.CountryId, newCellphone) != null)
            {
                throw new CommonException(ReasonCode.PhoneNumber_Exist, MessageResources.MobilePhoneHasReg);
            }

            var country = new CountryComponent().GetById(user.CountryId);

            SecurityVerify.SendCode(new UpdateCellphoneNewVerifier(), SystemPlatform.FiiiPay, user.Id.ToString(), $"{country.PhoneCode}{newCellphone}");
        }
Пример #11
0
        /// <summary>
        /// 发送登录验证码
        /// </summary>
        /// <param name="countryId"></param>
        /// <param name="cellphone"></param>
        public void SendLoginCode(int countryId, string cellphone)
        {
            if (AccountUseable(countryId, cellphone))
            {
                throw new CommonException(ReasonCode.ACCOUNT_NOT_EXISTS, MessageResources.AccountNotFound);
            }

            var country = new CountryComponent().GetById(countryId);

            SecurityVerify.SendCode(new LoginCellphoneVerifier(), SystemPlatform.FiiiPay, $"{countryId}:{cellphone}", $"{country.PhoneCode}{cellphone}");
        }
Пример #12
0
        public ServiceResult <PreGetVerifyNewCellphoneCodeOM> PreGetVerifyNewCellphoneCode()
        {
            var country = new CountryComponent().GetById(this.GetUser().CountryId);

            return(new ServiceResult <PreGetVerifyNewCellphoneCodeOM>
            {
                Data = new PreGetVerifyNewCellphoneCodeOM
                {
                    CountryName = this.IsZH() ? country.Name_CN : country.Name,
                    PhoneCode = country.PhoneCode
                }
            });
        }
Пример #13
0
        public SetupCode GenerateMerchantSecretKey(Guid accountId)
        {
            var merchant = new MerchantAccountDAC().GetById(accountId);

            if (merchant == null)
            {
                throw new CommonException(ReasonCode.ACCOUNT_NOT_EXISTS, Resources.用户不存在);
            }
            var country  = new CountryComponent().GetById(merchant.CountryId);
            var username = merchant.Username + "@FiiiPOS";
            var result   = new GoogleAuthenticator().GenerateSetupCode(SystemPlatform.FiiiPOS, username);

            return(result);
        }
Пример #14
0
        /// <summary>
        /// 获取商家基本信息
        /// </summary>
        /// <param name="merchantId"></param>
        /// <returns></returns>
        public MerchantBaseInfo GetMerchantBaseInfo_Web(Guid merchantId)
        {
            var info = new MerchantAccountDAC().GetMerchantBaseInfo_Web(merchantId);

            if (info == null)
            {
                throw new CommonException(ReasonCode.FiiiPosReasonCode.ACCOUNT_NOT_EXISTS, "用户不存在");
            }
            var country = new CountryComponent().GetById(info.CountryId);

            info.CountryName         = country.Name;
            info.CountryName_CN      = country.Name_CN;
            info.IsExistMerchantInfo = new MerchantInformationDAC().GetByMerchantAccountId(info.Id) != null;
            return(info);
        }
Пример #15
0
        public TradingReportDTO YearlyTrading(Guid merchantAccountId)
        {
            //if (!new ProfileComponent().ValidateLv1(merchantAccountId))
            //    throw new CommonException(ReasonCode.NOT_VERIFY_LV1, Resources.需要Lv1认证才能使用相关功能);

            var date = DateTime.UtcNow.Date;

            var endDate   = new DateTime(date.Year, date.Month, date.Day - 1);
            var startDate = new DateTime(date.Year, date.Month, 1).AddMonths(-11);

            var account = new MerchantAccountDAC().GetById(merchantAccountId);
            var country = new CountryComponent().GetById(account.CountryId);

            OrderDAC dac = new OrderDAC();
            List <OrderMonthStat> list = dac.GetTradingStatInMonth(merchantAccountId, startDate, endDate);

            var volume = list.Sum(e => e.OrderCount);
            var sum    = list.Sum(e => e.OrderAmount);
            var avg    = volume == 0 ? 0 : sum / volume;

            var result = new TradingReportDTO
            {
                FormDate     = startDate.ToUnixTime(),
                ToDate       = endDate.ToUnixTime(),
                Volume       = volume,
                SumAmount    = sum.ToString("F"),
                AvgAmount    = avg.ToString("F"),
                FiatCurrency = country.FiatCurrency ?? "USD",
                Stats        = new List <Stat>()
            };

            var cusorDate = startDate;

            while (cusorDate <= endDate)
            {
                var item = list.FirstOrDefault(e => DateTime.Parse($"{e.OrderYear}/{e.OrderMonth}") == cusorDate);
                var stat = new Stat
                {
                    Date   = cusorDate.ToUnixTime(),
                    Count  = item?.OrderCount ?? 0,
                    Amount = item?.OrderAmount ?? 0M
                };
                result.Stats.Add(stat);
                cusorDate = cusorDate.AddMonths(1);
            }

            return(result);
        }
Пример #16
0
        public PreVerifyLv2OM PreVerifyLv2(UserAccount user, bool isZH)
        {
            var profile = new UserProfileAgent().GetUserProfile(user.Id);
            var country = new CountryComponent().GetById(profile.Country.Value);

            return(new PreVerifyLv2OM
            {
                Address1 = profile.Address1,
                Address2 = profile.Address2,
                City = profile.City,
                CountryName = isZH ? country.Name_CN : country.Name,
                Postcode = profile.Postcode,
                State = profile.State,
                ResidentImage = profile.ResidentImage
            });
        }
Пример #17
0
        /// <summary>
        /// 发送忘记密码验证码
        /// </summary>
        /// <param name="countryId"></param>
        /// <param name="cellphone"></param>
        public void SendForgotPasswordCode(int countryId, string cellphone)
        {
            var user = new UserAccountDAC().GetByCountryIdAndCellphone(countryId, cellphone);

            if (user == null)
            {
                throw new CommonException(ReasonCode.ACCOUNT_NOT_EXISTS, MessageResources.AccountNotFound);
            }
            if (user.Status == 0)
            {
                throw new CommonException(ReasonCode.ACCOUNT_DISABLED, MessageResources.AccountDisabled);
            }

            var country = new CountryComponent().GetById(countryId);

            SecurityVerify.SendCode(new ForgetPasswordCellphoneVerifier(), SystemPlatform.FiiiPay, $"{countryId}:{cellphone}", $"{country.PhoneCode}{cellphone}");
        }
Пример #18
0
        public InfoOM Info(UserAccount user, bool isZH)
        {
            var agent = new UserProfileAgent();

            var profile = agent.GetUserProfile(user.Id);
            var country = new CountryComponent().GetById(user.CountryId);

            if (profile == null)
            {
                var userProfile = new UserProfile
                {
                    Country        = user.CountryId,
                    LastName       = "F" + RandomAlphaNumericGenerator.GenerateCode(8),
                    UserAccountId  = user.Id,
                    Cellphone      = user.Cellphone,
                    L1VerifyStatus = VerifyStatus.Uncertified,
                    L2VerifyStatus = VerifyStatus.Uncertified
                };
                var hasCreate = agent.AddProfile(userProfile);
                if (hasCreate)
                {
                    profile = userProfile;
                    _log.Info("Create profile info success. user id = " + user.Id);
                }
                else
                {
                    _log.Error("Create profile info error. user id = " + user.Id);
                }

                _log.Error("get profile info error, user id = " + user.Id);
            }

            return(new InfoOM
            {
                Avatar = user.Photo,
                Birthday = profile.DateOfBirth?.ToUnixTime().ToString(),
                Cellphone = new UserAccountComponent().GetMaskedCellphone(country.PhoneCode, user.Cellphone),
                CountryName = isZH ? country.Name_CN : country.Name,
                Email = new UserAccountComponent().GetMaskedEmail(user.Email),
                FullName = (string.IsNullOrEmpty(profile.FirstName) ? "" : "* ") + profile.LastName,
                Gender = profile.Gender,
                VerifiedStatus = GetVerifiedStatus(user)
            });
        }
        public void SendBindingSMS(string cellphone, int countryId, string merchantAccount, string sn)
        {
            var pos = new POSDAC().GetBySn(sn);

            if (pos == null)
            {
                throw new CommonException(ReasonCode.POSSN_ERROR, Resources.SN码不存在);
            }

            var account = new MerchantAccountDAC().GetByUsername(merchantAccount);

            if (account == null)
            {
                throw new GeneralException(Resources.AccountNotExists);
            }

            if (account.POSId.HasValue)
            {
                if (account.POSId == pos.Id)
                {
                    throw new CommonException(ReasonCode.GENERAL_ERROR, Resources.AccountHasBoundThisPOS);
                }
                else
                {
                    throw new CommonException(ReasonCode.GENERAL_ERROR, Resources.AccountHasBoundOtherPOS);
                }
            }

            var country = new CountryComponent().GetById(countryId);

            if (country == null)
            {
                throw new CommonException(10000, Resources.国家不存在);
            }
            if (account.PhoneCode != country.PhoneCode || account.Cellphone != cellphone)
            {
                throw new GeneralException(Resources.当前手机号与账号绑定的手机号不一致);
            }

            SecurityVerify.SendCode(new BindAccountCellphoneVerifier(), SystemPlatform.FiiiPOS, merchantAccount, $"{account.PhoneCode}{account.Cellphone}");
        }
        public AccountNeedVerifyInfo VerifyMerchantAccount(int countryId, string cellphone, string code, string merchantAccount)
        {
            SecurityVerify.Verify(new BindAccountCellphoneVerifier(), SystemPlatform.FiiiPOS, merchantAccount, code);

            var accountDac = new MerchantAccountDAC();
            var account    = accountDac.GetByUsername(merchantAccount);

            if (account == null)
            {
                throw new GeneralException(Resources.AccountNotExists);
            }

            var country = new CountryComponent().GetById(countryId);

            if (country == null)
            {
                throw new CommonException(10000, Resources.国家不存在);
            }

            string fullCellphone = $"{account.PhoneCode}{account.Cellphone}";

            if (!string.Equals(fullCellphone, country.PhoneCode + cellphone, StringComparison.InvariantCulture))
            {
                throw new GeneralException(Resources.当前手机号与账号绑定的手机号不一致);
            }

            var model = new BindAccountVerify
            {
                MerchantAccount   = merchantAccount,
                CellphoneVerified = true
            };

            SecurityVerify.SetModel(new CustomVerifier("BindAccount"), SystemPlatform.FiiiPOS, merchantAccount, model);

            return(new AccountNeedVerifyInfo
            {
                PIN = true,
                GoogleAuth = ValidationFlagComponent.CheckSecurityOpened(account.ValidationFlag, ValidationFlag.GooogleAuthenticator)
            });
        }
Пример #21
0
        public ProfileDTO GetProfile(Guid accountId)
        {
            var dac   = new MerchantAccountDAC();
            var agent = new MerchantProfileAgent();

            var account = dac.GetById(accountId);
            var profile = agent.GetMerchantProfile(accountId);
            var pos     = new POSDAC().GetById(account.POSId.Value);
            var country = new CountryComponent().GetById(account.CountryId);

            var result = new ProfileDTO
            {
                MerchantAccount    = account.Username,
                LastName           = profile.LastName,
                FirstName          = profile.FirstName,
                IdentityDocNo      = profile.IdentityDocNo,
                IdentityDocType    = (profile.IdentityDocType != IdentityDocType.IdentityCard && profile.IdentityDocType != IdentityDocType.Passport) ? IdentityDocType.IdentityCard : profile.IdentityDocType,
                FrontIdentityImage = profile.FrontIdentityImage,
                BackIdentityImage  = profile.BackIdentityImage,
                HandHoldWithCard   = profile.HandHoldWithCard,
                MerchantName       = account.MerchantName,
                CompanyName        = profile?.CompanyName,
                Email          = account.Email,
                Cellphone      = $"{account.PhoneCode} {account.Cellphone}",
                PosSn          = pos.Sn,
                Country        = country.Name,
                L1VerifyStatus = (int)(profile?.L1VerifyStatus ?? 0),
                L2VerifyStatus = (int)(profile?.L2VerifyStatus ?? 0),
                Address1       = profile?.Address1,
                Address2       = profile?.Address2,
                Postcode       = profile?.Postcode,
                City           = profile?.City,
                State          = profile?.State
            };

            return(result);
        }
Пример #22
0
        public TransferDetailOM Detail(Guid accountId, long transferId)
        {
            var    transfer      = new UserTransferDAC().GetTransfer(transferId);
            Guid   showAccountId = Guid.Empty;
            string transferType  = "";

            if (accountId == transfer.FromUserAccountId)
            {
                transferType  = Resources.TransferOut;
                showAccountId = transfer.ToUserAccountId;
            }
            else if (accountId == transfer.ToUserAccountId)
            {
                transferType  = Resources.TransferInto;
                showAccountId = transfer.FromUserAccountId;
            }

            UserProfile profile        = new UserProfileAgent().GetUserProfile(showAccountId);
            var         account        = new UserAccountDAC().GetById(showAccountId);
            var         country        = new CountryComponent().GetById(profile.Country.Value);
            var         cryptoCurrency = new CryptocurrencyDAC().GetById(transfer.CoinId);

            return(new TransferDetailOM
            {
                Status = (TransactionStatus)transfer.Status,
                StatusStr = Resources.OrderCompleted,
                TradeType = Resources.Transfer,
                TransferType = transferType,
                CoinCode = transfer.CoinCode,
                Amount = transfer.Amount.ToString(cryptoCurrency.DecimalPlace),
                AccountName = country.PhoneCode + " *******" + account.Cellphone.Substring(Math.Max(0, account.Cellphone.Length - 4)),
                Fullname = profile == null ? "" : ((string.IsNullOrEmpty(profile.FirstName) ? "" : "* ") + profile.LastName),
                Timestamp = transfer.Timestamp.ToUnixTime().ToString(),
                OrderNo = transfer.OrderNo
            });
        }
Пример #23
0
        private bool Register(int countryId, string cellphone, string password, string inviterCode)
        {
            var country   = new CountryComponent().GetById(countryId);
            var accountId = Guid.NewGuid();

            var userAccount = new UserAccount
            {
                Id                = accountId,
                PhoneCode         = country.PhoneCode,
                Cellphone         = cellphone,
                CountryId         = countryId,
                IsAllowExpense    = true,
                Email             = null,
                IsAllowWithdrawal = true,
                IsVerifiedEmail   = false,
                IsAllowTransfer   = true,
                Password          = PasswordHasher.HashPassword(password),
                Photo             = null,
                Pin               = null,
                RegistrationDate  = DateTime.UtcNow,
                SecretKey         = accountId.ToString().ToUpper(),
                Status            = 1,
                FiatCurrency      = country.FiatCurrency,
                InvitationCode    = GenerateInvitationCode(),
                InviterCode       = inviterCode,
                Nickname          = GenerateNickname(),
                ValidationFlag    = (byte)ValidationFlag.Cellphone
            };

            var userProfile = new UserProfile
            {
                Country        = countryId,
                LastName       = "F" + RandomAlphaNumericGenerator.GenerateCode(8),
                UserAccountId  = userAccount.Id,
                Cellphone      = cellphone,
                L1VerifyStatus = VerifyStatus.Uncertified,
                L2VerifyStatus = VerifyStatus.Uncertified
            };

            var accountDAC    = new UserAccountDAC();
            var agent         = new UserProfileAgent();
            var profileResult = agent.AddProfile(userProfile);

            if (profileResult)
            {
                try
                {
                    accountDAC.Insert(userAccount);
                }
                catch
                {
                    agent.RemoveProfile(userProfile);
                    throw;
                }

                //if (!string.IsNullOrEmpty(inviterCode))
                //{
                //    try
                //    {
                //        new InviteComponent().InsertRecord(new DTO.Invite.InviteRecordIM
                //        {
                //            InvitationCode = inviterCode,
                //            BeInvitedAccountId = userAccount.Id,
                //            Type = SystemPlatform.FiiiPay
                //        });
                //    }
                //    catch (Exception ex)
                //    {
                //        agent.RemoveProfile(userProfile);
                //        accountDAC.RemoveById(userAccount.Id);
                //        Error($"InviteComponent.InsertRecord faild:BeInvitedAccountId={userAccount.Id},InvitationCode={inviterCode},Type={SystemPlatform.FiiiPay.ToString()}", ex);
                //        throw ex;
                //    }
                //}
                return(true);
            }

            throw new CommonException(ReasonCode.GENERAL_ERROR, MessageResources.NetworkError);
        }
Пример #24
0
        //private static readonly bool IsPushProduction = Convert.ToBoolean(ConfigurationManager.AppSettings.Get("PushProduction"));

        public PayOrderOM PayExistedOrder(UserAccount user, string orderNo, string pin)
        {
            new SecurityComponent().VerifyPin(user, pin);

            var isAllowExpense = user.IsAllowExpense ?? true;

            if (!isAllowExpense)
            {
                throw new CommonException(ReasonCode.Not_Allow_Expense, MessageResources.PaymentForbidden);
            }

            var order = RedisHelper.Get <RedisOrderDTO>($"fiiipos:order:{orderNo}");

            RedisHelper.KeyDelete($"fiiipos:order:{orderNo}");
            if (order == null)
            {
                throw new ApplicationException(MessageResources.OrderNotFound);
            }

            //if (new OrderDAC().GetByOrderNo(orderNo) != null)
            //{
            //    throw new ApplicationException(Resources.订单已完成或者已退款);
            //}

            if (order.UserId != Guid.Empty)
            {
                if (order.UserId != user.Id)
                {
                    throw new ApplicationException(MessageResources.AccountNotMatch);
                }
            }

            var coin = new CryptocurrencyDAC().GetById(order.CryptoId);

            if (!coin.Status.HasFlag(CryptoStatus.Pay) || coin.Enable == 0)
            {
                throw new CommonException(ReasonCode.CURRENCY_FORBIDDEN, MessageResources.CurrencyForbidden);
            }

            var userWallet = new UserWalletDAC().GetByAccountId(user.Id, order.CryptoId);

            if (userWallet == null)
            {
                throw new CommonException(ReasonCode.INSUFFICIENT_BALANCE, MessageResources.InsufficientBalance);
            }
            var     exchangeRate    = GetExchangeRate(order.CountryId, order.FiatCurrency, coin);
            decimal fiatTotalAmount = (order.FiatAmount * (1 + order.Markup)).ToSpecificDecimal(4);
            decimal cryptoAmount    = (fiatTotalAmount / exchangeRate).ToSpecificDecimal(coin.DecimalPlace);

            if (userWallet.Balance < cryptoAmount)
            {
                throw new CommonException(ReasonCode.INSUFFICIENT_BALANCE, MessageResources.InsufficientBalance);
            }

            var merchantAccount = new MerchantAccountDAC().GetById(order.MerchantGuid);

            if (!merchantAccount.IsAllowAcceptPayment || merchantAccount.Status == AccountStatus.Locked)
            {
                throw new CommonException(ReasonCode.Not_Allow_Withdrawal, MessageResources.MerchantExceptionTransClose);
            }

            var merchantWallet = new MerchantWalletDAC().GetByAccountId(order.MerchantGuid, order.CryptoId);

            if (merchantWallet == null || !merchantWallet.SupportReceipt)
            {
                throw new ApplicationException(MessageResources.MerchantNotSupperCrypto);
            }
            var country   = new CountryComponent().GetById(merchantAccount.CountryId);
            var orderData = new Order
            {
                Id                  = Guid.NewGuid(),
                OrderNo             = order.OrderNo,
                MerchantAccountId   = merchantAccount.Id,
                CryptoId            = coin.Id,
                CryptoCode          = coin.Code,
                FiatAmount          = order.FiatAmount,
                PaymentType         = order.Type,
                FiatCurrency        = order.FiatCurrency,
                Status              = OrderStatus.Completed,
                ExpiredTime         = DateTime.UtcNow.AddMinutes(30),
                Markup              = merchantAccount.Markup,
                ExchangeRate        = GetExchangeRate(merchantAccount.CountryId, order.FiatCurrency, coin),
                UnifiedExchangeRate = GetExchangeRate(merchantAccount.CountryId, country.FiatCurrency ?? "USD", coin),
                UnifiedFiatCurrency = country.FiatCurrency ?? "USD",
                MerchantIP          = order.ClientIP,
                PaymentTime         = DateTime.UtcNow,
                Timestamp           = DateTime.UtcNow,
                UserAccountId       = user.Id
            };

            if (merchantAccount.WithdrawalFeeType != WithdrawalFeeType.FiiiCoin)
            {
                var calcModel =
                    CalculateAmount(order.FiatAmount, merchantAccount.Markup, merchantAccount.Receivables_Tier, orderData.ExchangeRate, coin);

                orderData.ActualFiatAmount   = calcModel.FiatTotalAmount;
                orderData.CryptoAmount       = calcModel.CryptoAmount;
                orderData.TransactionFee     = calcModel.TransactionFee;
                orderData.ActualCryptoAmount = calcModel.ActualCryptoAmount;

                var model = CalculateUnifiedAmount(orderData.CryptoAmount, orderData.ActualCryptoAmount, orderData.UnifiedExchangeRate);
                orderData.UnifiedFiatAmount       = model.UnifiedFiatAmount;
                orderData.UnifiedActualFiatAmount = model.UnifiedActualFiatAmount;
                var orderWithdrawalFee = new OrderWithdrawalFee()
                {
                    Timestamp = DateTime.UtcNow
                };
                orderWithdrawalFee.CryptoId = orderData.CryptoId;
                orderWithdrawalFee.Amount   = 0;

                Execute(orderWithdrawalFee);
            }
            else
            {
                var orderWithdrawalFee = CalculateOrderAmount(ref orderData, order, merchantAccount, coin);
                var wallet             = new MerchantWalletDAC().GetByAccountId(merchantAccount.Id, new CryptocurrencyDAC().GetByCode("FIII").Id);
                if (orderWithdrawalFee.Amount != 0)
                {
                    using (var scope = new TransactionScope())
                    {
                        var dbOrder = new OrderDAC().Create(orderData);
                        new UserTransactionDAC().Insert(new UserTransaction
                        {
                            Id           = Guid.NewGuid(),
                            AccountId    = userWallet.UserAccountId,
                            CryptoId     = userWallet.CryptoId,
                            CryptoCode   = userWallet.CryptoCode,
                            Type         = UserTransactionType.Order,
                            DetailId     = dbOrder.Id.ToString(),
                            Status       = (byte)dbOrder.Status,
                            Timestamp    = dbOrder.Timestamp,
                            Amount       = dbOrder.CryptoAmount,
                            OrderNo      = dbOrder.OrderNo,
                            MerchantName = merchantAccount.MerchantName
                        });

                        orderWithdrawalFee.OrderId = dbOrder.Id;
                        var id = new OrderWithdrawalFeeDAC().Insert(orderWithdrawalFee);
                        new MerchantWalletDAC().Decrease(wallet.Id, orderWithdrawalFee.Amount);
                        new MerchantWalletDAC().Increase(merchantWallet.Id, orderData.ActualCryptoAmount);
                        new UserWalletDAC().Decrease(userWallet.Id, cryptoAmount);
                        new UserWalletStatementDAC().Insert(new UserWalletStatement
                        {
                            Action        = UserWalletStatementAction.Consume,
                            Amount        = orderData.CryptoAmount,
                            Balance       = userWallet.Balance - orderData.CryptoAmount,
                            FrozenAmount  = 0,
                            FrozenBalance = userWallet.FrozenBalance,
                            Remark        = null,
                            Timestamp     = DateTime.UtcNow,
                            WalletId      = userWallet.Id
                        });
                        new MerchantWalletStatementDAC().Insert(new MerchantWalletStatement
                        {
                            Action    = MerchantWalletStatementAction.Receipt,
                            Amount    = orderData.ActualCryptoAmount,
                            Balance   = merchantWallet.Balance + orderData.ActualCryptoAmount,
                            Remark    = null,
                            Timestamp = DateTime.UtcNow,
                            WalletId  = merchantWallet.Id
                        });
                        new MerchantWalletStatementDAC().Insert(new MerchantWalletStatement
                        {
                            Action    = MerchantWalletStatementAction.Withdrawal,
                            Amount    = orderWithdrawalFee.Amount,
                            Balance   = merchantWallet.Balance - orderData.ActualCryptoAmount,
                            Remark    = null,
                            Timestamp = DateTime.UtcNow,
                            WalletId  = wallet.Id
                        });
                        scope.Complete();
                    }
                }
                else
                {
                    Execute(orderWithdrawalFee);
                }
            }
            void Execute(OrderWithdrawalFee orderWithdrawalFee)
            {
                using (var scope = new TransactionScope())
                {
                    var dbOrder = new OrderDAC().Create(orderData);
                    new UserTransactionDAC().Insert(new UserTransaction
                    {
                        Id           = Guid.NewGuid(),
                        AccountId    = userWallet.UserAccountId,
                        CryptoId     = userWallet.CryptoId,
                        CryptoCode   = userWallet.CryptoCode,
                        Type         = UserTransactionType.Order,
                        DetailId     = dbOrder.Id.ToString(),
                        Status       = (byte)dbOrder.Status,
                        Timestamp    = dbOrder.Timestamp,
                        Amount       = dbOrder.CryptoAmount,
                        OrderNo      = dbOrder.OrderNo,
                        MerchantName = merchantAccount.MerchantName
                    });
                    orderWithdrawalFee.OrderId = dbOrder.Id;
                    var id = new OrderWithdrawalFeeDAC().Insert(orderWithdrawalFee);
                    new UserWalletDAC().Decrease(userWallet.Id, cryptoAmount);
                    new MerchantWalletDAC().Increase(merchantWallet.Id, orderData.ActualCryptoAmount);
                    new UserWalletStatementDAC().Insert(new UserWalletStatement
                    {
                        Action        = UserWalletStatementAction.Consume,
                        Amount        = orderData.CryptoAmount,
                        Balance       = userWallet.Balance - orderData.CryptoAmount,
                        FrozenAmount  = 0,
                        FrozenBalance = userWallet.FrozenBalance,
                        Remark        = null,
                        Timestamp     = DateTime.UtcNow,
                        WalletId      = userWallet.Id
                    });
                    new MerchantWalletStatementDAC().Insert(new MerchantWalletStatement
                    {
                        Action    = MerchantWalletStatementAction.Receipt,
                        Amount    = orderData.ActualCryptoAmount,
                        Balance   = merchantWallet.Balance + orderData.ActualCryptoAmount,
                        Remark    = null,
                        Timestamp = DateTime.UtcNow,
                        WalletId  = merchantWallet.Id
                    });
                    scope.Complete();
                }
            }

            UserMSMQ.PubOrderPayed(orderData.Id, 0);
            //PushConsume(orderData.Id);
            UserMSMQ.PubConsumeOrder(orderData.Id);

            return(new PayOrderOM
            {
                Amount = orderData.CryptoAmount.ToString(coin.DecimalPlace),
                Currency = new CryptocurrencyDAC().GetById(order.CryptoId).Code,
                OrderId = orderData.Id.ToString(),
                OrderNo = orderData.OrderNo,
                Timestamp = orderData.PaymentTime?.ToUnixTime().ToString()
            });
        }
Пример #25
0
        /// <summary>
        /// 用户主动支付
        /// </summary>
        /// <param name="user"></param>
        /// <param name="im"></param>
        /// <returns></returns>
        public PayOrderOM Pay(UserAccount user, PayIM im)
        {
            if (im.Amount <= 0)
            {
                throw new CommonException(ReasonCode.GENERAL_ERROR, MessageResources.AmountGreater);
            }

            new SecurityComponent().VerifyPin(user, im.Pin);

            var isAllowExpense = user.IsAllowExpense ?? true;

            if (!isAllowExpense)
            {
                throw new CommonException(ReasonCode.Not_Allow_Expense, MessageResources.PaymentForbidden);
            }

            var coin = new CryptocurrencyDAC().GetById(im.CoinId);

            if (!coin.Status.HasFlag(CryptoStatus.Pay) || coin.Enable == 0)
            {
                throw new CommonException(ReasonCode.CURRENCY_FORBIDDEN, MessageResources.CurrencyForbidden);
            }

            var merchantAccount = GetMerchantAccountByIdOrCode(im.MerchantId, im.MerchantCode);

            if (merchantAccount == null)
            {
                throw new CommonException(ReasonCode.INVALID_QRCODE, MessageResources.InvalidQRCode);
            }

            if (!merchantAccount.IsAllowAcceptPayment || merchantAccount.Status == AccountStatus.Locked)
            {
                throw new CommonException(ReasonCode.Not_Allow_AcceptPayment, MessageResources.MerchantExceptionTransClose);
            }

            var country = new CountryComponent().GetById(merchantAccount.CountryId);

            var orderData = new Order
            {
                Id                  = Guid.NewGuid(),
                OrderNo             = IdentityHelper.OrderNo(),
                MerchantAccountId   = merchantAccount.Id,
                CryptoId            = coin.Id,
                CryptoCode          = coin.Code,
                FiatAmount          = im.Amount,
                PaymentType         = im.PaymentType,
                FiatCurrency        = merchantAccount.FiatCurrency,
                Status              = OrderStatus.Completed,
                ExpiredTime         = DateTime.UtcNow.AddMinutes(30),
                Markup              = merchantAccount.Markup,
                ExchangeRate        = GetExchangeRate(merchantAccount.CountryId, merchantAccount.FiatCurrency, coin),
                UnifiedExchangeRate = GetExchangeRate(merchantAccount.CountryId, country.FiatCurrency ?? "USD", coin),
                UnifiedFiatCurrency = country.FiatCurrency ?? "USD",
                MerchantIP          = null,
                PaymentTime         = DateTime.UtcNow,
                UserAccountId       = user.Id,
                Timestamp           = DateTime.UtcNow
            };

            var order = Generate(merchantAccount, coin, country.FiatCurrency ?? "USD", im.Amount, im.PaymentType);

            order.UserAccountId = user.Id;

            var userWallet = new UserWalletDAC().GetByAccountId(user.Id, im.CoinId);

            if (userWallet.Balance < order.CryptoAmount)
            {
                throw new CommonException(ReasonCode.INSUFFICIENT_BALANCE, MessageResources.InsufficientBalance);
            }

            order.Status      = OrderStatus.Completed;
            order.PaymentTime = DateTime.UtcNow;

            var merchantWallet = new MerchantWalletDAC().GetByAccountId(order.MerchantAccountId, order.CryptoId);

            if (merchantWallet == null || !merchantWallet.SupportReceipt)
            {
                throw new ApplicationException(MessageResources.MerchantNotSupperCrypto);
            }

            if (merchantAccount.WithdrawalFeeType != WithdrawalFeeType.FiiiCoin)
            {
                var calcModel =
                    CalculateAmount(im.Amount, merchantAccount.Markup, merchantAccount.Receivables_Tier, orderData.ExchangeRate, coin);

                orderData.ActualFiatAmount   = calcModel.FiatTotalAmount;
                orderData.CryptoAmount       = calcModel.CryptoAmount;
                orderData.TransactionFee     = calcModel.TransactionFee;
                orderData.ActualCryptoAmount = calcModel.ActualCryptoAmount;

                var model = CalculateUnifiedAmount(orderData.CryptoAmount, orderData.ActualCryptoAmount, orderData.UnifiedExchangeRate);
                orderData.UnifiedFiatAmount       = model.UnifiedFiatAmount;
                orderData.UnifiedActualFiatAmount = model.UnifiedActualFiatAmount;
                var orderWithdrawalFee = new OrderWithdrawalFee
                {
                    Timestamp = DateTime.UtcNow,
                    CryptoId  = orderData.CryptoId,
                    Amount    = 0
                };

                Execute(orderWithdrawalFee);
            }
            else
            {
                var orderWithdrawalFee = CalculateOrderAmount(ref orderData, new RedisOrderDTO()
                {
                    CountryId = merchantAccount.CountryId, FiatAmount = im.Amount
                }, merchantAccount, coin);
                var wallet = new MerchantWalletDAC().GetByAccountId(merchantAccount.Id, new CryptocurrencyDAC().GetByCode("FIII").Id);
                if (orderWithdrawalFee.Amount != 0)
                {
                    using (var scope = new TransactionScope())
                    {
                        var dbOrder = new OrderDAC().Create(orderData);
                        new UserTransactionDAC().Insert(new UserTransaction
                        {
                            Id           = Guid.NewGuid(),
                            AccountId    = userWallet.UserAccountId,
                            CryptoId     = userWallet.CryptoId,
                            CryptoCode   = userWallet.CryptoCode,
                            Type         = UserTransactionType.Order,
                            DetailId     = dbOrder.Id.ToString(),
                            Status       = (byte)dbOrder.Status,
                            Timestamp    = dbOrder.Timestamp,
                            Amount       = dbOrder.CryptoAmount,
                            OrderNo      = dbOrder.OrderNo,
                            MerchantName = merchantAccount.MerchantName
                        });
                        orderWithdrawalFee.OrderId = dbOrder.Id;
                        var id = new OrderWithdrawalFeeDAC().Insert(orderWithdrawalFee);

                        new MerchantWalletDAC().Decrease(wallet.Id, orderWithdrawalFee.Amount);
                        new MerchantWalletDAC().Increase(merchantWallet.Id, orderData.ActualCryptoAmount);
                        new UserWalletDAC().Decrease(userWallet.Id, orderData.ActualCryptoAmount);
                        new UserWalletStatementDAC().Insert(new UserWalletStatement
                        {
                            Action        = UserWalletStatementAction.Consume,
                            Amount        = orderData.CryptoAmount,
                            Balance       = userWallet.Balance - orderData.CryptoAmount,
                            FrozenAmount  = 0,
                            FrozenBalance = userWallet.FrozenBalance,
                            Remark        = null,
                            Timestamp     = DateTime.UtcNow,
                            WalletId      = userWallet.Id
                        });
                        new MerchantWalletStatementDAC().Insert(new MerchantWalletStatement
                        {
                            Action    = MerchantWalletStatementAction.Receipt,
                            Amount    = orderData.ActualCryptoAmount,
                            Balance   = merchantWallet.Balance + orderData.ActualCryptoAmount,
                            Remark    = null,
                            Timestamp = DateTime.UtcNow,
                            WalletId  = merchantWallet.Id
                        });
                        new MerchantWalletStatementDAC().Insert(new MerchantWalletStatement
                        {
                            Action    = MerchantWalletStatementAction.Withdrawal,
                            Amount    = orderWithdrawalFee.Amount,
                            Balance   = merchantWallet.Balance - orderData.ActualCryptoAmount,
                            Remark    = null,
                            Timestamp = DateTime.UtcNow,
                            WalletId  = wallet.Id
                        });
                        scope.Complete();
                    }
                }
                else
                {
                    Execute(orderWithdrawalFee);
                }
            }
            void Execute(OrderWithdrawalFee orderWithdrawalFee)
            {
                using (var scope = new TransactionScope())
                {
                    var dbOrder = new OrderDAC().Create(orderData);
                    new UserTransactionDAC().Insert(new UserTransaction
                    {
                        Id           = Guid.NewGuid(),
                        AccountId    = userWallet.UserAccountId,
                        CryptoId     = userWallet.CryptoId,
                        CryptoCode   = userWallet.CryptoCode,
                        Type         = UserTransactionType.Order,
                        DetailId     = dbOrder.Id.ToString(),
                        Status       = (byte)dbOrder.Status,
                        Timestamp    = dbOrder.Timestamp,
                        Amount       = dbOrder.CryptoAmount,
                        OrderNo      = dbOrder.OrderNo,
                        MerchantName = merchantAccount.MerchantName
                    });
                    orderWithdrawalFee.OrderId = dbOrder.Id;
                    var id = new OrderWithdrawalFeeDAC().Insert(orderWithdrawalFee);

                    new UserWalletDAC().Decrease(userWallet.Id, orderData.CryptoAmount);
                    new MerchantWalletDAC().Increase(merchantWallet.Id, orderData.ActualCryptoAmount);
                    new UserWalletStatementDAC().Insert(new UserWalletStatement
                    {
                        Action        = UserWalletStatementAction.Consume,
                        Amount        = orderData.CryptoAmount,
                        Balance       = userWallet.Balance - orderData.CryptoAmount,
                        FrozenAmount  = 0,
                        FrozenBalance = userWallet.FrozenBalance,
                        Remark        = null,
                        Timestamp     = DateTime.UtcNow,
                        WalletId      = userWallet.Id
                    });
                    new MerchantWalletStatementDAC().Insert(new MerchantWalletStatement
                    {
                        Action    = MerchantWalletStatementAction.Receipt,
                        Amount    = orderData.ActualCryptoAmount,
                        Balance   = merchantWallet.Balance + orderData.ActualCryptoAmount,
                        Remark    = null,
                        Timestamp = DateTime.UtcNow,
                        WalletId  = merchantWallet.Id
                    });
                    scope.Complete();
                }
            }

            UserMSMQ.PubOrderPayed(orderData.Id, 0);
            //PushConsume(order.Id);
            UserMSMQ.PubConsumeOrder(orderData.Id);

            return(new PayOrderOM
            {
                Amount = orderData.CryptoAmount.ToString(coin.DecimalPlace),
                Currency = new CryptocurrencyDAC().GetById(order.CryptoId).Code,
                OrderId = orderData.Id.ToString(),
                OrderNo = orderData.OrderNo,
                Timestamp = orderData.PaymentTime?.ToUnixTime().ToString()
            });
        }
        public SignonDTO Signup(int countryId, string cellphone, string merchantAccount, string merchantName, string posSn, string invitationCode, string pin)
        {
            SecurityVerify.Verify <FiiiPosSignUpVerify>(new CustomVerifier("FiiiPosSignUp"), SystemPlatform.FiiiPOS, $"{countryId}:{cellphone}", (model) =>
            {
                return(model.CellphoneVerified);
            });

            var country = new CountryComponent().GetById(countryId);

            if (country == null)
            {
                throw new CommonException(10000, Resources.国家不存在);
            }
            var cacheKey = $"{countryId}{cellphone}";
            var verifier = new FiiiPosRegisterVerifier();
            var dic      = verifier.GetRegisterModel(SystemPlatform.FiiiPOS, cacheKey, false);

            MerchantAccount excistAccount = new MerchantAccountDAC().GetByUsername(merchantAccount);

            if (excistAccount != null)
            {
                throw new CommonException(ReasonCode.ACCOUNT_EXISTS, Resources.帐号已存在);
            }

            UserAccount inviterAccount = new UserAccount();

            if (!string.IsNullOrEmpty(invitationCode))
            {
                inviterAccount = new UserAccountDAC().GetUserAccountByInviteCode(invitationCode);
                if (inviterAccount == null)
                {
                    throw new CommonException(ReasonCode.INVITORCODE_NOT_EXISTS, Resources.邀请码不存在);
                }
            }

            var posDac = new POSDAC();
            var pos    = posDac.GetInactivedBySn(posSn);

            if (pos == null)
            {
                throw new CommonException(ReasonCode.POSSN_ERROR, Resources.SN码不存在);
            }

            var merchantMS = new MasterSettingDAC().SelectByGroup("Merchant");

            Guid            beInvitedAccountId = Guid.NewGuid();
            MerchantAccount account            = new MerchantAccount
            {
                CountryId        = countryId,
                Cellphone        = cellphone,
                Username         = merchantAccount,
                MerchantName     = merchantName,
                PIN              = PasswordHasher.HashPassword(pin),
                Id               = beInvitedAccountId,
                POSId            = pos.Id,
                IsVerifiedEmail  = false,
                PhoneCode        = dic["PhoneCode"],
                RegistrationDate = DateTime.UtcNow,
                Status           = AccountStatus.Active,
                SecretKey        = beInvitedAccountId.ToString(),
                FiatCurrency     = dic["FiatCurrency"],
                Markup           = Convert.ToDecimal(merchantMS.First(e => e.Name == "Merchant_Markup").Value),
                Receivables_Tier = Convert.ToDecimal(merchantMS.First(e => e.Name == "Merchant_TransactionFee").Value),
                //默认开启手机验证
                ValidationFlag = (byte)ValidationFlag.Cellphone,
                InvitationCode = invitationCode
            };

            POSMerchantBindRecord posBindRecord = new POSMerchantBindRecord
            {
                POSId            = pos.Id,
                SN               = pos.Sn,
                MerchantId       = account.Id,
                MerchantUsername = merchantAccount,
                BindTime         = DateTime.UtcNow,
                BindStatus       = (byte)POSBindStatus.Binded
            };

            MerchantProfile profile = new MerchantProfile
            {
                MerchantId     = account.Id,
                Country        = account.CountryId,
                Cellphone      = account.Cellphone,
                L1VerifyStatus = VerifyStatus.Uncertified,
                L2VerifyStatus = VerifyStatus.Uncertified
            };

            MerchantProfileAgent agent = new MerchantProfileAgent();
            bool addProfileResult      = agent.AddMerchant(profile);

            if (!addProfileResult)
            {
                throw new CommonException(ReasonCode.GENERAL_ERROR, "Add merchant profile error.");
            }
            int recordId = default(int);

            try
            {
                using (var scope = new TransactionScope())
                {
                    posDac.ActivePOS(pos);
                    new MerchantAccountDAC().Insert(account);
                    recordId = new POSMerchantBindRecordDAC().Insert(posBindRecord);
                    if (!string.IsNullOrEmpty(invitationCode))
                    {
                        BindInviter(posSn, beInvitedAccountId, inviterAccount.Id, invitationCode);
                    }

                    scope.Complete();
                }
            }
            catch (Exception ex)
            {
                agent.RemoveMerchantById(profile);

                //LogHelper.Error(ex);
                throw;
            }

            if (!string.IsNullOrEmpty(invitationCode))
            {
                RabbitMQSender.SendMessage("InvitePosBindSuccess", new Tuple <Guid, long>(inviterAccount.Id, recordId));
            }

            verifier.DeleteCacheModel(SystemPlatform.FiiiPOS, cacheKey);

            return(GetAccessToken(pos, account));
        }
Пример #27
0
        public void SendSecurityValidateCellphoneCode(UserAccount user, string code)
        {
            var country = new CountryComponent().GetById(user.CountryId);

            SecurityVerify.SendCode(new MandatoryCellphoneVerifier(), SystemPlatform.FiiiPay, code + user.Id, $"{country.PhoneCode}{user.Cellphone}");
        }
Пример #28
0
        public TransferOM Transfer(UserAccount account, TransferIM im)
        {
            SecurityVerify.Verify(new PinVerifier(), SystemPlatform.FiiiPay, account.Id.ToString(), account.Pin, im.Pin);
            if (account.L1VerifyStatus != VerifyStatus.Certified)
            {
                throw new ApplicationException();
            }
            if (account.IsAllowTransfer.HasValue && !account.IsAllowTransfer.Value)
            {
                throw new CommonException(ReasonCode.TRANSFER_FORBIDDEN, MessageResources.TransferForbidden);
            }
            var toAccount = new UserAccountDAC().GetByCountryIdAndCellphone(im.ToCountryId, im.ToCellphone);

            if (toAccount == null)
            {
                throw new CommonException(ReasonCode.ACCOUNT_NOT_EXISTS, MessageResources.AccountNotExist);
            }
            if (toAccount.IsAllowTransfer.HasValue && !toAccount.IsAllowTransfer.Value)
            {
                throw new CommonException(ReasonCode.TRANSFER_FORBIDDEN, MessageResources.ToAccountTransferForbidden);
            }
            if (im.Amount >= Convert.ToDecimal(Math.Pow(10, 11)))
            {
                throw new CommonException(ReasonCode.TRANSFER_AMOUNT_OVERFLOW, MessageResources.TransferAmountOverflow);
            }
            var currency = new CryptocurrencyDAC().GetById(im.CoinId);

            if (!currency.Status.HasFlag(CryptoStatus.Transfer) || currency.Enable == 0)
            {
                throw new CommonException(ReasonCode.CURRENCY_FORBIDDEN, MessageResources.CurrencyForbidden);
            }
            if (im.Amount < (decimal)Math.Pow(10, -currency.DecimalPlace))
            {
                throw new CommonException(ReasonCode.TRANSFER_AMOUNT_OVERFLOW, MessageResources.TransferAmountTooSmall);
            }
            var decimalDigits = im.Amount.ToString().Length - im.Amount.ToString().IndexOf('.') - 1;

            if (decimalDigits > currency.DecimalPlace)
            {
                throw new CommonException(ReasonCode.TRANSFER_AMOUNT_OVERFLOW, MessageResources.TransferAmountOverflow);
            }

            if (account.Id == toAccount.Id)
            {
                throw new CommonException(ReasonCode.TRANSFER_TO_SELF, MessageResources.TransferToSelf);
            }

            var uwComponent = new UserWalletComponent();

            var toWallet = uwComponent.GetUserWallet(toAccount.Id, im.CoinId);

            if (toWallet == null)
            {
                toWallet = uwComponent.GenerateWallet(toAccount.Id, currency.Id);
            }

            var      country      = new CountryComponent().GetById(im.ToCountryId);
            DateTime dtCreateTime = DateTime.UtcNow;

            var fromWallet = uwComponent.GetUserWallet(account.Id, im.CoinId);

            if (fromWallet.Balance < im.Amount)
            {
                throw new CommonException(ReasonCode.TRANSFER_BALANCE_LOW, MessageResources.TransferBalanceLow);
            }

            UserTransfer transfer = new UserTransfer
            {
                Timestamp         = dtCreateTime,
                OrderNo           = CreateOrderno(),
                FromUserAccountId = account.Id,
                FromUserWalletId  = fromWallet.Id,
                CoinId            = currency.Id,
                CoinCode          = currency.Code,
                ToUserAccountId   = toAccount.Id,
                ToUserWalletId    = toWallet.Id,
                Amount            = im.Amount,
                Status            = (byte)TransactionStatus.Confirmed
            };

            var uwDAC  = new UserWalletDAC();
            var uwsDAC = new UserWalletStatementDAC();
            var utDAC  = new UserTransactionDAC();

            //var pushComponent = new FiiiPayPushComponent();
            using (var scope = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, new TimeSpan(0, 0, 1, 30)))
            {
                transfer.Id = new UserTransferDAC().Insert(transfer);

                utDAC.Insert(new UserTransaction
                {
                    Id         = Guid.NewGuid(),
                    AccountId  = transfer.FromUserAccountId,
                    CryptoId   = transfer.CoinId,
                    CryptoCode = transfer.CoinCode,
                    Type       = UserTransactionType.TransferOut,
                    DetailId   = transfer.Id.ToString(),
                    Status     = transfer.Status,
                    Timestamp  = dtCreateTime,
                    Amount     = transfer.Amount,
                    OrderNo    = transfer.OrderNo
                });

                utDAC.Insert(new UserTransaction
                {
                    Id         = Guid.NewGuid(),
                    AccountId  = transfer.ToUserAccountId,
                    CryptoId   = transfer.CoinId,
                    CryptoCode = transfer.CoinCode,
                    Type       = UserTransactionType.TransferIn,
                    DetailId   = transfer.Id.ToString(),
                    Status     = transfer.Status,
                    Timestamp  = dtCreateTime,
                    Amount     = transfer.Amount,
                    OrderNo    = transfer.OrderNo
                });

                uwDAC.Decrease(fromWallet.Id, transfer.Amount);
                uwDAC.Increase(toWallet.Id, transfer.Amount);

                uwsDAC.Insert(new UserWalletStatement
                {
                    WalletId      = fromWallet.Id,
                    Action        = UserWalletStatementAction.TansferOut,
                    Amount        = -transfer.Amount,
                    Balance       = fromWallet.Balance - transfer.Amount,
                    FrozenAmount  = 0,
                    FrozenBalance = fromWallet.FrozenBalance,
                    Timestamp     = dtCreateTime
                });

                uwsDAC.Insert(new UserWalletStatement
                {
                    WalletId      = toWallet.Id,
                    Action        = UserWalletStatementAction.TansferIn,
                    Amount        = transfer.Amount,
                    Balance       = toWallet.Balance + transfer.Amount,
                    FrozenAmount  = 0,
                    FrozenBalance = toWallet.FrozenBalance,
                    Timestamp     = dtCreateTime
                });

                scope.Complete();
            }

            RabbitMQSender.SendMessage("UserTransferOutFiiiPay", transfer.Id);
            RabbitMQSender.SendMessage("UserTransferIntoFiiiPay", transfer.Id);
            //pushComponent.PushTransferOut(transfer.Id);
            //pushComponent.PushTransferInto(transfer.Id);

            return(new TransferOM
            {
                Timestamp = dtCreateTime.ToUnixTime().ToString(),
                TracingId = transfer.Id,
                TracingNo = transfer.OrderNo,
                AccountName = country.PhoneCode + " " + toAccount.Cellphone
            });
        }