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

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

简单消息服务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. 大端小端系统_union_栈的增长方向

    一道题引发的思考: 1.看一下之前写的union的特点,理解一下共享内存的概念 2.栈的增长方向是从高地址向低地址增长(数组比较特别,a[0]在低地址,a[n-1]在高地址)(堆由低地址到高地址存储) ...

  2. c++聪聪看书(低数据版代码)

    聪聪是一个善良可爱.睿智聪慧的好孩子.聪聪喜欢看书,这一天她在看一本书时看到了这样一个问题:给你一个正整数n,你要将它分成若干个自然数Ai的和的形式,并且使得这若干个自然数Ai的乘积尽量大,并输出最大 ...

  3. 数据库使用数据泵迁移遇到LOB字段

    impdp system/Clic1234 attach=SYS_IMPORT_ILEARN_TRA desc ILEARN_TRA.NOTIFI_TACTIC desc ILEARN_TRA.MSG ...

  4. 史上最全的java随机数生成算法分享(转)

    这篇文章主要介绍了史上最全的java随机数生成算法,我分享一个最全的随机数的生成算法,最代码的找回密码的随机数就是用的这个方法 String password = RandomUtil.generat ...

  5. WebApi接口传参不再困惑(4):传参详解(转载)

    WebApi接口传参不再困惑(4):传参详解   前言:还记得刚使用WebApi那会儿,被它的传参机制折腾了好久,查阅了半天资料.如今,使用WebApi也有段时间了,今天就记录下API接口传参的一些方 ...

  6. C和C++混合编程中的extern "C" {}

    引言 在用C++的项目源码中,经常会不可避免的会看到下面的代码: 1 2 3 4 5 6 7 8 9 #ifdef __cplusplus extern "C" { #endif ...

  7. 常见的JAVA包

    java.lang 提供利用 Java 编程语言进行程序设计的基础类.最重要的类是 Object(它是类层次结构的根)和 Class(它的实例表示正在运行的应用程序中的类). java.util 包含 ...

  8. cloudera learning1:cloudera简介及安装

    cloudera分为两个部分:CDH和CM.CDH是Cloudera Distribution Hadoop的简称,顾名思义,就是cloudera公司发布的Hadoop版本,封装了Apache Had ...

  9. Json与常见的类型之间的转换

    常用的json list转json List list=new ArrayList(); list.add("1"); list.add("2"); JsonA ...

  10. dede文章内容页增加视频文件

     具体方法:1.在优酷上注册个账号.将要上传的视频在优酷上发布.2.待审核完成后分享复制html代码. 3.在后台发布文章时点击源码,将优酷中复制的代码考过来.4.发布后生成页面即可.(可参照vide ...