xcx.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. package wx_mp
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/astaxie/beego"
  6. "bytes"
  7. "fohow.com/libs/tool"
  8. "io/ioutil"
  9. "net/http"
  10. )
  11. type SessionKey struct {
  12. Openid string `json:"openid"` //用户唯一标识
  13. SessionKey string `json:"session_key"` //会话密钥
  14. Unionid string `json:"unionid"` //用户在开放平台的唯一标识符。本字段在满足一定条件的情况下才返回。
  15. }
  16. type SessionKeyError struct {
  17. Errcode int64 `json:"errcode"` //用户唯一标识
  18. Errmsg string `json:"errmsg"` //会话密钥
  19. }
  20. // appId :小程序唯一标识
  21. // appSecret: 小程序的 app secret
  22. // code: 登录时获取的 code
  23. func GetXcxSessionKey(appId, appSecret, code string) *SessionKey {
  24. url := fmt.Sprintf("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code", appId, appSecret, code)
  25. resp := tool.HttpCall(url, "GET", nil, nil)
  26. var key *SessionKey
  27. //beego.BeeLogger.Warn("GetXcxSessionKey resp: %s", resp)
  28. if err := json.Unmarshal([]byte(resp), &key); err != nil {
  29. beego.BeeLogger.Error("GetXcxSessionKey parse query error:", err)
  30. }
  31. if key == nil || key.Openid == "" || key.SessionKey == "" {
  32. var keyError *SessionKeyError
  33. if err := json.Unmarshal([]byte(resp), &keyError); err != nil {
  34. beego.BeeLogger.Error("GetXcxSessionKey parse query error:", err)
  35. }
  36. beego.BeeLogger.Error("GetXcxSessionKey get session key error:%s", keyError)
  37. return nil
  38. }
  39. return key
  40. }
  41. type TemplateMessage struct {
  42. ToUser string `json:"touser"` // 必须, 接受者OpenID
  43. TemplateId string `json:"template_id"` // 必须, 模版ID
  44. URL string `json:"url,omitempty"` // 可选, 用户点击后跳转的URL, 该URL必须处于开发者在公众平台网站中设置的域中
  45. TopColor string `json:"topcolor,omitempty"` // 可选, 整个消息的颜色, 可以不设置
  46. Data json.RawMessage `json:"data"` // 必须, JSON 格式的 []byte, 满足特定的模板需求
  47. }
  48. func (msg *TemplateMessage) ToJson() {
  49. b, err := json.Marshal(msg)
  50. if err != nil {
  51. fmt.Println(err)
  52. return
  53. }
  54. fmt.Println(string(b))
  55. }
  56. type DataKeywordValue struct {
  57. Value string `json:"value"`
  58. Color string `json:"color"`
  59. }
  60. func NewDataKeywordValue(value string, color string) *DataKeywordValue {
  61. if color == "" {
  62. color = "#FFFFFF"
  63. }
  64. return &DataKeywordValue{Value: value, Color: color}
  65. }
  66. type OrderDispatchdMessageData struct {
  67. Amount DataKeywordValue `json:"keyword1"`
  68. Datetime DataKeywordValue `json:"keyword2"`
  69. Reason DataKeywordValue `json:"keyword3"`
  70. Remark DataKeywordValue `json:"keyword4"`
  71. }
  72. type BalanceChangedMessageData struct {
  73. Amount DataKeywordValue `json:"keyword1"`
  74. Datetime DataKeywordValue `json:"keyword2"`
  75. Reason DataKeywordValue `json:"keyword3"`
  76. Remark DataKeywordValue `json:"keyword4"`
  77. }
  78. type ProductLogisticsChangedMessageData struct {
  79. DispatchTime DataKeywordValue `json:"keyword1"`
  80. ProductName DataKeywordValue `json:"keyword2"`
  81. OrderId DataKeywordValue `json:"keyword3"`
  82. ExpressCompany DataKeywordValue `json:"keyword4"`
  83. ExpressOrderNo DataKeywordValue `json:"keyword5"`
  84. Remark DataKeywordValue `json:"keyword6"`
  85. }
  86. type OrderCreatedMessageData struct {
  87. OrderId DataKeywordValue `json:"keyword1"`
  88. Created_at DataKeywordValue `json:"keyword2"`
  89. ProductName DataKeywordValue `json:"keyword3"`
  90. Count DataKeywordValue `json:"keyword4"`
  91. OrderStatus DataKeywordValue `json:"keyword5"`
  92. Remark DataKeywordValue `json:"keyword6"`
  93. }
  94. type SelfUseNotifyMessageData struct {
  95. ProductName DataKeywordValue `json:"keyword1"`
  96. SelfUseCount DataKeywordValue `json:"keyword2"`
  97. WarmTip DataKeywordValue `json:"keyword3"`
  98. ServicePerson DataKeywordValue `json:"keyword4"`
  99. }
  100. type Template3MessageData struct {
  101. Kerword1 DataKeywordValue `json:"keyword1"`
  102. Kerword2 DataKeywordValue `json:"keyword2"`
  103. Kerword3 DataKeywordValue `json:"keyword3"`
  104. }
  105. type SubscribeDataValue struct {
  106. Value string `json:"value"`
  107. }
  108. type SubscribeMessage struct {
  109. ToUser string `json:"touser"`
  110. TemplateId string `json:"template_id"`
  111. Page string `json:"page,omitempty"`
  112. Data json.RawMessage `json:"data"`
  113. Lang string `json:"lang,omitempty"`
  114. MiniProgram string `json:"miniprogram_state,omitempty"`
  115. }
  116. type SubscribeMessageResponse struct {
  117. ErrCode int64 `json:"errcode"`
  118. ErrMsg string `json:"errmsg"`
  119. }
  120. func SendTemplateMessage(toUserOpenId string, templateId string, page string, formId string, data json.RawMessage, emphasisKeyword string) {
  121. token := GetAccessToken(beego.AppConfig.String("WxFohowXcxAppId"), beego.AppConfig.String("WxFohowXcxAppSecret"))
  122. beego.BeeLogger.Info("TestSendingTemplatemsgController got token: %s", token)
  123. template := `{
  124. "touser": "%s",
  125. "template_id": "%s",
  126. "page": "%s",
  127. "form_id": "%s",
  128. "data": %s,
  129. "emphasis_keyword": "%s"
  130. }`
  131. postData := fmt.Sprintf(template, toUserOpenId, templateId, page, formId, data, emphasisKeyword)
  132. apiUrl := fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=%s", token)
  133. var jsonStr = []byte(postData)
  134. req, err := http.NewRequest("POST", apiUrl, bytes.NewBuffer(jsonStr))
  135. req.Header.Set("Content-Type", "application/json")
  136. client := &http.Client{}
  137. resp, err := client.Do(req)
  138. if err != nil {
  139. beego.BeeLogger.Error(err.Error())
  140. }
  141. beego.BeeLogger.Warn("wx_mp.SendTemplateMessage, resp is null : %v", resp == nil)
  142. if resp != nil {
  143. defer resp.Body.Close()
  144. body, _ := ioutil.ReadAll(resp.Body)
  145. fmt.Println("response Body:", string(body))
  146. return
  147. }
  148. beego.BeeLogger.Warn("wx_mp.SendTemplateMessage, finished")
  149. }
  150. func SendXcxSubscribeMessage(toUserOpenId string, templateId string, page string, data interface{}) error {
  151. token := GetAccessToken(beego.AppConfig.String("WxFohowXcxAppId"), beego.AppConfig.String("WxFohowXcxAppSecret"))
  152. if token == "" {
  153. return fmt.Errorf("xcx subscribe message access token is empty")
  154. }
  155. jsonTemplateData, err := json.Marshal(data)
  156. if err != nil {
  157. return err
  158. }
  159. msg := SubscribeMessage{
  160. ToUser: toUserOpenId,
  161. TemplateId: templateId,
  162. Page: page,
  163. Data: jsonTemplateData,
  164. Lang: "zh_CN",
  165. }
  166. postData, err := json.Marshal(msg)
  167. if err != nil {
  168. return err
  169. }
  170. apiUrl := fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=%s", token)
  171. req, err := http.NewRequest("POST", apiUrl, bytes.NewBuffer(postData))
  172. if err != nil {
  173. return err
  174. }
  175. req.Header.Set("Content-Type", "application/json")
  176. resp, err := (&http.Client{}).Do(req)
  177. if err != nil {
  178. return err
  179. }
  180. defer resp.Body.Close()
  181. body, err := ioutil.ReadAll(resp.Body)
  182. if err != nil {
  183. return err
  184. }
  185. beego.BeeLogger.Warn("wx_mp.SendXcxSubscribeMessage response: %s", string(body))
  186. ret := new(SubscribeMessageResponse)
  187. if err := json.Unmarshal(body, ret); err != nil {
  188. return err
  189. }
  190. if ret.ErrCode != 0 {
  191. return fmt.Errorf("wechat subscribe message errcode=%d errmsg=%s", ret.ErrCode, ret.ErrMsg)
  192. }
  193. return nil
  194. }
  195. func formatFen(amount int64) string {
  196. return fmt.Sprintf("%.2f元", float64(amount)/100)
  197. }