微信相关接口
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

109 lines
2.3 KiB

  1. package wechat
  2. import (
  3. "errors"
  4. "fmt"
  5. )
  6. type wx_template_msg_res struct {
  7. Errcode int `json:"errcode"`
  8. Errmsg string `json:"errmsg"`
  9. msgid int `json:"msgid"`
  10. }
  11. func SendTemplateMessage(access_token string, touser, template_id, url string, data map[string]interface{}, client_msg_id, miniapp_appid, miniapp_pagepath string) (wx_template_msg_res, error) {
  12. var res wx_template_msg_res
  13. if touser == "" {
  14. return res, errors.New("缺少用户openid")
  15. }
  16. if template_id == "" {
  17. return res, errors.New("缺少消息模板")
  18. }
  19. if access_token == "" {
  20. return res, errors.New("缺少access token")
  21. }
  22. api_url := fmt.Sprintf(MP_TEMPLATE_MESSAGE_API, access_token)
  23. msg := map[string]interface{}{
  24. "touser": touser,
  25. "template_id": template_id,
  26. "url": url,
  27. "data": data,
  28. }
  29. if client_msg_id != "" {
  30. msg["client_msg_id"] = client_msg_id
  31. }
  32. if miniapp_appid != "" {
  33. msg["miniprogram"] = map[string]string{
  34. "appid": miniapp_appid,
  35. "pagepath": miniapp_pagepath,
  36. }
  37. }
  38. msg_json, err := json.Marshal(msg)
  39. if err != nil {
  40. return res, err
  41. }
  42. data_byte, err := PostJson(api_url, msg_json)
  43. if err == nil {
  44. err = json.Unmarshal(data_byte, &res)
  45. }
  46. return res, err
  47. }
  48. func SendTemplateMessageApplet(access_token string, touser, template_id string, miniprogram map[string]string, data map[string]interface{}, client_msg_id, miniapp_appid, miniapp_pagepath string) (wx_template_msg_res, error) {
  49. var res wx_template_msg_res
  50. if touser == "" {
  51. return res, errors.New("缺少用户openid")
  52. }
  53. if template_id == "" {
  54. return res, errors.New("缺少消息模板")
  55. }
  56. if access_token == "" {
  57. return res, errors.New("缺少access token")
  58. }
  59. api_url := fmt.Sprintf(MP_TEMPLATE_MESSAGE_API, access_token)
  60. msg := map[string]interface{}{
  61. "touser": touser,
  62. "template_id": template_id,
  63. "data": data,
  64. }
  65. if len(miniprogram) > 0 {
  66. msg["miniprogram"] = miniprogram
  67. }
  68. if client_msg_id != "" {
  69. msg["client_msg_id"] = client_msg_id
  70. }
  71. if miniapp_appid != "" {
  72. msg["miniprogram"] = map[string]string{
  73. "appid": miniapp_appid,
  74. "pagepath": miniapp_pagepath,
  75. }
  76. }
  77. msg_json, err := json.Marshal(msg)
  78. if err != nil {
  79. return res, err
  80. }
  81. data_byte, err := PostJson(api_url, msg_json)
  82. if err == nil {
  83. err = json.Unmarshal(data_byte, &res)
  84. }
  85. return res, err
  86. }