百度短信API开发教程

看到此文,是否觉得体内洪荒之力爆发,饥渴难耐想吐槽
本文为转载文章,若有侵权或违规行为,请联系我,会及时处理相关内容。

支付宝微  信

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

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

百度api短信开发

百度api短信开发

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

点击它跳转到

2

 

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

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

3

他们有Java等,

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

4

5

 

6

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

这个方法实现。

7

 

  '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

其实也可以在百度平台上测试

8

这样就算完成整个短信开发了。

 


原文链接:http://www.cnblogs.com/xiaohuasan/p/5841698.html


分类: 技术, 技术分享, 编程 | 标签: , , , , | 评论 | Permalink

发表评论

电子邮件地址不会被公开。 必填项已用*标注