1
0

wechat-corp-account.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. package channel
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "message-pusher/common"
  8. "message-pusher/model"
  9. "net/http"
  10. "time"
  11. )
  12. type wechatCorpAccountResponse struct {
  13. ErrorCode int `json:"errcode"`
  14. ErrorMessage string `json:"errmsg"`
  15. AccessToken string `json:"access_token"`
  16. ExpiresIn int `json:"expires_in"`
  17. }
  18. type WeChatCorpAccountTokenStoreItem struct {
  19. CorpId string
  20. AgentSecret string
  21. AgentId string
  22. AccessToken string
  23. }
  24. func (i *WeChatCorpAccountTokenStoreItem) Key() string {
  25. return i.CorpId + i.AgentId + i.AgentSecret
  26. }
  27. func (i *WeChatCorpAccountTokenStoreItem) IsShared() bool {
  28. return model.DB.Where("wechat_corp_account_id = ? and wechat_corp_account_agent_secret = ? and wechat_corp_account_agent_id = ?",
  29. i.CorpId, i.AgentSecret, i.AgentId).Find(&model.User{}).RowsAffected != 1
  30. }
  31. func (i *WeChatCorpAccountTokenStoreItem) Token() string {
  32. return i.AccessToken
  33. }
  34. func (i *WeChatCorpAccountTokenStoreItem) Refresh() {
  35. // https://work.weixin.qq.com/api/doc/90000/90135/91039
  36. client := http.Client{
  37. Timeout: 5 * time.Second,
  38. }
  39. req, err := http.NewRequest("GET", fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s",
  40. i.CorpId, i.AgentSecret), nil)
  41. if err != nil {
  42. common.SysError(err.Error())
  43. return
  44. }
  45. responseData, err := client.Do(req)
  46. if err != nil {
  47. common.SysError("failed to refresh access token: " + err.Error())
  48. return
  49. }
  50. defer responseData.Body.Close()
  51. var res wechatCorpAccountResponse
  52. err = json.NewDecoder(responseData.Body).Decode(&res)
  53. if err != nil {
  54. common.SysError("failed to decode wechatCorpAccountResponse: " + err.Error())
  55. return
  56. }
  57. if res.ErrorCode != 0 {
  58. common.SysError(res.ErrorMessage)
  59. return
  60. }
  61. i.AccessToken = res.AccessToken
  62. common.SysLog("access token refreshed")
  63. }
  64. type wechatCorpMessageRequest struct {
  65. MessageType string `json:"msgtype"`
  66. ToUser string `json:"touser"`
  67. AgentId string `json:"agentid"`
  68. TextCard struct {
  69. Title string `json:"title"`
  70. Description string `json:"description"`
  71. URL string `json:"url"`
  72. } `json:"textcard"`
  73. Text struct {
  74. Content string `json:"content"`
  75. } `json:"text"`
  76. Markdown struct {
  77. Content string `json:"content"`
  78. } `json:"markdown"`
  79. }
  80. type wechatCorpMessageResponse struct {
  81. ErrorCode int `json:"errcode"`
  82. ErrorMessage string `json:"errmsg"`
  83. }
  84. func SendWeChatCorpMessage(message *Message, user *model.User) error {
  85. if user.WeChatCorpAccountId == "" {
  86. return errors.New("未配置微信企业号消息推送方式")
  87. }
  88. // https://developer.work.weixin.qq.com/document/path/90236
  89. messageRequest := wechatCorpMessageRequest{
  90. ToUser: user.WeChatCorpAccountUserId,
  91. AgentId: user.WeChatCorpAccountAgentId,
  92. }
  93. if message.Content == "" {
  94. messageRequest.MessageType = "text"
  95. messageRequest.Text.Content = message.Description
  96. } else {
  97. if user.WeChatCorpAccountClientType == "plugin" {
  98. messageRequest.MessageType = "textcard"
  99. messageRequest.TextCard.Title = message.Title
  100. messageRequest.TextCard.Description = message.Description
  101. // TODO: render content and set URL
  102. messageRequest.TextCard.URL = common.ServerAddress
  103. } else {
  104. messageRequest.MessageType = "markdown"
  105. messageRequest.Markdown.Content = message.Content
  106. }
  107. }
  108. jsonData, err := json.Marshal(messageRequest)
  109. if err != nil {
  110. return err
  111. }
  112. key := fmt.Sprintf("%s%s%s", user.WeChatCorpAccountId, user.WeChatCorpAccountAgentId, user.WeChatCorpAccountAgentSecret)
  113. accessToken := TokenStoreGetToken(key)
  114. resp, err := http.Post(fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s", accessToken), "application/json",
  115. bytes.NewBuffer(jsonData))
  116. if err != nil {
  117. return err
  118. }
  119. var res wechatCorpMessageResponse
  120. err = json.NewDecoder(resp.Body).Decode(&res)
  121. if err != nil {
  122. return err
  123. }
  124. if res.ErrorCode != 0 {
  125. return errors.New(res.ErrorMessage)
  126. }
  127. return nil
  128. }