手机验证码

手机验证码用的是第三方的:云片(需要花钱)https://www.yunpian.com/

需要去云片网注册+审核自己做需要的模板。

引用:


using Yunpian.Sdk;
using Yunpian.Sdk.Model;

方法实现:

 /// <summary>
        /// 1、手机验证码
        /// </summary>
        /// <param name="Mobile">手机号码</param>
        /// <returns></returns>
        [HttpPost]
        [Route("PhoneCaptcha/{Mobile}")]
        public string PhoneCaptcha([FromRoute] string Mobile)
        {
            if (!ModelState.IsValid)
            {
                return APIResult.Error("数据格式错误");
            }

            //初始化clnt,使用单例方式
            var clnt = new YunpianClient("").Init();//这里写注册云片网所给的APIKEY
            string Code = MobileCode();//调用自己写的随机数方法
            //发送短信API
            var param = new Dictionary<string, string>
            {
                [Const.Mobile] = Mobile,
                [Const.Text] = "【云片网】您的验证码是" + Code//要与模板一致
            };
            var r = clnt.Sms().SingleSend(param);
            if (r.Code == 33)
            {
                clnt.Dispose();
                return APIResult.Error("验证码发送失败,请等待30秒后重新发送!");
            }
            else if (r.Code == 22)
            {
                clnt.Dispose();
                return APIResult.Error("验证码发送失败,请等待1个小时后重新发送!");
            }
            else if (r.Code == 17)
            {
                clnt.Dispose();
                return APIResult.Error("验证码发送失败,请等待24个小时后重新发送!");
            }
            else if (r.Code == 0)
            {
                clnt.Dispose();
                return  Code;
            }
            else
            {
                clnt.Dispose();
                Code="验证码发送失败,请重新发送!";
                return Code;
            }
            //获取返回结果, 返回码:r.Code, 返回码描述:r.Msg, API结果:r.Data, 其他说明:r.Detail, 调用异常:r.E
            //账户:clnt.User().* 签名:clnt.Sign().* 模版:clnt.Tpl().* 短信:clnt.Sms().* 视频短信:clnt.VideoSms().* 语音:clnt.Voice().* 短链接:clnt.ShortUrl().*
            //释放clnt
        }

手机验证码生成随机数:

/// <summary>
        /// 手机随机验证码
        /// </summary>
        /// <returns></returns>
        private string MobileCode()
        {
            string RandomCode = "";

            for (int i = 0; i < 4; i++)
            {
                //获取随机数的方法
                Random rand = new Random();

                int RandKey = rand.Next(0, 10);
                RandomCode += RandKey.ToString();
            }
            return RandomCode;
        }

猜你喜欢

转载自blog.csdn.net/zhx2011341124/article/details/81745720