Exemple #1
0
        protected override void Operator(JObject data, DemoDbContext db)
        {
            //判断是否邮箱是否已经注册
            if (dataControls[DataFactoryName.IsExistUA].Operate(data, db) != null)
            {
                code = 1002;
                return;
            }

            //判断是否已经收到注册链接
            if (dataControls[DataFactoryName.IsExistTRD].Operate(data, db) != null)
            {
                code = 1003;
                return;
            }

            string validataCode = RandomCode.GetLetterAndNumber(8);

            data.Add(IVN.ValidataCode, validataCode);

            //将邮箱和临时验证码存入数据库
            if (dataControls[DataFactoryName.AddApplyTRD].Operate(data, db) == null)
            {
                code = 1004;
                return;
            }

            //发送注册链接
            BaseSendEmail sendRigister = new SendRegisterEmail();

            sendRigister.Send(data[IVN.Email].ToString(), validataCode);

            return;
        }
        public async Task <ResultObject> Demo1()
        {
            try
            {
                SystemUserEntity model = new SystemUserEntity
                {
                    Id         = Guid.NewGuid(),
                    Salt       = RandomCode.Number(6, true),
                    IsDelete   = 0,
                    CreateTime = DateTime.Now,
                    LoginName  = "123123",
                    LoginPwd   = "123123",
                    NickName   = "123123",
                    UpdateTime = DateTime.Now
                };
                //var ss = await _user.Insert(model);
                var ss = await _sUser.Insert(model);

                return(Success(ss));
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Exemple #3
0
        /// <summary>
        /// JS-SDK里面的wx.chooseWXPay()发起一个微信支付请求参数
        /// </summary>
        /// <param name="prepay_id">统一支付接口返回的prepay_id参数值</param>
        /// <param name="time">当前时间</param>
        /// <returns></returns>
        public static chooseWXPayModel chooseWXPay(string prepay_id, DateTime time)
        {
            /*
             * paySign 采用统一的微信支付 Sign 签名生成方法,注意这里 appId 也要参与签名,appId 与 config 中传入的 appId 一致。
             * 即最后参与签名的参数有appId, timeStamp, nonceStr, package, signType。
             */
            chooseWXPayModel chooseWXPay = new chooseWXPayModel();

            chooseWXPay.timestamp = Common.ConvertTime(time);
            chooseWXPay.nonceStr  = RandomCode.createRandomCode(16, true);
            chooseWXPay.package   = "prepay_id=" + prepay_id;
            chooseWXPay.signType  = "MD5";
            chooseWXPay.paySign   = "";

            Dictionary <string, string> chooseWXPayParams = new Dictionary <string, string>();

            chooseWXPayParams.Add("appId", Privacy.AppId);
            chooseWXPayParams.Add("timeStamp", chooseWXPay.timestamp.ToString());
            chooseWXPayParams.Add("nonceStr", chooseWXPay.nonceStr);
            chooseWXPayParams.Add("package", chooseWXPay.package);
            chooseWXPayParams.Add("signType", chooseWXPay.signType);

            string sign    = "";
            string package = GetPackage(chooseWXPayParams, out sign);

            chooseWXPay.paySign = sign;
            return(chooseWXPay);
        }
Exemple #4
0
        public async Task <ActionResult> ResetPassword(ResetPasswordViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            var user = await UserManager.FindByNameAsync(model.Email);

            if (user == null)
            {
                // Don't reveal that the user does not exist
                return(RedirectToAction("ResetPasswordConfirmation", "Account", new { statuscode = "Faile" }));
            }
            var result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password);

            if (result.Succeeded)
            {
                //each process hava a randomcode , just use onetime.
                var tempCodeStatus = new RandomCode().RandomCodeGenral(28, true);
                TempData["TempCodeStatus"] = tempCodeStatus;
                return(RedirectToAction("ResetPasswordConfirmation", "Account", new { statuscode = tempCodeStatus, id = user.Id }));
            }
            AddErrors(result);
            return(View());
        }
Exemple #5
0
        /// <summary>生成动态匿名调用内部方法(参数由TArg转为实际类型后调用,并将调用返回值转为TRes)</summary>
        public ApiFunc CreateMethod()
        {
            var dynamicMethod = new DynamicMethod($"{Method.Name}_{RandomCode.Generate(6)}"
                                                  , typeof(object), new[]
            {
                typeof(IInlineMessage),
                typeof(ISerializeProxy),
                typeof(object)
            });

            ilGenerator = dynamicMethod.GetILGenerator();

            //如果修补操作码,则填充空间。 尽管可能消耗处理周期,但未执行任何有意义的操作。
            ilGenerator.Emit(OpCodes.Nop);
            //构造
            Ctor();
            //构造属性
            Properties();
            //调用方法 controler.Api();
            Call();
            //对对象调用后期绑定方法,并且将返回值推送到计算堆栈上。
            Result();

            return(dynamicMethod.CreateDelegate(typeof(ApiFunc)) as ApiFunc);
        }
Exemple #6
0
        internal RandomCode GetRandomCode(int state = 0)
        {
            var cmd = sqlHelper.PrepareTextSqlCommand(GetModelSql);

            cmd.AddParam("@State", state);
            //return cmd.ExecSingleReader<RandomCode>(reader => new RandomCode
            //{
            //    Id = reader.GetValue<int>("ID"),
            //    Code = reader.GetValue<int>("code"),
            //    State = reader.GetValue<int>("state")
            //});
            try
            {
                using (var reader = cmd.ExecuteReader())
                {
                    var infomodel = new RandomCode();
                    while (reader.Read())
                    {
                        infomodel.Id    = (int)reader["Id"];
                        infomodel.Code  = (int)reader["Code"];
                        infomodel.State = (int)reader["State"];
                    }

                    return(infomodel);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemple #7
0
        internal List <RandomCode> GetAllTotalRandomCode()
        {
            var randomcmd = sqlHelper.PrepareTextSqlCommand("SELECT   [id],[code],[state] FROM [EtownDB].[dbo].[RandomCode]");

            try
            {
                using (var reader = randomcmd.ExecuteReader())
                {
                    var randomlist = new List <RandomCode>();
                    while (reader.Read())
                    {
                        var infomodel = new RandomCode();
                        infomodel.Id    = (int)reader["Id"];
                        infomodel.Code  = (int)reader["Code"];
                        infomodel.State = (int)reader["State"];

                        randomlist.Add(infomodel);
                    }

                    return(randomlist);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemple #8
0
        /// <summary>
        /// 获取验证码
        /// </summary>
        /// <returns></returns>
        public ActionResult GetValidateCode()
        {
            RandomCode randomCode = new RandomCode();
            string     code       = randomCode.CreateValidateCode(6);

            Session["ValidateCode"] = code;
            byte[] bytes = randomCode.CreateValidateGraphic(code);
            return(File(bytes, @"image/jpeg"));
        }
Exemple #9
0
 internal string GetAESKey()
 {
     if (AESKey == null)
     {
         AESKey  = RandomCode.Generate(16, RandomCode.RandomCodeType.HighLetterAndNumber).ToLower();
         aes.Key = Encoding.UTF8.GetBytes(AESKey);
     }
     return(AESKey);
 }
Exemple #10
0
        /// <summary>
        /// 微信红包支付
        /// </summary>
        /// <returns></returns>
        public static string GetBonus(string CurrentWXID, string act_id, string act_name, int money, string wishing, string remark, string nick_name, string send_name)
        {
            //构建微信红包接口参数对象
            BonusModel bonusModel = new BonusModel()
            {
                sign         = "",
                mch_billno   = Privacy.PartnerID + DateTime.Now.ToString("yyyyMMdd") + GetTenRandomNum(),
                mch_id       = Privacy.PartnerID,
                wxappid      = Privacy.AppId,
                nick_name    = nick_name,
                send_name    = send_name,
                re_openid    = CurrentWXID,
                total_amount = money,
                min_value    = money,
                max_value    = money,
                total_num    = 1,
                wishing      = wishing,
                client_ip    = System.Configuration.ConfigurationManager.AppSettings["serverIP"].ToString(),              //"219.234.83.88",
                act_name     = act_name,
                act_id       = act_id,
                remark       = remark,
                nonce_str    = RandomCode.createRandomCode(16, true),
            };
            Dictionary <string, string> singWXBonusParams = new Dictionary <string, string>();

            singWXBonusParams.Add("nonce_str", bonusModel.nonce_str);
            singWXBonusParams.Add("mch_billno", bonusModel.mch_billno);
            singWXBonusParams.Add("mch_id", bonusModel.mch_id);
            singWXBonusParams.Add("wxappid", bonusModel.wxappid);
            singWXBonusParams.Add("nick_name", bonusModel.nick_name);
            singWXBonusParams.Add("send_name", bonusModel.send_name);
            singWXBonusParams.Add("re_openid", bonusModel.re_openid);
            singWXBonusParams.Add("total_amount", bonusModel.total_amount.ToString());
            singWXBonusParams.Add("min_value", bonusModel.min_value.ToString());
            singWXBonusParams.Add("max_value", bonusModel.max_value.ToString());
            singWXBonusParams.Add("total_num", bonusModel.total_num.ToString());
            singWXBonusParams.Add("wishing", bonusModel.wishing);
            singWXBonusParams.Add("client_ip", bonusModel.client_ip);
            singWXBonusParams.Add("act_name", bonusModel.act_name);
            singWXBonusParams.Add("remark", bonusModel.remark);
            singWXBonusParams.Add("act_id", bonusModel.act_id);
            string sign    = "";
            string package = GetPackage(singWXBonusParams, out sign);

            bonusModel.sign = sign;
            string tempxmlstr = WeChatHelper4Net.XmlHelper.Serialize(bonusModel);
            string xml        = tempxmlstr.Substring(tempxmlstr.IndexOf("<sign>"));

            xml = "<xml>" + xml;
            //调用微信红包接口,支付用户红包奖金
            string resultXml = Send(xml, "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack");

            //处理接口返回数据
            resultXml = resultXml.Replace("<xml>", "<BonusResultModel>").Replace("</xml>", "</BonusResultModel>");
            return(resultXml);
        }
        public ActionResult CreateGroup()
        {
            if (User.Identity.GetAccountType().Equals("Student"))
            {
                return(RedirectToAction("UserHome", controllerName: "User"));
            }
            string GroupID = RandomCode.RandomString(6);

            return(View());
        }
        public Test_SweetStream()
        {
            SweetStream sw = new SweetStream();

            while (true)
            {
                MemoryStream memoryStream = new MemoryStream();

                for (int i = 1; i <= 1000; i++)
                {
                    byte[] b = sw.Encode(Encoding.UTF8.GetBytes(RandomCode.Generate(new Random().Next(1, 5000))));
                    // byte[] b = sw.Encode(Encoding.UTF8.GetBytes("a"));
                    int size = 128 - memoryStream.ToArray().Length;
                    if (size > 0)
                    {
                        int sss = size - b.Length;
                        if (sss >= 0)
                        {
                            memoryStream.Write(b);
                        }
                        else
                        {
                            memoryStream.Write(b, 0, size);
                            sw.Decode(memoryStream.ToArray());
                            memoryStream = new MemoryStream();
                            memoryStream.Write(b, size, -sss);
                        }
                    }
                    else
                    {
                        sw.Decode(memoryStream.ToArray());
                        memoryStream = new MemoryStream();
                        memoryStream.Write(b);
                    }
                }

                if (memoryStream.ToArray().Length > 0)
                {
                    sw.Decode(memoryStream.ToArray());
                }

                int    count = 0;
                byte[] r     = sw.TakeStreamBuffer();
                do
                {
                    count++;
                    Console.WriteLine(Encoding.UTF8.GetString(r));
                    r = sw.TakeStreamBuffer();
                } while (r != null);
                Console.WriteLine("all:" + count);

                Thread.Sleep(100);
                Console.ReadKey();
            }
        }
Exemple #13
0
        private VCodeImgModel CreateVCodeImg()
        {
            VCodeImgModel rtnResult = new VCodeImgModel {
                VCodePos = new List <PointPosModel>()
            };
            string code = RandomCode.Create(this._options);

            rtnResult = VCodeImage.Create(code, 200, 200, this._options);

            return(rtnResult);
        }
Exemple #14
0
 public void GetLetterAndNumberTest()
 {
     if (RandomCode.GetLetterAndNumber(8).Length == 8)
     {
         Assert.Pass();
     }
     else
     {
         Assert.Fail();
     }
 }
Exemple #15
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Expires = -1;
            width            = URLHelper.GetRequestQuery <int>("w", width, Convert.ToInt32);
            height           = URLHelper.GetRequestQuery("h", height, Convert.ToInt32);
            //string checkCode = CreateRandomCode(4);
            string checkCode = RandomCode.GetRandomCode(StringPlus.NumberConst, 4);

            Session["CheckCode"] = checkCode;             //checkCode;
            RandomCode.ResopnseColorImage(Context, width, height, checkCode);
            //CreateImage(checkCode);
        }
        public ActionResult JoinGroup(JoinGroupModels models)
        {
            var checkclassid =
                from c in _context.UserClass
                where c.ClassID == models.ClassID
                select new
            {
                Classid = c.ClassID
            };

            if (!checkclassid.Any())
            {
                ModelState.AddModelError("JoinDupGroupNotExist", errorMessage: "Class Doesn't Exist. Please enter new Class ID");
                return(View(models));
            }
            models.StudentID   = User.Identity.GetUserId();
            models.classdetail = RandomCode.RandomString(10);
            UserInClass iin = new UserInClass()
            {
                StudentID = models.StudentID, ClassID = models.ClassID
            };

            iin.classdetail = models.classdetail;
            var query =
                from dup in _context.UserInClasses
                where (dup.ClassID == models.ClassID && dup.StudentID == models.StudentID)
                select new
            {
                dupname = dup.StudentID
            };

            foreach (var i in query)
            {
                if (i.dupname == models.StudentID)
                {
                    ModelState.AddModelError("JoinDupGroupError", errorMessage: "You Already Join This Group");
                    return(View(models));
                }
            }

            try
            {
            }
            catch (Exception)
            {
                ModelState.AddModelError("JoinGroupError", errorMessage: "Cannot Join Group At This Time");
                return(View(models));
            }
            _context.UserInClasses.Add(iin);
            _context.SaveChanges();
            return(RedirectToAction("StudentGroupView"));
        }
Exemple #17
0
        public int InsertOrUpdateRandomCode(RandomCode model)
        {
            var cmd = sqlHelper.PrepareStoredSqlCommand(SQLInsertOrUpdate);

            cmd.AddParam("@Id", model.Id);
            cmd.AddParam("@Code", model.Code);
            cmd.AddParam("@State", model.State);

            var parm = cmd.AddReturnValueParameter("ReturnValue");

            cmd.ExecuteNonQuery();
            return((int)parm.Value);
        }
Exemple #18
0
        private string CreateRandomCode(string routeCode, PasswordOptions passwordOptions)
        {
            // Create random code
            string randomCode = RandomCode.Generate(passwordOptions);

            // Verify if random codes already exists with this route
            if (_context.AuthorizationCodes.Any(x => x.Route == routeCode && x.Code == randomCode))
            {
                // Generate a brand new random code
                return(CreateRandomCode(routeCode, passwordOptions));
            }

            return(randomCode);
        }
Exemple #19
0
 public int InsertOrUpdate(RandomCode randomcode)
 {
     using (var sql = new SqlHelper())
     {
         try
         {
             var internalData = new InternalRandomCode(sql);
             int result       = internalData.InsertOrUpdateRandomCode(randomcode);
             return(result);
         }
         catch
         {
             throw;
         }
     }
 }
Exemple #20
0
 public RandomCode GetRandomCodeByCode(int codee)
 {
     using (var sql = new SqlHelper())
     {
         try
         {
             var        internalData = new InternalRandomCode(sql);
             RandomCode code         = internalData.GetRandomCodeByCode(codee);
             return(code);
         }
         catch (Exception ex)
         {
             throw ex;
         }
     }
 }
Exemple #21
0
 public RandomCode GetRandomCode(int state = 0)
 {
     using (var sql = new SqlHelper())
     {
         RandomCode code = new RandomCode();
         try
         {
             var internalData = new InternalRandomCode(sql);
             code = internalData.GetRandomCode();
             return(code);
         }
         catch (Exception ex)
         {
             throw ex;
         }
     }
 }
Exemple #22
0
        internal List <RandomCode> getRandomCodeList(int topnum)
        {
            var randomcmd = sqlHelper.PrepareTextSqlCommand("SELECT TOP " + topnum + " [id],[code],[state] FROM [EtownDB].[dbo].[RandomCode] where [state]=0  order by id asc");

            try
            {
                var randomlist = new List <RandomCode>();
                using (var reader = randomcmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        var infomodel = new RandomCode();
                        infomodel.Id    = (int)reader["Id"];
                        infomodel.Code  = (int)reader["Code"];
                        infomodel.State = (int)reader["State"];

                        randomlist.Add(infomodel);
                    }
                }
                if (randomlist != null)
                {
                    if (randomlist.Count > 0)
                    {
                        foreach (RandomCode r in randomlist)
                        {
                            r.State = 1;
                            InsertOrUpdateRandomCode(r);
                        }
                        return(randomlist);
                    }
                    else
                    {
                        return(null);
                    }
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemple #23
0
        public async Task <AddPresentationPayload> AddPresentationAsync(
            AddPresentationInput input,
            [Service] AppDbContext context)
        {
            var presentation = new PresentationModel
            {
                Name              = input.Name,
                Code              = RandomCode.Get(),
                HasStarted        = false,
                NumberOfSlides    = 5,
                CurrentSlideIndex = 0
            };

            context.Presentations.Add(presentation);
            await context.SaveChangesAsync();

            return(new AddPresentationPayload(presentation));
        }
        public Test_RandomCode()
        {
            Console.WriteLine("HighLowLetterAndNumberAndSymbol:");
            Console.WriteLine(RandomCode.Generate(32, RandomCode.RandomCodeType.HighLowLetterAndNumberAndSymbol));
            Console.WriteLine("HighLowLetterAndNumber:");
            Console.WriteLine(RandomCode.Generate(32, RandomCode.RandomCodeType.HighLowLetterAndNumber));
            Console.WriteLine("HighLetterAndNumber:");
            Console.WriteLine(RandomCode.Generate(32, RandomCode.RandomCodeType.HighLetterAndNumber));
            Console.WriteLine("HighLetter:");
            Console.WriteLine(RandomCode.Generate(32, RandomCode.RandomCodeType.HighLetter));
            Console.WriteLine("Number:");
            Console.WriteLine(RandomCode.Generate(32, RandomCode.RandomCodeType.Number));

            Console.WriteLine("Guid[no line]:");
            Console.WriteLine(RandomCode.GenerateGuid(false));
            Console.WriteLine("Guid:");
            Console.WriteLine(RandomCode.GenerateGuid(true));
        }
Exemple #25
0
        /// <summary>
        /// 生成二维码的随机码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Button1_Click(object sender, EventArgs e)
        {
            int totalnum = 0;
            IList <RandomCode> totallist = new RandomCodeData().GetAllTotalRandomCode();

            if (totallist == null)
            {
                totalnum = 0;
            }
            else
            {
                totalnum = totallist.Count;
            }


            for (int i = 0; i < 20000000 - totalnum; i++)
            {
                int codeeee = CreateNum();

                RandomCode randddd = new RandomCodeData().GetRandomCodeByCode(codeeee);
                if (randddd == null)
                {
                    RandomCode randomm = new RandomCode
                    {
                        Id    = 0,
                        Code  = codeeee,
                        State = 0
                    };
                    try
                    {
                        int identity = new RandomCodeData().InsertOrUpdate(randomm);
                    }
                    catch (Exception ex)
                    {
                        i--;
                    }
                }
                else
                {
                    i--;
                }
            }
            Label1.Text = "20000000已经插入";
        }
Exemple #26
0
 private void RandomCodeButton1_Click(object sender, EventArgs e)
 {
     if (String.IsNullOrWhiteSpace(tbLength.Text) || String.IsNullOrWhiteSpace(tbInclude.Text))
     {
         WarningNotice.Null();
         return;
     }
     if (!int.TryParse(tbLength.Text, out _))
     {
         if (long.TryParse(tbLength.Text, out _))
         {
             WarningNotice.IsLongType();
             return;
         }
         WarningNotice.NotNumber();
         return;
     }
     tbRandomCodeResult.Text = RandomCode.GetRandomString(int.Parse(tbLength.Text), tbInclude.Text);
 }
Exemple #27
0
        /// <summary>
        /// 获取JS-SDK配置信息
        /// </summary>
        /// <param name="AppId">AppId为空时默认取配置文件appSettings节点key=WeChatAppId</param>
        /// <param name="jsapi_ticket">jsapi_ticket</param>
        /// <param name="url">url(当前网页的URL,不包含#及其后面部分,要用Request.Url.AbsoluteUri,否则会存在编码问题)</param>
        /// <returns></returns>
        public static Models.JSSDK.JSSDKConfig GetConfig(string AppId, string jsapi_ticket, string url)
        {
            if (string.IsNullOrWhiteSpace(jsapi_ticket))
            {
                throw new ArgumentNullException(nameof(jsapi_ticket));
            }
            if (string.IsNullOrWhiteSpace(url))
            {
                throw new ArgumentNullException(nameof(url));
            }
            AppId = string.IsNullOrWhiteSpace(AppId) ? Privacy.AppId : AppId;

            Models.JSSDK.JSSDKConfig config = new Models.JSSDK.JSSDKConfig();
            config.appId     = AppId;
            url              = Common.CleanUrl(url);                  //移除url里面#及#后面的部分
            config.timestamp = Common.ConvertTime(DateTime.Now);
            config.nonceStr  = RandomCode.createRandomCode(16, true); //生成16位随机字符串,数字,大写英文字母,小写英文字母

            /*
             * 关于URL编码导致签名错误的问题:
             * 微信建议:确认url是页面完整的url(请在当前页面alert(location.href.split('#')[0])确认),包括'http(s)://'部分,以及'?'后面的GET参数部分,但不包括'#'hash后面的部分。
             * 注意必须以http://或https://开头,分别支持80端口和443端口。其它协议或端口都不行!
             */

            /*
             * 对所有待签名参数按照字段名的ASCII 码从小到大排序(字典序)后,使用URL键值对的格式(即key1=value1&key2=value2…)拼接成字符串string1。
             * 这里需要注意的是所有参数名均为小写字符。对string1作sha1加密,字段名和字段值都采用原始值,不进行URL 转义。
             */
            Dictionary <string, string> WeiXinUrlParameters = new Dictionary <string, string>();

            WeiXinUrlParameters.Add("jsapi_ticket", jsapi_ticket);
            WeiXinUrlParameters.Add("noncestr", config.nonceStr);
            WeiXinUrlParameters.Add("timestamp", config.timestamp.ToString());
            WeiXinUrlParameters.Add("url", url);
            string stringTemp = WeiXinUrlParameters.Sort().ToURLParameter();

            /*
             * 对string1进行sha1签名,得到signature
             */
            config.signature = Common.SHA1Encrypt(stringTemp);
            return(config);
        }
        private CuponCode CreateCupon(string userid)
        {
            var tempUser = _dbBCDH.Invoices.Where(x => x.ID_Account == userid && x.Payment_Methods != "PayForAccount").FirstOrDefault();

            if (tempUser != null)
            {
                return(null);
            }
            else
            {
                var       dateCreate = DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss");
                var       code       = new RandomCode().RandomNumber(8);
                CuponCode tempCode   = new CuponCode {
                    Code = code, ContentCode = "KMFristTimeBuy", CreateDate = Convert.ToDateTime(dateCreate), NumberUse = 1, PercentSale = 10, ValueSale = 0, EndDate = Convert.ToDateTime(dateCreate).AddDays(7)
                };
                _dbBCDH.Entry(tempCode).State = System.Data.Entity.EntityState.Added;
                _dbBCDH.SaveChanges();
                return(tempCode);
            }
        }
Exemple #29
0
        /// <summary>
        /// Generates token by given model.
        /// Validates whether the given model is valid, then gets the symmetric key.
        /// Encrypt the token and returns it.
        /// </summary>
        /// <param name="model"></param>
        /// <returns>Generated token.</returns>
        public string GenerateToken(PaymentWithBKOnline paymentModel)
        {
            var TockenID       = new RandomCode().RandomNumber(4);
            var ExpireSeconds  = 60;
            var SecretKeyValue = ConfigurationManager.AppSettings["SecretKey"];
            var APIKey         = ConfigurationManager.AppSettings["AppKey"];
            var payload        = new Dictionary <string, object>
            {
                { "iss", APIKey },
                { "iat", DateTimeOffset.Now.ToUnixTimeSeconds() },
                { "exp", DateTimeOffset.Now.AddSeconds(ExpireSeconds).ToUnixTimeSeconds() },
                { "jti", TockenID },
                { "form_params", paymentModel }
            };
            IJwtAlgorithm     algorithm  = new HMACSHA256Algorithm();
            IJsonSerializer   serializer = new JsonNetSerializer();
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            IJwtEncoder       encoder    = new JwtEncoder(algorithm, serializer, urlEncoder);
            var token = encoder.Encode(payload, SecretKeyValue);

            return(token);
        }
Exemple #30
0
        public ActionResult WebHookResult(HttpContext context)
        {
            var jsonSerialzer = new JavaScriptSerializer();
            var jsonString    = string.Empty;

            context.Request.InputStream.Position = 0;
            using (var inputStream = new StreamReader(context.Request.InputStream))
            {
                jsonString = inputStream.ReadToEnd();
            }
            var data = new PaymentWebWook();

            data = jsonSerialzer.Deserialize <PaymentWebWook>(jsonString);
            var        number_ramdom = new RandomCode().RandomNumber(2);
            LinkSystem mg            = new LinkSystem {
                ID_LinkSystem = Convert.ToInt32(number_ramdom)
            };

            _dbBCDH.Entry(mg).State = System.Data.Entity.EntityState.Added;
            _dbBCDH.SaveChanges();
            return(new EmptyResult());
        }