中国站
帮助中心 > 通信 > API文档 > 代码示例 > C#

C#

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Net.Http;
  4. using System.Security.Cryptography;
  5. using System.Text;
  6. namespace SmsDemo
  7. {
  8. class SendSms
  9. {
  10. private static Object generateSign(string signatureString, string secretKey, bool raw_output = false)
  11. {
  12. var enc = Encoding.UTF8;
  13. HMACSHA1 hmac = new HMACSHA1(enc.GetBytes(secretKey));
  14. hmac.Initialize();
  15. byte[] buffer = enc.GetBytes(signatureString);
  16. if (raw_output)
  17. {
  18. return hmac.ComputeHash(buffer);
  19. }
  20. else
  21. {
  22. return BitConverter.ToString(hmac.ComputeHash(buffer)).Replace("-", "").ToLower();
  23. }
  24. }
  25. public static void send()
  26. {
  27. String url = "https://api.yisu.com/sms/sendSms";
  28. String accessId = "*****";
  29. String accessSecret = "*****";
  30. Random rnd = new Random();
  31. TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
  32. List<KeyValuePair<String, String>> paramList = new List<KeyValuePair<String, String>>();
  33. paramList.Add(new KeyValuePair<String, String>("accessId", accessId));
  34. paramList.Add(new KeyValuePair<String, String>("templateCode", "100001"));
  35. paramList.Add(new KeyValuePair<String, String>("phone", "13800000000"));
  36. paramList.Add(new KeyValuePair<String, String>("timestamp", Convert.ToInt64(ts.TotalSeconds).ToString()));
  37. paramList.Add(new KeyValuePair<String, String>("nonce", rnd.Next(1, 1000000).ToString()));
  38. paramList.Add(new KeyValuePair<String, String>("templateVars", "{\"code\":\"123456\",\"min\":\"5\"}"));
  39. paramList.Sort(
  40. delegate (KeyValuePair<String, String> p1, KeyValuePair<String, String> p2)
  41. {
  42. return p1.Key.CompareTo(p2.Key);
  43. }
  44. );
  45. var param_str = "";
  46. foreach (var param in paramList)
  47. {
  48. param_str += param.Key.ToString() + "=" + param.Value.ToString() + "&";
  49. }
  50. param_str = param_str.Substring(0, param_str.Length - 1);
  51. byte[] sign = (byte[])generateSign(param_str, accessSecret, true);
  52. paramList.Add(new KeyValuePair<String, String>("signature", Convert.ToBase64String(sign)));
  53. HttpClient client = null;
  54. HttpResponseMessage response = null;
  55. try
  56. {
  57. client = new HttpClient();
  58. response = client.PostAsync(url, new FormUrlEncodedContent(paramList)).Result;
  59. String result = response.Content.ReadAsStringAsync().Result;
  60. Console.WriteLine("result:{0}", result);
  61. }
  62. catch (Exception e)
  63. {
  64. Console.WriteLine("\nException Caught!");
  65. Console.WriteLine("Message :{0} ", e.Message);
  66. }
  67. finally
  68. {
  69. if (null != response)
  70. {
  71. response.Dispose();
  72. }
  73. if (null != client)
  74. {
  75. client.Dispose();
  76. }
  77. }
  78. }
  79. static void Main(string[] args)
  80. {
  81. send();
  82. }
  83. }
  84. }