aliyun.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package sms
  2. import (
  3. "encoding/json"
  4. openapi "github.com/alibabacloud-go/darabonba-openapi/client"
  5. dysmsapi20170525 "github.com/alibabacloud-go/dysmsapi-20170525/v2/client"
  6. util "github.com/alibabacloud-go/tea-utils/service"
  7. "github.com/alibabacloud-go/tea/tea"
  8. )
  9. type Aliyun struct {
  10. SignName string
  11. AppId string
  12. AppKey string
  13. TemplateId string
  14. }
  15. /**
  16. * 使用AK&SK初始化账号Client
  17. * @param accessKeyId
  18. * @param accessKeySecret
  19. * @return Client
  20. * @throws Exception
  21. */
  22. func (c *Aliyun) CreateClient() (_result *dysmsapi20170525.Client, _err error) {
  23. config := &openapi.Config{
  24. // 您的 AccessKey ID
  25. AccessKeyId: tea.String(c.AppId),
  26. // 您的 AccessKey Secret
  27. AccessKeySecret: tea.String(c.AppKey),
  28. }
  29. // 访问的域名
  30. config.Endpoint = tea.String("dysmsapi.aliyuncs.com")
  31. _result = &dysmsapi20170525.Client{}
  32. _result, _err = dysmsapi20170525.NewClient(config)
  33. return _result, _err
  34. }
  35. func (c *Aliyun) Send(datatype, dataparams, phones interface{}) interface{} {
  36. client, _err := c.CreateClient()
  37. if _err != nil {
  38. return _err
  39. }
  40. dataparamsMap := dataparams.(map[string]interface{})
  41. dataparamsMapStr, _ := json.Marshal(dataparamsMap)
  42. phonesStr, _ := json.Marshal(phones.([]string))
  43. sendSmsRequest := &dysmsapi20170525.SendBatchSmsRequest{
  44. SignNameJson: tea.String(c.SignName),
  45. TemplateCode: tea.String(c.TemplateId),
  46. PhoneNumberJson: tea.String(string(phonesStr)),
  47. TemplateParamJson: tea.String(string(dataparamsMapStr)),
  48. }
  49. runtime := &util.RuntimeOptions{}
  50. tryErr := func() (_e error) {
  51. defer func() {
  52. if r := tea.Recover(recover()); r != nil {
  53. _e = r
  54. }
  55. }()
  56. // 复制代码运行请自行打印 API 的返回值
  57. _, _err = client.SendBatchSmsWithOptions(sendSmsRequest, runtime)
  58. if _err != nil {
  59. return _err
  60. }
  61. return nil
  62. }()
  63. if tryErr != nil {
  64. var error = &tea.SDKError{}
  65. if _t, ok := tryErr.(*tea.SDKError); ok {
  66. error = _t
  67. } else {
  68. error.Message = tea.String(tryErr.Error())
  69. }
  70. // 如有需要,请打印 error
  71. util.AssertAsString(error.Message)
  72. }
  73. return _err
  74. }