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

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

简单消息服务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, , 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 > Then
Dim Prefix As String = ""
If Telphonenum.Length = Then
Prefix = Telphonenum.Substring(, )
If Prefix = "" Then
result = Telphonenum.Substring(, )
End If
ElseIf (Telphonenum.Length = ) Then
Prefix = Telphonenum.Substring(, )
If Prefix = "" Or Prefix = "+86" Then
result = Telphonenum.Substring(, )
End If
Else
result = "号码错误"
End If ElseIf (Telphonenum.Length < ) 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, , 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();
}

百度api短信开发的更多相关文章

  1. C#.NET 大型信息化系统集成快速开发平台 - 手机短信开发接口 4.0

    可以批量发信息给手机,相同的信息发给多个手机号码的效果图 已发送手机短信列表 可以批量发手机的功能,可以把先有的待发信息列表,直接通过批量发送功能发出 这个是设置发送模板公式的功能展示,可以设置发送的 ...

  2. 短信API——短信验证码

    简介 短信服务(Short Message Service.SMS)是指通过调用短信发送API,将指定短信内容发送给指定手机用户. 阿里云短信服务 阿里云短信服务产品介绍:https://www.al ...

  3. jssip音视频及短信开发demo(中文注释完整版)

    完整案例demo下载地址:http://download.csdn.net/download/qq_39421580/10214712 <!DOCTYPE html> <html l ...

  4. Zabbix使用第三方API短信报警

    之前试过邮件告警,微信告警.但是,对于一些企业的重要业务服务器,可能是存放在隔离的内网中的,无法正常连接外网.这个时候,就有必要考虑一下使用短信告警.以下这个其实还是需要服务器能够连接到外网的,但是我 ...

  5. java发送短信开发,第三方接口方法

    必备的三个jar包Maven有自己去下: commons-logging commons-logging 1.1 commons-httpclient commons-httpclient 3.1 c ...

  6. 学校公文办公处理系统_基于ASP.NET和Swfupload、FlashPaper2.2、校讯通短信发送的开发

    学校新来了一个主管教学的副校长,他对他以前工作学校的公文处理系统表示高度留念,于是乎叫我们也开发一个. 我就参考了那个学校的办公管理系统,发现其实功能也蛮简单的,就是一个文件上传下载的功能,选择用户组 ...

  7. java servlet手机app访问接口(二)短信验证

    今天找了几个短信平台,其实最想使用的一个是sharesdk,使用它上面http api短信功能,不仅价格低,而且最少可以充值100RMB,但是审核过于严格,对应APP还必须集成他们的短信功能,而且要上 ...

  8. Android Studio精彩案例(五)《JSMS短信验证码功能实现》

    转载本专栏文章,请注明出处,尊重原创 .文章博客地址:道龙的博客 很多应用刚打开的时候,让我们输入手机号,通过短信验证码来登录该应用.那么,这个场景是怎么实现的呢?其实是很多开放平台提供了短信验证功能 ...

  9. C# 通过串口发送短信

    手机短信群发作为企业日常通知,公告,天气预报等信息的一个发布平台,在于成本低,操作方便等诸多特点,成为企业通讯之首选.本文介绍短信的编码方式,AT指令以及用C#实现串口通讯的方法. 前言目前,发送短信 ...

随机推荐

  1. JS全兼容检测浏览器类型及版本

    直接上代码: <script> var browser = (function () { var isIE6 = /msie 6/i.test(navigator.userAgent); ...

  2. error C2512: “Rectangle”: 没有合适的默认构造函数可用

    解决办法可能为: 1.再构造一个空的显性构造函数:

  3. Tomcat学习记录

    阅读摘录如下: 本质 Tomcat最本质就是个能运行JSP/Servlet的Web服务器 , 因此最典型的应用就是用户通过浏览器访问服务器,Tomcat接收到请求后转发给Servlet,由Servle ...

  4. Python 随机数生成总结

    random.uniform(a, b),返回[a,b]之间的浮点数 random.randint(a, b),返回[a,b]之间的整数 random.randrange([start], stop[ ...

  5. Yii源码阅读笔记(三十四)

    Instance类, 表示依赖注入容器或服务定位器中对某一个对象的引用 namespace yii\di; use Yii; use yii\base\InvalidConfigException; ...

  6. SQL PRIMARY KEY 约束\SQL FOREIGN KEY 约束\SQL CHECK 约束

    SQL PRIMARY KEY 约束 PRIMARY KEY 约束唯一标识数据库表中的每条记录. 主键必须包含唯一的值. 主键列不能包含 NULL 值. 每个表都应该有一个主键,并且每个表只能有一个主 ...

  7. 关于复选框input[type=checkbox]

    关于复选框input[type=checkbox],其实在前面的文章中说过一次,当时主要关注点在设置复选框的状态,利用prop实现,今天继续关注一下复选框. 自己在项目中,遇到一个全选/全不选的需求, ...

  8. CSS3媒体查询能检测到的特性小结

    CSS3的Media Queries能够检测到的特性总结: 视口(viewport)解释地址:http://baike.baidu.com/view/1522985.htm width:视口宽度的检测 ...

  9. 用Apache生产csr申请证书

    一. 安装Apache: 1.安装完成后将apache安装目录下 conf 文件夹中的"openssl.cnf"文件复制到bin文件夹中: 2.配置Apache支持ssl: 打开A ...

  10. Quartz2D 编程指南(四)位图与图像遮罩、CoreGraphics 绘制 Layer

    概览 图形上下文 路径 颜色与颜色空间 变换 图案 阴影 渐变 透明层 Quartz 2D 中的数据管理 位图与图像遮罩 CoreGraphics 绘制 Layer 位图与图像遮罩 简介 位图与图像遮 ...