公司原來有一個短信發送的功能,是調用第三方的,可是很不穩定,時不時就收不到短信,可是錢已經扣了。對於這樣的事,誰都忍受不了的。因而想找一個穩定短信發送平臺,第一想到的是阿里雲,百度。在這兩個平臺上公司都有認證了,因而省了不少事。如今開始吧。html
找到百度開放雲登陸窗口,而後登陸,進入控制中心,而後在產品服務中找到,以下圖json
簡單消息服務SMS。前提是帳號已經認證了。api
點擊它跳轉到app
首先是短信簽名申請,這個能夠根據他們提供的文檔一一操做,蓋章,拍照上傳,等待他們審覈(大概兩個星期吧)。審覈成功,而後是短信模版申請,而後審覈(大概一兩天)測試
數量沒有限制。this
這個時候其實咱們能夠根據他們文檔進行開發了,只要簽名和短信模板審覈已經過咱們就能夠測試了。阿里雲
他們有Java等,spa
SDK,可是沒有.net的,所以我只能調用他們的API實現。首先要認證。.net
這個我是偷了一回懶。因爲有同事作好了這個,他以前實現了一個百度api發送郵箱的功能。我只要把他那部分認證的代碼搬過來就是了。若是願意看,也是能夠實現的。我把認證的代碼搬來。3d
這個方法實現。
'https://msdn.microsoft.com/zh-cn/library/system.security.cryptography.hmacsha256(v%3DVS.95).aspx 'http://blog.sina.com.cn/s/blog_5eded52b0100e0mq.html Function GetSigningKeyByHMACSHA256HEX(ByVal SecretAccessKey As String, ByVal authStringPrefix As String) As String Dim Livehmacsha256 As HMACSHA256 = New HMACSHA256(Encoding.UTF8.GetBytes(SecretAccessKey)) Dim LiveHash As Byte() = Livehmacsha256.ComputeHash(Encoding.UTF8.GetBytes(authStringPrefix)) Dim SigningKey As String = HashEncode(LiveHash) Return SigningKey End Function Function GetSignatureByHMACSHA256HEX(ByVal SigningKey As String, ByVal CanonicalRequest As String) As String Dim Livehmacsha256 As HMACSHA256 = New HMACSHA256(Encoding.UTF8.GetBytes(SigningKey)) Dim LiveHash As Byte() = Livehmacsha256.ComputeHash(Encoding.UTF8.GetBytes(CanonicalRequest)) Dim Signature As String = HashEncode(LiveHash) Return Signature End Function '將字符串所有變成小寫。 Function HashEncode(ByVal hash As Byte()) As String Return BitConverter.ToString(hash).Replace("-", "").ToLower() End Function 'http://www.cnblogs.com/runliuv/p/5088787.html Public Function GetSHA256hash(ByVal input As String, ByVal _input_charset As String) As String Dim clearBytes As Byte() = Encoding.UTF8.GetBytes(input) Dim sha256 As SHA256 = New SHA256Managed() sha256.ComputeHash(clearBytes) Dim hashedBytes As Byte() = sha256.Hash sha256.Clear() Dim output As String = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower() Return output End Function
Imports System.Security.CryptographyImports System.Globalization Imports System.IO.Compression Public Class BaiduSMSTest Private smsinfo As SMSInfo Public Sub New(ByVal smsinfos As SMSInfo) Me.smsinfo = smsinfos End Sub Public Property GetSMSInfo() As SMSInfo Get Return smsinfo End Get Set(ByVal value As SMSInfo) smsinfo = value End Set End Property Function SendSMSWEBAPI() As String Try Dim receiveStream As System.IO.Stream = Nothing Dim responseReader As IO.StreamReader = Nothing Dim timestamp As String = Date.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ") Dim timestamp2 As String = Date.UtcNow.ToString("yyyy-MM-dd") Dim SecretAccessKey As String = "Secret Access Key 申請所得" Dim AccessKeyId As String = "Access Key ID申請所得" ' Dim authStringPrefix As String = "bce-auth-v1/{accessKeyId}/{timestamp}/{expirationPeriodInSeconds}" Dim authStringPrefix As String = String.Format("bce-auth-v1/{1}/{0}/1800", timestamp, AccessKeyId) '這裏要改 ' Dim CanonicalRequest As String = "HTTP Method + "\n" + CanonicalURI + "\n" + CanonicalQueryString + "\n" + CanonicalHeaders" Dim CanonicalRequest As String = String.Format("POST" & vbLf & "/v1/message" & vbLf & vbLf & "host:sms.bj.baidubce.com") Dim SigningKey As String = GetSigningKeyByHMACSHA256HEX(SecretAccessKey, authStringPrefix) Dim Signature As String = GetSignatureByHMACSHA256HEX(SigningKey, CanonicalRequest) Dim Content As String = String.Empty Content = "{ ""templateId"":""" + smsinfo.TemplateId + """,""receiver"":" + smsinfo.Receiver + ",""contentVar"":""" + smsinfo.ContentVar + """}" Dim ContentByte As Byte() = Encoding.UTF8.GetBytes(Content) Dim GetOrderURL As String = New Uri("http://sms.bj.baidubce.com/v1/message").ToString() Dim HttpWReq As System.Net.HttpWebRequest = CType(System.Net.WebRequest.Create(GetOrderURL), System.Net.HttpWebRequest) ' HttpWReq.Timeout = 600 * 1000 ''一分鐘查詢 HttpWReq.ContentLength = ContentByte.Length HttpWReq.ContentType = "application/json" HttpWReq.Headers("x-bce-date") = timestamp HttpWReq.Headers("Authorization") = String.Format("bce-auth-v1/{2}/{0}/1800/host/{1}", timestamp, Signature, AccessKeyId) HttpWReq.Host = "sms.bj.baidubce.com" HttpWReq.Method = "POST" HttpWReq.KeepAlive = False Dim StreamData As System.IO.Stream = HttpWReq.GetRequestStream() StreamData.Write(ContentByte, 0, ContentByte.Length) StreamData.Close() Dim HttpWRes As System.Net.HttpWebResponse = CType(HttpWReq.GetResponse, System.Net.HttpWebResponse) If HttpWRes.Headers.Get("Content-Encoding") = "gzip" Then Dim zipStream As System.IO.Stream = HttpWRes.GetResponseStream() receiveStream = New GZipStream(zipStream, CompressionMode.Decompress) Else receiveStream = HttpWRes.GetResponseStream() End If responseReader = New IO.StreamReader(receiveStream) Dim responseString As String = responseReader.ReadToEnd() Return responseString Catch ex As Exception Return ex.Message End Try End Function End Class
Public Class SMSInfo '模版id Private _templateId As String Public Property TemplateId() As String Get Return _templateId End Get Set(ByVal value As String) _templateId = value End Set End Property '接受短信者 Private _receiver As String Public Property Receiver() As String Get Return _receiver End Get Set(ByVal value As String) _receiver = value End Set End Property '內容 Private _contentVar As String Public Property ContentVar() As String Get Return _contentVar End Get Set(ByVal value As String) _contentVar = value End Set End Property End Class
號碼檢查方法
Function clearprefix(ByVal Telphonenum As String) As String Dim result As String = "" If Telphonenum.Length > 11 Then Dim Prefix As String = "" If Telphonenum.Length = 13 Then Prefix = Telphonenum.Substring(0, 2) If Prefix = "86" Then result = Telphonenum.Substring(2, 11) End If ElseIf (Telphonenum.Length = 14) Then Prefix = Telphonenum.Substring(0, 3) If Prefix = "086" Or Prefix = "+86" Then result = Telphonenum.Substring(3, 11) End If Else result = "號碼錯誤" End If ElseIf (Telphonenum.Length < 11) Then result = "不是手機號碼" Else result = Telphonenum End If Return result End Function
代碼測試,發送的內容是本身根據自定義的模板來的,組成標準的格式就能夠了。
Dim SMSinfo As SMSInfo = New SMSInfo() SMSinfo.TemplateId = "申請的短信模板" SMSinfo.Receiver = "[""手機號碼""]" SMSinfo.ContentVar = "{\""短信內容參數一\"":\""zhangsan \"",\""短信內容參數二\"":\""888888 \"",\""短信內容參數三\"":\""我是測試內容,我是測試內容 \""}" Protected Sub btntest_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btntest.Click Dim bdsms As BaiduSMSTest = New BaiduSMSTest(SMSinfo) Dim result As String = bdsms.SendSMSWEBAPI() End Sub
其實也能夠在百度平臺上測試
這樣就算完成整個短信開發了。
下面這個是C#版本的
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace PictureTest.BaiduSMS { public class SMSInfo { //模板 public string TemplateId { get; set; } //接受者 public string Receiver { get; set; } //內容 public string ContentVar { get; set; } } }
主要代碼
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Security.Cryptography; using System.Text; using System.Net; using System.IO.Compression; namespace PictureTest.BaiduSMS { public class BaiduSMSTest { private SMSInfo smsinfo; public SMSInfo Smsinfo { get { return smsinfo; } set { smsinfo = value; } } public BaiduSMSTest(SMSInfo smsinfo) { this.smsinfo = smsinfo; } public string SendSMSWEBAPI() { try { System.IO.Stream receiveStream = null; System.IO.StreamReader responseReader = null; string timestamp = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ"); // string timestamp2 As String = Date.UtcNow.ToString("yyyy-MM-dd") string SecretAccessKey = "申請所得"; string AccessKeyId = "申請所得"; // ' Dim authStringPrefix As String = "bce-auth-v1/{accessKeyId}/{timestamp}/{expirationPeriodInSeconds}" string authStringPrefix = string.Format("bce-auth-v1/{1}/{0}/1800", timestamp, AccessKeyId);// '這裏要改 // ' Dim CanonicalRequest As String = "HTTP Method + "\n" + CanonicalURI + "\n" + CanonicalQueryString + "\n" + CanonicalHeaders" string CanonicalRequest = string.Format("POST" + "\n" + "/v1/message" + "\n" + "\n" + "host:sms.bj.baidubce.com"); string SigningKey = GetSigningKeyByHMACSHA256HEX(SecretAccessKey, authStringPrefix); string Signature = GetSignatureByHMACSHA256HEX(SigningKey, CanonicalRequest); string Content = string.Empty; // Content = "{ \"templateId\":" + smsinfo.TemplateId + ",\"receiver\":" + smsinfo.Receiver + ",\"contentVar\":" + smsinfo.ContentVar + "}"; Content = "{"+"\""+"templateId"+"\""+":" + smsinfo.TemplateId + ","+"\""+"receiver"+"\""+":" + smsinfo.Receiver + ","+"\""+"contentVar"+"\""+":" + smsinfo.ContentVar + "}"; string temp = Content.ToString(); byte[] ContentByte = Encoding.UTF8.GetBytes(temp); string GetOrderURL = new Uri("http://sms.bj.baidubce.com/v1/message").ToString(); System.Net.HttpWebRequest HttpWReq =(WebRequest.Create(GetOrderURL) as System.Net.HttpWebRequest); //' HttpWReq.Timeout = 600 * 1000 ''一分鐘查詢 HttpWReq.ContentLength = ContentByte.Length; HttpWReq.ContentType = "application/json"; HttpWReq.Headers["x-bce-date"] = timestamp; HttpWReq.Headers["Authorization"] = string.Format("bce-auth-v1/{2}/{0}/1800/host/{1}", timestamp, Signature, AccessKeyId); HttpWReq.Host = "sms.bj.baidubce.com"; HttpWReq.Method = "POST"; HttpWReq.KeepAlive = false; System.IO.Stream StreamData = HttpWReq.GetRequestStream(); StreamData.Write(ContentByte, 0, ContentByte.Length); StreamData.Close(); System.Net.HttpWebResponse HttpWRes =(System.Net.HttpWebResponse) HttpWReq.GetResponse(); if (HttpWRes.Headers.Get("Content-Encoding") == "gzip" ){ System.IO.Stream zipStream = HttpWRes.GetResponseStream(); receiveStream = new GZipStream(zipStream, CompressionMode.Decompress); }else { receiveStream = HttpWRes.GetResponseStream(); } responseReader = new System.IO.StreamReader(receiveStream); string responseString = responseReader.ReadToEnd(); return responseString; } catch (Exception ex) { throw ex; } } public string GetSigningKeyByHMACSHA256HEX(String SecretAccessKey , String authStringPrefix ){ HMACSHA256 Livehmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(SecretAccessKey)); byte[] LiveHash = Livehmacsha256.ComputeHash(Encoding.UTF8.GetBytes(authStringPrefix)); string SigningKey = HashEncode(LiveHash); return SigningKey; } public string GetSignatureByHMACSHA256HEX( String SigningKey , String CanonicalRequest) { HMACSHA256 Livehmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(SigningKey)); byte[] LiveHash = Livehmacsha256.ComputeHash(Encoding.UTF8.GetBytes(CanonicalRequest)); string Signature = HashEncode(LiveHash); return Signature; } // '將字符串所有變成小寫。 public string HashEncode(byte[] hash) { return BitConverter.ToString(hash).Replace("-", "").ToLower(); } public string GetSHA256hash(string input , string _input_charset ){ byte[] clearBytes = Encoding.UTF8.GetBytes(input); SHA256 sha256 = new SHA256Managed(); sha256.ComputeHash(clearBytes); byte[] hashedBytes = sha256.Hash; sha256.Clear(); string output = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower(); return output; } } }
測試代碼
protected void btntest_Click(object sender, EventArgs e) { SMSInfo SMSinfo = new SMSInfo(); SMSinfo.TemplateId = "\""+"短信模版"+"\""; SMSinfo.Receiver = "["+"\""+手機號碼+"\""+"]"; SMSinfo.ContentVar = "{\"參數一\":\"zhangsan \",\"參數二\":\"99999 \",\"參數三\":\"我是測試內容\"}"; BaiduSMSTest bdsms = new BaiduSMSTest(SMSinfo); string result = bdsms.SendSMSWEBAPI(); }