融云发送手机短信验证短信(.net版本)_.NET_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > .NET > 融云发送手机短信验证短信(.net版本)

融云发送手机短信验证短信(.net版本)

 2017/2/12 5:30:48  Rexcnblog  程序员俱乐部  我要评论(0)
  • 摘要:首先本次需求是在MVC5中进行的,那么先添加WEBAPI的接口usingSystem;usingSystem.Web.Http;usingSystem.Net.Http;usingSystem.Web.Script.Serialization;usingSystem.Text;usingSystem.Web;namespaceBlackNails.Controllers{publicabstractclassWebAPI2BaseController:ApiController
  • 标签:.net 手机 net 版本

  首先本次需求是在MVC5中进行的,那么先添加WEBAPI的接口

class="code_img_closed" src="/Upload/Images/2017021205/0015B68B3C38AA5B.gif" alt="">
using System;
using System.Web.Http;
using System.Net.Http;
using System.Web.Script.Serialization;
using System.Text;
using System.Web;

namespace BlackNails.Controllers
{
    public abstract class WebAPI2BaseController : ApiController
    {
        public HttpContext context = HttpContext.Current;

        public static HttpResponseMessage toJson(Object obj)
        {
            String str;
            if (obj is String || obj is Char)
            {
                str = obj.ToString();
            }
            else
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                str = serializer.Serialize(obj);
            }
            HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
            return result;
        }

        public string Options()
        {
            return null; // HTTP 200 response with empty body
        }
    }
}
logs_code_collapse">View Code

然后添加一个UserController接口文档

using BlackNails.CommonClass;
using BlackNails.Controllers;
using BlackNails.DAL;
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http;
using System.Web.Script.Serialization;

namespace BlackNails.WebAPI
{
    public class UserController : WebAPI2BaseController
    {

        [HttpGet]
        public HttpResponseMessage sendCode(string mobile)
        {
            var response = new Response();

            Random r = new Random();
            int i = r.Next(10000, 99999);
            string Random = i.ToString();

            TimeSpan ts = DateTime.Now - DateTime.Parse("1970-1-1");
            string Timestamp = Convert.ToInt32(ts.TotalSeconds).ToString();

            //以字节方式存储
            byte[] data = Encoding.Default.GetBytes(Constant.APP_SECRET + Random + Timestamp);
            System.Security.Cryptography.SHA1 sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
            //得到哈希值
            byte[] result = sha1.ComputeHash(data);
            //转换成为字符串的显示
            string Signature = BitConverter.ToString(result).Replace("-", "");

            WebRequest request = WebRequest.Create("http://api.sms.ronghub.com/sendCode.json");
            request.Method = "POST";
            string postData = "mobile=" + mobile + "&templateId=" + Constant.TEMPLATE_REGISTER + "&region=86";
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = byteArray.Length;
            request.Headers.Add("App-Key", Constant.APP_KEY);
            request.Headers.Add("Nonce", Random);
            request.Headers.Add("Timestamp", Timestamp);
            request.Headers.Add("Signature", Signature);
            Stream dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();
            WebResponse resp = request.GetResponse();
            dataStream = resp.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            string responseFromServer = reader.ReadToEnd();
            //var responseFromServer = "{\"code\":200,\"sessionId\":\"7jVyzHqjAV19w0P4e389TG\"}";
            JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
            ReturnJson _ReturnJson = jsonSerializer.Deserialize<ReturnJson>(responseFromServer);
            var code = _ReturnJson.code;
            var sessionId = _ReturnJson.sessionId;
            if(code == 200)
            {
                response.Code = 0;
                response.Message = "发送验证码成功!";
                context.Cache.Insert(mobile, sessionId);
            } else
            {
                response.Code = 1;
                response.Message = "发送验证码失败!";
                context.Cache.Insert(mobile, "");
            }
            reader.Close();
            dataStream.Close();
            resp.Close();

            response.Data = null;
            return toJson(response);
        }

        [HttpGet]
        public HttpResponseMessage verifyCode(string mobile, string code)
        {
            var response = new Response();

            Random r = new Random();
            int i = r.Next(10000, 99999);
            string Random = i.ToString();

            TimeSpan ts = DateTime.Now - DateTime.Parse("1970-1-1");
            string Timestamp = Convert.ToInt32(ts.TotalSeconds).ToString();

            //以字节方式存储
            byte[] data = Encoding.Default.GetBytes(Constant.APP_SECRET + Random + Timestamp);
            System.Security.Cryptography.SHA1 sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
            //得到哈希值
            byte[] result = sha1.ComputeHash(data);
            //转换成为字符串的显示
            string Signature = BitConverter.ToString(result).Replace("-", "");

            WebRequest request = WebRequest.Create("http://api.sms.ronghub.com/verifyCode.json");
            request.Method = "POST";
            string postData = "sessionId="+ context.Cache[mobile] +"&code=" + code;
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            request.ContentType = "application/x-www-form-urlencoded";
            request.Headers.Add("App-Key", Constant.APP_KEY);
            request.Headers.Add("Nonce", Random);
            request.Headers.Add("Timestamp", Timestamp);
            request.Headers.Add("Signature", Signature);
            Stream dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();
            WebResponse resp = request.GetResponse();
            dataStream = resp.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            string responseFromServer = reader.ReadToEnd();
            JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
            ReturnJson _ReturnJson = jsonSerializer.Deserialize<ReturnJson>(responseFromServer);
            var rtnCode = _ReturnJson.code;
            var rtnSuccess = _ReturnJson.success;
            if (rtnCode == 200)
            {
                response.Code = 0;
                response.Message = "手机号验证成功!";
            }
            else
            {
                response.Code = 1;
                response.Message = "手机号验证失败!";
            }
            reader.Close();
            dataStream.Close();
            resp.Close();

            response.Data = rtnSuccess;
            return toJson(response);
        }
    }
}
View Code

 

发表评论
用户名: 匿名