百度api短信开发

    公司原来有一个短信发送的功能,是调用第三方的,但是很不稳定,时不时就收不到短信,但是钱已经扣了。对于这样的事,谁都忍受不了的。于是想找一个稳定短信发送平台,第一想到的是阿里云,百度。在这两个平台上公司都有认证了,于是省了很多事。现在开始吧。

   

    找到百度开放云登录窗口,然后登录,进入控制中心,然后在产品服务中找到,如下图

简单消息服务SMS。前提是账号已经认证了。

点击它跳转到

 

   首先是短信签名申请,这个可以根据他们提供的文档一一操作,盖章,拍照上传,等待他们审核(大概两个星期吧)。审核成功,然后是短信模版申请,然后审核(大概一两天)

数量没有限制。

 

这个时候其实我们可以根据他们文档进行开发了,只要签名和短信模板审核已通过我们就可以测试了。

 

他们有Java等

SDK,但是没有.net的,因此我只能调用他们的API实现。首先要认证。

 

这个我是偷了一回懒。由于有同事做好了这个,他之前实现了一个百度api发送邮箱的功能。我只要把他那部分认证的代码搬过来就是了。如果愿意看,也是可以实现的。我把认证的代码搬来。

 这个方法实现。

 

 

  '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();
    }

 

posted @ 2016-09-05 12:02  剧里局外  阅读(9069)  评论(21编辑  收藏  举报