AliMessagePost.cs 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using Tea;
  2. namespace OASystem.API.OAMethodLib.ALiYun
  3. {
  4. public class AliMessagePost
  5. {
  6. private static string accessKeyId { get; set; } = "LTAI5t982d4MQ8FqswNt3qkf";
  7. private static string accessKeySecret { get; set; } = "VsDBzZI4O6IEli7NgdWHoZviHgYgYB";
  8. /**
  9. * 使用AK&SK初始化账号Client
  10. * @param accessKeyId
  11. * @param accessKeySecret
  12. * @return Client
  13. * @throws Exception
  14. */
  15. public static AlibabaCloud.SDK.Dysmsapi20170525.Client CreateClient(string accessKeyId, string accessKeySecret)
  16. {
  17. AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
  18. {
  19. // 必填,您的 AccessKey ID
  20. AccessKeyId = accessKeyId,
  21. // 必填,您的 AccessKey Secret
  22. AccessKeySecret = accessKeySecret,
  23. };
  24. // 访问的域名
  25. config.Endpoint = "dysmsapi.aliyuncs.com";
  26. return new AlibabaCloud.SDK.Dysmsapi20170525.Client(config);
  27. }
  28. public static string PostMessage(string phoneNumber, string signName, string templateCode, string templateParam)
  29. {
  30. // 请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID 和 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
  31. // 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例使用环境变量获取 AccessKey 的方式进行调用,仅供参考,建议使用更安全的 STS 方式,更多鉴权访问方式请参见:https://help.aliyun.com/document_detail/378671.html
  32. AlibabaCloud.SDK.Dysmsapi20170525.Client client = CreateClient(accessKeyId, accessKeySecret);
  33. AlibabaCloud.SDK.Dysmsapi20170525.Models.SendSmsRequest sendSmsRequest = new AlibabaCloud.SDK.Dysmsapi20170525.Models.SendSmsRequest
  34. {
  35. PhoneNumbers = phoneNumber,
  36. SignName = signName,
  37. TemplateCode = templateCode,
  38. TemplateParam = templateParam
  39. };
  40. string result = "发送失败,未知错误";
  41. try
  42. {
  43. // 复制代码运行请自行打印 API 的返回值
  44. var suc = client.SendSmsWithOptions(sendSmsRequest, new AlibabaCloud.TeaUtil.Models.RuntimeOptions());
  45. result = JsonConvert.SerializeObject(suc);
  46. }
  47. catch (TeaException error)
  48. {
  49. // 如有需要,请打印 error
  50. result = AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
  51. }
  52. catch (Exception _error)
  53. {
  54. TeaException error = new TeaException(new Dictionary<string, object>
  55. {
  56. { "message", _error.Message }
  57. });
  58. // 如有需要,请打印 error
  59. result = AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
  60. }
  61. return result;
  62. }
  63. }
  64. }