/// <summary>
/// 百度接口签名帮助类
/// </summary>
public class BaiduApiHelper
{
#region 构造函数 /// <summary>
/// 构造函数
/// </summary>
/// <param name="accessKeyId">百度AccessKeyId(AK)</param>
/// <param name="secretAccessKey">百度SecretAccessKey(SK)</param>
public BaiduApiHelper(string accessKeyId, string secretAccessKey)
{
_accessKeyId = accessKeyId;
_secretAccessKey = secretAccessKey;
} #endregion #region 内部成员 private string _accessKeyId { get; }
private string _secretAccessKey { get; }
private string UriEncode(string input, bool encodeSlash = false)
{
StringBuilder builder = new StringBuilder();
foreach (byte b in Encoding.UTF8.GetBytes(input))
{
if ((b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') || (b >= '' && b <= '') || b == '_' || b == '-' || b == '~' || b == '.')
{
builder.Append((char)b);
}
else if (b == '/')
{
if (encodeSlash)
{
builder.Append("%2F");
}
else
{
builder.Append((char)b);
}
}
else
{
builder.Append('%').Append(b.ToString("X2"));
}
}
return builder.ToString();
}
private string Hex(byte[] data)
{
var sb = new StringBuilder();
foreach (var b in data)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
private string CanonicalRequest(HttpWebRequest req)
{
Uri uri = req.RequestUri;
StringBuilder canonicalReq = new StringBuilder();
canonicalReq.Append(req.Method).Append("\n").Append(UriEncode(Uri.UnescapeDataString(uri.AbsolutePath))).Append("\n"); var parameters = HttpUtility.ParseQueryString(uri.Query);
List<string> parameterStrings = new List<string>();
foreach (KeyValuePair<string, string> entry in parameters)
{
parameterStrings.Add(UriEncode(entry.Key) + '=' + UriEncode(entry.Value));
}
parameterStrings.Sort();
canonicalReq.Append(string.Join("&", parameterStrings.ToArray())).Append("\n"); string host = uri.Host;
if (!(uri.Scheme == "https" && uri.Port == ) && !(uri.Scheme == "http" && uri.Port == ))
{
host += ":" + uri.Port;
}
canonicalReq.Append("host:" + UriEncode(host));
return canonicalReq.ToString();
} #endregion #region 外部接口 /// <summary>
/// 发送POST请求
/// </summary>
/// <param name="method">请求方法,需要大写,列如(POST)</param>
/// <param name="host">主机地址列如(http://sms.bj.baidubce.com)</param>
/// <param name="url">接口地址列如(/bce/v2/message)</param>
/// <param name="paramters">参数列表</param>
/// <returns></returns>
public string RequestData(string method, string host, string url, Dictionary<string, object> paramters = null)
{
string ak = _accessKeyId;
string sk = _secretAccessKey;
DateTime now = DateTime.Now;
int expirationInSeconds = ; HttpWebRequest req = WebRequest.Create(host + url) as HttpWebRequest;
Uri uri = req.RequestUri;
req.Method = method;
req.ContentType = "application/json"; if (paramters != null)
{
Stream requestStream = req.GetRequestStream();
byte[] data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(paramters));
requestStream.Write(data, , data.Length);
} string signDate = now.ToUniversalTime().ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ssK");
string authString = "bce-auth-v1/" + ak + "/" + signDate + "/" + expirationInSeconds;
string signingKey = Hex(new HMACSHA256(Encoding.UTF8.GetBytes(sk)).ComputeHash(Encoding.UTF8.GetBytes(authString))); string canonicalRequestString = CanonicalRequest(req); string signature = Hex(new HMACSHA256(Encoding.UTF8.GetBytes(signingKey)).ComputeHash(Encoding.UTF8.GetBytes(canonicalRequestString)));
string authorization = authString + "/host/" + signature; req.Headers.Add("x-bce-date", signDate);
req.Headers.Add(HttpRequestHeader.Authorization, authorization); HttpWebResponse res;
string message = "";
try
{
res = req.GetResponse() as HttpWebResponse;
}
catch (WebException e)
{
res = e.Response as HttpWebResponse;
}
message = new StreamReader(res.GetResponseStream()).ReadToEnd(); return message;
} /// <summary>
/// 发送短信
/// </summary>
/// <param name="phoneNum">手机号码</param>
/// <param name="code">验证码</param>
/// <returns></returns>
public static bool SendMsg(string phoneNum, string code)
{
try
{
BaiduApiHelper baiduApiHelper = new BaiduApiHelper("", ""); string host = "http://sms.bj.baidubce.com";
string url = "/bce/v2/message";
Dictionary<string, object> paramters = new Dictionary<string, object>();
paramters.Add("invokeId", "Vhn0B-vCXn-8888");
paramters.Add("phoneNumber", phoneNum);
paramters.Add("templateCode", "smsTpl:e747612888e9018888");
paramters.Add("contentVar", new { code = code }); string resJsonStr = baiduApiHelper.RequestData("POST", host, url, paramters);
var resJson = JsonConvert.DeserializeObject<JObject>(resJsonStr); return resJson["code"]?.ToString() == "";
}
catch
{
return false;
}
} #endregion
}

直接调用,传入手机号和验证码即可。

最新文章

  1. Atom 如何隐藏 .Ds_Store 文件
  2. js-图标控件
  3. PHP文件相关
  4. #ifdef __cplusplus extern &quot;C&quot;
  5. hdu 5745 La Vie en rose DP + bitset优化
  6. Zabbix探索:纠结的选择
  7. Git 钩子
  8. 【CF492E】【数学】Vanya and Field
  9. kobox: key_proc.c -v1 怎样使用proc文件系统调试驱动
  10. Oracle推断领域包括中国
  11. 【h5+c3】web前端实战项目、快装webapp手机案例源码
  12. 深入理解hashCode
  13. Tomcat性能调优后, 启动出现警告问题 [did not find a matching property.]
  14. 反片语 UVA 156
  15. python的日志模块:logging;django的日志系统;django日志输出时间修改
  16. 23种设计模式之责任链模式(Chain of Responsibility)
  17. Windows Server 2008 R2之五操作主控的管理
  18. Oracle/MySQL decimal/int/number 转字符串
  19. 【12c OCP】CUUG OCP认证071考试原题解析(33)
  20. EasyUI 异步Tree

热门文章

  1. hihocoder#1046: K个串
  2. systemd socket activation golang demo
  3. pipelinewise 学习二 创建一个简单的pipeline
  4. Redis之eval+lua实现初步
  5. PHP7新增的主要特性
  6. bzoj4605: 崂山白花蛇草水 权值线段树套KDtree
  7. AcWing 95 费解的开关
  8. shell expect的简单实用
  9. java的static和this
  10. maven 左边空了