wechat

package
v0.0.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 18, 2021 License: Apache-2.0 Imports: 14 Imported by: 0

README

wecaht - 一个小型的微信公众号api

你可以快速搭建一个订阅号/服务号应用,支持被动回复,主动回复,设置菜单,素材管理,用户管理等

Installation

$ go get github.com/slrem/wechat

Examples 1

被动回复 可以和web框架配合使用 以echo为例

package main

import (
  "fmt"
  "log"
  "github.com/labstack/echo"
  "github.com/slrem/wechat"
)

  //错误处理
  func ErrorHandler(err error, c wechat.Context) error {
  		return c.Response().Success()
  }

//中间件
func LogUserActive() wechat.Middleware {
  	return func(next wechat.Handler) wechat.Handler {
  		return func(c wechat.Context) error {
        log.Println(c.Request().FromUserName())
  			return next(c)
  		}
  	}
  }

//文本消息处理
func textHandler(c wechat.Context) (err error) {
  	log.Println(c.Request().Content()) //用户发送来的文本消息

    //do somethings
    ...
    return c.Response().Text(c.Request().Content())
}

//关注事件处理
func subscribeHandler(c wechat.Context) (err error) {

	return c.Response().Text("欢迎关注[微笑]")
}

//取消关注事件处理
func unsubscribeHandler(c wechat.Context) (err error) {
	return c.Response().Success() //不做处理
}

//菜单处理事件
func clickMenuHandler(c wechat.Context) (err error) {
  key:=c.Request().EventKey()
	return  c.Response().Image(mediaid)
}

func main()  {
  w, err := wechat.New(
  		"appID", //公众号appid
  		"appsecret", //公众号appsecret
  		"token", //公众号设置的token
  		"encodingAESKey", //公众号加密钥匙
      nil
      )


  w.WechatErrorHandler = ErrorHandler

  w.Use(LogUserActive()) // 记录活跃时间

  w.Text(textHandler)
  w.SubscribeEvent(subscribeHandler)
  w.UnsubscribeEvent(unsubscribeHandler)
  w.MenuClickEvent(clickMenuHandler)

  e := echo.New()
  e.Any("/wechat/:app", func(c echo.Context) (err error) {
    w.Server(c.Response(), c.Request())
  }
}

e.Start(":8080")

Examples 2

package main

import (
  "fmt"
  "log"

  "github.com/slrem/wechat"
)

func main() {
	w, err := wechat.New(
		"appID", //公众号appid
		"appsecret", //公众号appsecret
		"token", //公众号设置的token
		"encodingAESKey", //公众号加密钥匙
    nil
    )  

	t := w.Trader() //获取一个操作器
	//创建菜单
  menustr:=`{
     "button":[
     {
          "type":"click",
          "name":"今日歌曲",
          "key":"V1001_TODAY_MUSIC"
      },
      {
           "name":"菜单",
           "sub_button":[
           {
               "type":"view",
               "name":"搜索",
               "url":"http://www.soso.com/"
            },
            {
                 "type":"miniprogram",
                 "name":"wxa",
                 "url":"http://mp.weixin.qq.com",
                 "appid":"wx286b93c14bbf93aa",
                 "pagepath":"pages/lunar/index"
             },
            {
               "type":"click",
               "name":"赞一下我们",
               "key":"V1001_GOOD"
            }]
       }]
 }`
  t.CreateMenu(menustr)

//获取粉丝openid

	f, _ := t.GetFans("")
	for _,v:=range f{
    log.Println(v)
  }

//主动发送消息
  t.SendTextMsg("openid", "你好")

//添加一个图片素材
  b,_:=toutil.ReadFile("image.jpg")
  mediaid,url,err:=t.AddImageMaterial(b)

//主动发送消息
  t.SendImageMsg("openid", mediaid)

//群发消息 tagid为0 表示发给全部,其他的为发给属于标签id的所有用户
t.SendTextAll(tagid, "这是群发消息")

Documentation

Index

Constants

View Source
const (
	SubscriptionsType
	ServiceType
)

Variables

View Source
var ArticleCountOverError = errors.New("article count over 10")

Functions

This section is empty.

Types

type Article

type Article struct {
	Title       CDATAString
	Description CDATAString
	PicUrl      CDATAString
	Url         CDATAString
}

type ArticleItem

type ArticleItem struct {
	Item Article `xml:"item"`
}

func NewArticleItem

func NewArticleItem(title, description, picUrl, url string) ArticleItem

type ArticleResponseMessage

type ArticleResponseMessage struct {
	XMLName      xml.Name `xml:"xml"`
	ToUserName   string
	FromUserName string
	CreateTime   int64
	MsgType      string
	ArticleCount int
	Articles     []ArticleItem
}

func NewArticleResponseMessage

func NewArticleResponseMessage(to, from string, articles ...ArticleItem) (a ArticleResponseMessage, err error)

type CDATAString

type CDATAString struct {
	CDATA string `xml:",cdata"`
}

type Context

type Context interface {
	Wechat() *Wechat
	Request() Request
	Response() Response
	SetHandler(h Handler)
}

type Handler

type Handler func(Context) error

type ImageMessage

type ImageMessage interface {
	MsgId() int64
	PicUrl() string
	MediaId() string
	// contains filtered or unexported methods
}

type ImageResponseMessage

type ImageResponseMessage struct {
	XMLName      xml.Name `xml:"xml"`
	ToUserName   string
	FromUserName string
	CreateTime   int64
	MsgType      string
	Image        MediaId
}

func NewImageResponseMessage

func NewImageResponseMessage(to, from, mediaId string) ImageResponseMessage

type LinkMessage

type LinkMessage interface {
	Title() string
	Description() string
	Url() string
	MsgId() int64
	// contains filtered or unexported methods
}

type LocationEventMessage

type LocationEventMessage interface {
	Event() string
	Latitude()
	Longitude() float32
	Precision() float32
	// contains filtered or unexported methods
}

type LocationMessage

type LocationMessage interface {
	LocationX()
	LocationY()
	Scale() int
	Label() string
	MsgId() int64
	// contains filtered or unexported methods
}

type MediaId

type MediaId struct {
	MediaId CDATAString
}
type MenuClickEventMessage interface {
	Event() string
	EventKey() string
	// contains filtered or unexported methods
}
type MenuViewEventMessage interface {
	Event() string
	EventKey() string
	MenuId() int64
	// contains filtered or unexported methods
}

type Middleware

type Middleware func(Handler) Handler

type MsgType

type MsgType int
const (
	UnknownType MsgType = iota
	TextType
	ImageType
	VoiceType
	VideoType
	ShortVideoType
	LocationType
	LinkType

	EventType

	SubscribeEventType
	UnsubscribeEventType
	ScanEventType
	ScanSubscribeEventType
	LocationEventType
	MenuViewEventType
	MenuClickEventType

	ScancodePushEventType
	ScancodeWaitmsgEventType
	PicSysphotoEventType
	PicPhotoOrAlbumEventType
	PicWeixinEventType
	LocationSelectEvenType

	TemplateSendJobFinishEventType
)

type Music

type Music struct {
	Title        CDATAString
	Description  CDATAString
	MusicUrl     CDATAString
	HQMusicUrl   CDATAString
	ThumbMediaId string
}

func NewMusic

func NewMusic(title, description, musicUrl, HQMusicUrl, thumbMediaId string) Music

type MusicResponseMessage

type MusicResponseMessage struct {
	XMLName      xml.Name `xml:"xml"`
	ToUserName   string
	FromUserName string
	CreateTime   int64
	MsgType      string
	Music        Music
}

func NewMusicResponseMessage

func NewMusicResponseMessage(to, from string, music Music) MusicResponseMessage

type PicListItem

type PicListItem struct {
	Item PicMd5Sum `xml:"item"`
}

type PicMd5Sum

type PicMd5Sum struct {
	PicMd5Sum string
}

type Request

type Request interface {
	ToUserName() string
	FromUserName() string
	CreateTime() int
	MsgType() MsgType
	Content() string
	MsgId() int64
	PicUrl() string
	MediaId() string
	Format() string
	Recognition() string
	ThumbMediaId() string
	LocationX() float64
	LocationY() float64
	Scale() int
	Label() string
	Title() string
	Description() string
	Url() string
	Event() string
	EventKey() string
	Ticket() string
	Latitude() float32
	Longitude() float32
	Precision() float32

	MenuId() int64
	ScanCodeInfo() ScanCodeInfo
	SendPicsInfo() SendPicsInfo
	SendLocationInfo() SendLocationInfo

	Status() string
}

type Response

type Response interface {
	Success() error
	String(s string) error
	Bytes(b []byte) error
	Response(data interface{}) error
	Text(content string) error
	Image(mediaID string) error
	Voice(mediaID string) error
	Video(video Video) error
	Music(music Music) error
	Article(articles ...ArticleItem) error
}

type Route

type Route struct {
	MsgType MsgType
	Key     string
	Handler Handler
}

type Router

type Router struct {
	// contains filtered or unexported fields
}

func NewRouter

func NewRouter() *Router

func (*Router) Add

func (r *Router) Add(msgType MsgType, key string, route Route)

func (*Router) Find

func (r *Router) Find(c Context)

func (*Router) Get

func (r *Router) Get(msgType MsgType, key string) Handler

type ScanCodeInfo

type ScanCodeInfo struct {
	ScanType   string
	ScanResult string
}

type ScanEventMessage

type ScanEventMessage interface {
	Event() string
	EventKey() string
	Ticket() string
	// contains filtered or unexported methods
}

type ScanSubscribeEventMessage

type ScanSubscribeEventMessage interface {
	Event() string
	EventKey() string
	Ticket() string
	// contains filtered or unexported methods
}

type SendLocationInfo

type SendLocationInfo struct {
	Location_X float64
	Location_Y float64
	Scale      float64
	Label      string
	Poiname    string
}

type SendPicsInfo

type SendPicsInfo struct {
	Count   int
	PicList []PicListItem
}

type ShortVideoMessage

type ShortVideoMessage interface {
	MediaId() string
	ThumbMediaId() string
	MsgId() int64
	// contains filtered or unexported methods
}

type SubscribeEventMessage

type SubscribeEventMessage interface {
	Event() string
	// contains filtered or unexported methods
}

type TextMessage

type TextMessage interface {
	MsgId() int64
	Content() string
	// contains filtered or unexported methods
}

type TextResponseMessage

type TextResponseMessage struct {
	XMLName      xml.Name `xml:"xml"`
	ToUserName   string
	FromUserName string
	CreateTime   int64
	MsgType      string
	Content      CDATAString
}

func NewTextResponseMessage

func NewTextResponseMessage(to, from, content string) TextResponseMessage

type UnsubscribeEventMessage

type UnsubscribeEventMessage interface {
	Event() string
	// contains filtered or unexported methods
}

type Video

type Video struct {
	MediaId     CDATAString
	Title       CDATAString
	Description CDATAString
}

func NewVideo

func NewVideo(mediaId, title, description string) Video

type VideoMessage

type VideoMessage interface {
	MediaId() string
	ThumbMediaId() string
	MsgId() int64
	// contains filtered or unexported methods
}

type VideoResponseMessage

type VideoResponseMessage struct {
	XMLName      xml.Name `xml:"xml"`
	ToUserName   string
	FromUserName string
	CreateTime   int64
	MsgType      string
	Video        Video
}

func NewVideoResponseMessage

func NewVideoResponseMessage(to, from string, video Video) VideoResponseMessage

type VoiceMessage

type VoiceMessage interface {
	MediaId() string
	Recognition() string
	Format() string
	MsgId() int64
	// contains filtered or unexported methods
}

type VoiceResponseMessage

type VoiceResponseMessage struct {
	XMLName      xml.Name `xml:"xml"`
	ToUserName   string
	FromUserName string
	CreateTime   int64
	MsgType      string
	Voice        MediaId
}

func NewVoiceResponseMessage

func NewVoiceResponseMessage(to, from, mediaId string) VoiceResponseMessage

type Wechat

type Wechat struct {
	AppID          string
	AppSecret      string
	Token          string
	EncodingAESKey string
	WechatType     WechatType

	WechatErrorHandler WechatErrorHandler
	// contains filtered or unexported fields
}

func New

func New(appID, appSecret, token, encodingAESKey string, h trader.Handler) (w *Wechat, err error)

func (*Wechat) Decrypt

func (w *Wechat) Decrypt(msgSignature, timestamp, nonce string, data []byte) (d []byte, err error)

func (*Wechat) DefaultHandler

func (w *Wechat) DefaultHandler() Handler

func (*Wechat) Encrypt

func (w *Wechat) Encrypt(d []byte) (b []byte, err error)

func (*Wechat) Image

func (w *Wechat) Image(h Handler)
func (w *Wechat) Link(h Handler)

func (*Wechat) Location

func (w *Wechat) Location(h Handler)

func (*Wechat) LocationEvent

func (w *Wechat) LocationEvent(h Handler)

func (*Wechat) LocationSelectEven

func (w *Wechat) LocationSelectEven(h Handler)

func (*Wechat) MenuClickEvent

func (w *Wechat) MenuClickEvent(h Handler)

func (*Wechat) MenuViewEvent

func (w *Wechat) MenuViewEvent(h Handler)

func (*Wechat) PicPhotoOrAlbumEvent

func (w *Wechat) PicPhotoOrAlbumEvent(h Handler)

func (*Wechat) PicSysphotoEvent

func (w *Wechat) PicSysphotoEvent(h Handler)

func (*Wechat) PicWeixinEvent

func (w *Wechat) PicWeixinEvent(h Handler)

func (*Wechat) ScanEvent

func (w *Wechat) ScanEvent(h Handler)

func (*Wechat) ScanSubscribeEvent

func (w *Wechat) ScanSubscribeEvent(h Handler)

func (*Wechat) ScancodePushEvent

func (w *Wechat) ScancodePushEvent(h Handler)

func (*Wechat) ScancodeWaitmsgEvent

func (w *Wechat) ScancodeWaitmsgEvent(h Handler)

func (*Wechat) Server

func (w *Wechat) Server(rw http.ResponseWriter, r *http.Request)

func (*Wechat) SetDefaultHandler

func (w *Wechat) SetDefaultHandler(h Handler)

func (*Wechat) SetEncodingAesKey

func (w *Wechat) SetEncodingAesKey(encodingAESKey string) (err error)

func (*Wechat) ShortVideo

func (w *Wechat) ShortVideo(h Handler)

func (*Wechat) SubscribeEvent

func (w *Wechat) SubscribeEvent(h Handler)

func (*Wechat) TemplateSendJobFinishEvent

func (w *Wechat) TemplateSendJobFinishEvent(h Handler)

func (*Wechat) Text

func (w *Wechat) Text(h Handler)

func (*Wechat) Trader

func (w *Wechat) Trader() *trader.Trader

func (*Wechat) UnsubscribeEvent

func (w *Wechat) UnsubscribeEvent(h Handler)

func (*Wechat) Use

func (w *Wechat) Use(m ...Middleware)

func (*Wechat) Voice

func (w *Wechat) Voice(h Handler)

type WechatErrorHandler

type WechatErrorHandler func(error, Context) error

type WechatType

type WechatType int

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL