使用go開發公衆號之 關注公衆號發送小程序卡片

  • 首先準備工作
    •   先準備好公衆號和小程序,並且將小程序關聯公衆號

       

       

    • 準備一張小程序的縮略圖 

      //使用 https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=yourtoken&type=thumb
      接口進行縮略圖進行上傳 //這裏我是通過postman進行上傳的  //獲取asstoken 可能會報白名單的問題 ,需要把你獲取token的ip 添加到公衆號白名單。
      記錄下返回的thumb_media_id(media_id)

       

    • 使用 "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=%s" 接口進行發送客戶服務消息
          card := MiniprogramCard{
                      Touser: reflect.ValueOf(server.RequestMsg.FromUserName).String(), //需要發送的用戶
                      //miniprogrampage
                      Msgtype: "miniprogrampage",
                      Miniprogrampage: MiniProgramPage{
                          Title:          "title",
                          Appid:          "", //微信小程序appid
                          PagePath:       "pages/index/index",  //微信小程序頁面地址
                          ThumbMediaId: "A9WJuZt1K57Vs1AQAPmx3JG_G7IGzBS_2sx_WpNSGvU"}, //小程序卡片圖片的媒體ID
                  }

      下面是具體實現的代碼

      package main
      
      import (
          "bytes"
          "encoding/json"
          "fmt"
          wechat "github.com/silenceper/wechat/v2"
          "github.com/silenceper/wechat/v2/cache"
          offConfig "github.com/silenceper/wechat/v2/officialaccount/config"
          "github.com/silenceper/wechat/v2/officialaccount/message"
          "net/http"
          "reflect"
          "time"
      )
      
      func GenHTTPClient(timeout *time.Duration) *http.Client {
          if timeout != nil {
              return &http.Client{
                  Timeout: *timeout * time.Second,
              }
          } else {
              return &http.Client{
                  Timeout: 3 * time.Second,
              }
          }
      }
      
      
      type MiniprogramCard struct {
          Touser          string          `json:"touser"`
          Msgtype         string          `json:"msgtype"`
          Miniprogrampage MiniProgramPage `json:"miniprogrampage"`
      }
      
      type MiniProgramPage struct {
          Title        string `json:"title"`
          Appid        string `json:"appid"`    //微信小程序appid
          PagePath     string `json:"pagepath"` //微信小程序頁面地址
          ThumbMediaId string `json:"thumb_media_id"`
      }
      
      func serveWechat(rw http.ResponseWriter, req *http.Request) {
          wc := wechat.NewWechat()
          //這裏本地內存保存access_token,也可選擇redis,memcache或者自定cache
          memory := cache.NewMemory()
          cfg := &offConfig.Config{ //從你自己公衆號後臺去拿
              AppID:          "",
              AppSecret:      "",
              Token:          "",
              EncodingAESKey: "",
              Cache:          memory,
          }
          officialAccount := wc.GetOfficialAccount(cfg)
          ak, _ := officialAccount.GetAccessToken()
          // 傳入request和responseWriter
          server := officialAccount.GetServer(req, rw)
          //設置接收消息的處理方法
          server.SetMessageHandler(func(mixMessage *message.MixMessage) *message.Reply {
              //TODO
              //回覆消息:演示回覆用戶發送的消息
              switch mixMessage.MsgType {
              //自動回覆消息
              case message.MsgTypeText:
                  text := message.NewText(mixMessage.Content)
                  return &message.Reply{MsgType: message.MsgTypeText, MsgData: text}
              }
              switch mixMessage.Event {
              //如果是初次訂閱回覆圖文消息
              case message.EventSubscribe:
                  //獲取token
      
                  //根據token 發送客服消息
                  url := fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=%s", ak)
                  card := MiniprogramCard{
                      Touser: reflect.ValueOf(server.RequestMsg.FromUserName).String(), //需要發送的用戶
                      //miniprogrampage
                      Msgtype: "miniprogrampage",
                      Miniprogrampage: MiniProgramPage{
                          Title:          "title",
                          Appid:          "", //微信小程序appid
                          PagePath:       "pages/index/index",  //微信小程序頁面地址
                          ThumbMediaId: "A9WJuZt1K57Vs1AQAPmx3JG_G7IGzBS_2sx_WpNSGvU"}, //小程序卡片圖片的媒體ID
                  }
                  req, _ := json.Marshal(card)
                  res, _ := GenHTTPClient(nil).Post(url, "application/json", bytes.NewBuffer(req))
                  fmt.Println(res)
              }
              text := message.NewText(mixMessage.Content)
              return &message.Reply{MsgType: message.MsgTypeText, MsgData: text}
          })
          //處理消息接收以及回覆
          err := server.Serve()
          if err != nil {
              fmt.Println(err)
              return
          }
          //發送回覆的消息
          server.Send()
      }
      
      func main() {
          http.HandleFunc("/", serveWechat)
          fmt.Println("wechat server listener at", ":8001")
          err := http.ListenAndServe(":8001", nil)
          if err != nil {
              fmt.Printf("start server error , err=%v", err)
          }
      }

       tips:另外如果沒有線上環境域名 ,可以在花生殼買一個域名,然後把域名代理到本地的一個端口。這樣就能在本地斷點微信公衆號那邊發送過來的消息了。

    發表評論
    所有評論
    還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
    相關文章