c#发送手机短信

本代码使用网易短信平台

同时提供:发送短信给多人,校验验证码,发送通知类短信等等

        /// <summary>
        /// 发送短信
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("sendMessage")]
        public int SendCode()
        {
            string nonce = "12345";
            int templateid = 111111;//模板id
            string appKey = "****************";//key
            string appSecret = "*******";//密码
            string mobile = "12345678901";//接收短信的手机号
            String url = "https://api.netease.im/sms/sendcode.action" + string.Format("?templateid={0}&mobile={1}", templateid, mobile);

            TimeSpan ts = DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1);
            string curTime = System.Convert.ToInt32(ts.TotalSeconds).ToString();//当前的时间戳
            String checkSum = getCheckSum(appSecret, nonce, curTime);//计算并获取CheckSum

            IDictionary<object, String> headers = new Dictionary<object, String>();
            headers["AppKey"] = appKey;
            headers["Nonce"] = nonce;
            headers["CurTime"] = curTime;
            headers["CheckSum"] = checkSum;
            headers["ContentType"] = "application/x-www-form-urlencoded;charset=utf-8";
            int code = HttpPost(url, null, headers);//发起Http请求

            return code;
        }
        /// <summary>
        /// 计算并获取CheckSum
        /// </summary>
        /// <param name="appSecret"></param>
        /// <param name="nonce"></param>
        /// <param name="curTime"></param>
        /// <returns></returns>
        public String getCheckSum(String appSecret, String nonce, String curTime)
        {
            byte[] data = Encoding.Default.GetBytes(appSecret + nonce + curTime);
            byte[] result;

            SHA1 sha = new SHA1CryptoServiceProvider();
            result = sha.ComputeHash(data);//进行SHA1哈希计算,转化成16进制字符

            return getFormattedText(result);
        }
        private String getFormattedText(byte[] bytes)
        {
            char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5','6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
            int len = bytes.Length;
            StringBuilder buf = new StringBuilder(len * 2);
            for (int j = 0; j < len; j++)
            {
                buf.Append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
                buf.Append(HEX_DIGITS[bytes[j] & 0x0f]);
            }
            return buf.ToString();
        }
        /// <summary>
        /// 发起Http请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <param name="headers"></param>
        /// <returns></returns>
        public int HttpPost(string url, Stream data, IDictionary<object, string> headers = null)
        {
            WebRequest request = HttpWebRequest.Create(url);
            request.Method = "POST";
            if (data != null)
                request.ContentLength = data.Length;

            if (headers != null)
            {
                foreach (var v in headers)
                {
                    if (v.Key is HttpRequestHeader)
                        request.Headers[(HttpRequestHeader)v.Key] = v.Value;
                    else
                        request.Headers[v.Key.ToString()] = v.Value;
                }
            }
            HttpWebResponse response = null;
            int code = 0;
            try
            {
                response = (HttpWebResponse)request.GetResponse();
                Stream dataStream = response.GetResponseStream();//获取服务器返回的内容 流
                StreamReader reader = new StreamReader(dataStream);//打开流 以便访问
                string responseFromServer = reader.ReadToEnd();//读取
                ResultData result = common.JsonHelper.DeserializeJsonToObject<ResultData>(responseFromServer);//转为json  { "code":413,"msg":"verify err","obj":1}
                code = result.code;

                reader.Close();
                dataStream.Close();
                response.Close();
            }
            catch (Exception)
            {
                return code;
            }
            return code;
        }
        class ResultData
        {
            public int code { get; set; }
            public string msg { get; set; }
            public string obj { get; set; }
        }

 

posted @ 2019-05-15 15:00  Zoe97  阅读(866)  评论(0编辑  收藏  举报