weixin

package module
v0.0.0-...-2a45edf Latest Latest
Warning

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

Go to latest
Published: Mar 9, 2015 License: MIT Imports: 21 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

微信公众平台库 – Go语言版本

简介

这是一个使用Go语言对微信公众平台的封装。参考了微信公众平台API文档

Build Status GoDoc

入门

安装

通过执行下列语句就可以完成安装

go get github.com/wizjin/weixin
注册微信公众平台

注册微信公众平台,填写验证微信公众平台的Token

示例
package main

import (
	"github.com/wizjin/weixin"
	"net/http"
)

// 文本消息的处理函数
func Echo(w weixin.ResponseWriter, r *weixin.Request) {
	txt := r.Content			// 获取用户发送的消息
	w.ReplyText(txt)			// 回复一条文本消息
	w.PostText("Post:" + txt)	// 发送一条文本消息
}

// 关注事件的处理函数
func Subscribe(w weixin.ResponseWriter, r *weixin.Request) {
	w.ReplyText("欢迎关注") // 有新人关注,返回欢迎消息
}

func main() {
	// my-token 验证微信公众平台的Token
	// app-id, app-secret用于高级API调用。
	// 如果仅使用接收/回复消息,则可以不填写,使用下面语句
	// mux := weixin.New("my-token", "", "")
	mux := weixin.New("my-token", "app-id", "app-secret")
	// 注册文本消息的处理函数
	mux.HandleFunc(weixin.MsgTypeText, Echo)
	// 注册关注事件的处理函数
	mux.HandleFunc(weixin.MsgTypeEventSubscribe, Subscribe)
	http.Handle("/", mux) // 注册接收微信服务器数据的接口URI
	http.ListenAndServe(":80", nil) // 启动接收微信数据服务器
}

微信公众平台要求在收到消息后5秒内回复消息(Reply接口) 如果时间操作很长,则可以使用Post接口发送消息

处理函数

处理函数的定义可以使用下面的形式

func Func(w weixin.ResponseWriter, r *weixin.Request) {
	...
}

可以注册的处理函数类型有以下几种

  • weixin.MsgTypeText 接收文本消息
  • weixin.MsgTypeImage 接收图片消息
  • weixin.MsgTypeVoice 接收语音消息
  • weixin.MsgTypeVideo 接收视频消息
  • weixin.MsgTypeLocation 接收地理位置消息
  • weixin.MsgTypeLink 接收链接消息
  • weixin.MsgTypeEventSubscribe 接收关注事件
  • weixin.MsgTypeEventUnsubscribe 接收取消关注事件
  • weixin.MsgTypeEventScan 接收扫描二维码事件
  • weixin.MsgTypeEventClick 接收自定义菜单事件
发送被动响应消息

需要发送被动响应消息,可通过weixin.ResponseWriter的下列方法完成

  • ReplyText(text) 回复文本消息
  • ReplyImage(mediaId) 回复图片消息
  • ReplyVoice(mediaId) 回复语音消息
  • ReplyVideo(mediaId, title, description) 回复视频消息
  • ReplyMusic(music) 回复音乐消息
  • ReplyNews(articles) 回复图文消息
发送客服消息
  • PostText(text) 发送文本消息
  • PostImage(mediaId) 发送图片消息
  • PostVoice(mediaId) 发送语音消息
  • PostVideo(mediaId, title, description) 发送视频消息
  • PostMusic(music) 发送音乐消息
  • PostNews(articles) 发送图文消息
上传/下载多媒体文件

使用如下函数可以用来上传多媒体文件:

UploadMediaFromFile(mediaType string, filepath string)

示例 (用一张本地图片来返回图片消息):

func ReciveMessage(w weixin.ResponseWriter, r *weixin.Request) {
	mediaId, err := w.UploadMediaFromFile(weixin.MediaTypeImage, "/my-file-path") // 上传本地文件并获取MediaID
	if err != nil {
		w.ReplyText("保存图片失败")
	} else {
		w.ReplyImage(mediaId)	// 利用获取的MediaId来返回图片消息
	}
}

使用如下函数可以用来下载多媒体文件:

DownloadMediaToFile(mediaId string, filepath string)

示例 (收到一条图片消息,然后保存图片到本地文件):

func ReciveImageMessage(w weixin.ResponseWriter, r *weixin.Request) {
	err := w.DownloadMediaToFile(r.MediaId, "/my-file-path") // 下载文件并保存到本地
	if err != nil {
		w.ReplyText("保存图片失败")
	} else {
		w.ReplyText("保存图片成功")
	}
}

参考连接

版权声明

This project is licensed under the MIT license, see LICENSE.

更新日志

Version 0.4 - upcoming
  • 创建/换取二维码
Version 0.3 - 2014/01/07
  • 多媒体文件处理:上传/下载多媒体文件
Version 0.2 - 2013/12/19
  • 发送客服消息:文本消息,图片消息,语音消息,视频消息,音乐消息,图文消息
Version 0.1 – 2013/12/17
  • Token验证URL有效性
  • 接收普通消息:文本消息,图片消息,语音消息,视频消息,地理位置消息,链接消息
  • 接收事件推送:关注/取消关注,扫描二维码事件,上报地理位置,自定义菜单
  • 发送被动响应消息:文本消息,图片消息,语音消息,视频消息,音乐消息,图文消息

Documentation

Overview

Weixin MP SDK (Golang)

Index

Constants

View Source
const (
	QR_SCENE       = "QR_SCENE"
	QR_LIMIT_SCENE = "QR_LIMIT_SCENE"

	EventSubscribe   = "subscribe"
	EventUnsubscribe = "unsubscribe"
	EventScan        = "SCAN"
	EventClick       = "CLICK"
	// Message type
	MsgTypeDefault          = ".*"
	MsgTypeText             = "text"
	MsgTypeImage            = "image"
	MsgTypeVoice            = "voice"
	MsgTypeVideo            = "video"
	MsgTypeLocation         = "location"
	MsgTypeLink             = "link"
	MsgTypeEvent            = msgEvent + ".*"
	MsgTypeEventSubscribe   = msgEvent + "\\." + EventSubscribe
	MsgTypeEventUnsubscribe = msgEvent + "\\." + EventUnsubscribe
	MsgTypeEventScan        = msgEvent + "\\." + EventScan
	MsgTypeEventClick       = msgEvent + "\\." + EventClick

	// Media type
	MediaTypeImage = "image"
	MediaTypeVoice = "voice"
	MediaTypeVideo = "video"
	MediaTypeThumb = "thumb"
)

Variables

This section is empty.

Functions

func Int64Assert

func Int64Assert(val interface{}) int64

func ParseCreateTime

func ParseCreateTime(createTime interface{}) time.Time

func SetLogger

func SetLogger(aLogger *log.FactorLog)

Types

type Article

type Article struct {
	Title       string `json:"title"`
	Description string `json:"description"`
	PicUrl      string `json:"picurl"`
	Url         string `json:"url"`
}

Use to reply news message

type Button

type Button struct {
	Type      string  `json:"type,omitempty"`
	Name      string  `json:"name,omitempty"`
	Key       string  `json:"key,omitempty"`
	Url       string  `json:"url,omitempty"`
	SubButton *Button `json:"sub_button,omitempty"`
}

type Group

type Group struct {
	Id   uint64 `json:"id,omitempty"`
	Name string `json:"name,omitempty"`
	Num  uint64 `json:"count,omitempty"`
}

type HandlerFunc

type HandlerFunc func(ResponseWriter, *Request)

Callback function

type Menu struct {
	Button []*Button `json:"button,omitempty"`
}

type MessageHeader

type MessageHeader struct {
	ToUserName   string
	FromUserName string
	CreateTime   int
	MsgType      string
}

Common message header

type Music

type Music struct {
	Title        string `json:"title"`
	Description  string `json:"description"`
	MusicUrl     string `json:"musicurl"`
	HQMusicUrl   string `json:"hqmusicurl"`
	ThumbMediaId string `json:"thumb_media_id"`
}

Use to reply music message

type Request

type Request struct {
	MessageHeader
	MsgId        int64
	Content      string
	PicUrl       string
	MediaId      string
	Format       string
	ThumbMediaId string
	LocationX    float32 `xml:"Location_X"`
	LocationY    float32 `xml:"Location_Y"`
	Scale        float32
	Label        string
	Title        string
	Description  string
	Url          string
	Event        string
	EventKey     string
	Ticket       string
	Latitude     float32
	Longitude    float32
	Precision    float32
	Recognition  string
	FormValues   url.Values
}

Weixin request

type ResponseWriter

type ResponseWriter interface {
	// Reply message
	ReplyText(text string)
	ReplyImage(mediaId string)
	ReplyVoice(mediaId string)
	ReplyVideo(mediaId string, title string, description string)
	ReplyMusic(music *Music)
	ReplyNews(articles []Article)
	// Post message
	PostText(text string) error
	PostImage(mediaId string) error
	PostVoice(mediaId string) error
	PostVideo(mediaId string, title string, description string) error
	PostMusic(music *Music) error
	PostNews(articles []Article) error
	// Media operator
	UploadMediaFromFile(mediaType string, filepath string) (string, error)
	DownloadMediaToFile(mediaId string, filepath string) error
	UploadMedia(mediaType string, filename string, reader io.Reader) (string, error)
	DownloadMedia(mediaId string, writer io.Writer) error
	// Group operator
	CreateGroup(name string) (*Group, error)
	GetGroups() ([]Group, error)
	GetUserGroup(openId string) (*Group, error)
	ChangeGroupName(group *Group) error
	ChangeUserGroup(openId string, groupId uint64) error
	// User operator
	GetUser(openId string, lang string) (*User, error)
	GetSubscribers(nextOpenId string) (*Subscribers, error)
	GetSubscribersWithInfo(nextOpenId string) (*Subscribers, []*User, error)
	// Menu operator
	CreateMenu(menu *Menu) error
	DeleteMenu() error
	// Orcode operator
	CreateQrcode(sceneId uint64) (*TicketReply, error)
	CreateTempQrcode(sceneId uint64, expireSeconds uint) (*TicketReply, error)
	ShowQrcode(sceneId uint64) error
	ShowTempQrcode(sceneId uint64, expireSeconds uint) error
	// Helper
	PgDB() *pg.DB
	App() string
	Wx() *Weixin
}

Use to output reply

type SceneParams

type SceneParams struct {
	Expires  uint64    `json:"expires,omitempty"`
	Callback string    `json:"callback"`
	Created  time.Time `json:"-"`
}

type ScenesMap

type ScenesMap struct {
	Mutex  *sync.Mutex
	Scenes map[uint64]SceneParams
}

type Subscribers

type Subscribers struct {
	Total uint64 `json:"total"`
	Count uint32 `json:"count"`
	Data  struct {
		OpenId []string `json:"openid"`
	} `json:"data"`
	NextOpenId string `json:"next_openid"`
}

type TicketReply

type TicketReply struct {
	Ticket        string `json:"ticket"`
	ExpireSeconds uint   `json:"expire_seconds"`
}

type User

type User struct {
	Subscribe       uint8  `json:"subscribe"`
	OpenId          string `json:"openid"`
	Nick            string `json:"nickname"`
	Sex             uint8  `json:"sex"`
	City            string `json:"city"`
	Country         string `json:"country"`
	Province        string `json:"province"`
	Language        string `json:"language"`
	HeadImgUrl      string `json:"headimgurl"`
	SubscribeTime   uint64 `json:"subscribe_time"`
	UnsubscribeTime uint64 `json:"unsubscribe_time"`
	GroupId         uint64 `json:"groupid"`
}

type Weixin

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

func New

func New(app string, token string, appid string, secret string) *Weixin

Create a Weixin instance

func (*Weixin) ChangeGroupName

func (wx *Weixin) ChangeGroupName(group *Group) error

Change Group Name

func (*Weixin) ChangeUserGroup

func (wx *Weixin) ChangeUserGroup(openId string, groupId uint64) error

Change User Group

func (*Weixin) CreateGroup

func (wx *Weixin) CreateGroup(name string) (group *Group, err error)

Create Group

func (*Weixin) CreateMenu

func (wx *Weixin) CreateMenu(menu *Menu) error

Create Menu

func (*Weixin) CreateQrcode

func (wx *Weixin) CreateQrcode(sceneId uint64) (ticketReply *TicketReply, err error)

Create Permenent Qrcode

func (*Weixin) CreateTempQrcode

func (wx *Weixin) CreateTempQrcode(sceneId uint64, expireSeconds uint) (ticketReply *TicketReply, err error)

Create Temperary Qrcode

func (*Weixin) DeleteMenu

func (wx *Weixin) DeleteMenu() error

Create Menu

func (*Weixin) DownloadMedia

func (wx *Weixin) DownloadMedia(mediaId string, writer io.Writer) error

Download media with media

func (*Weixin) DownloadMediaToFile

func (wx *Weixin) DownloadMediaToFile(mediaId string, fp string) error

Download media and save to local file

func (*Weixin) GetGroups

func (wx *Weixin) GetGroups() (groups []Group, err error)

Get Groups

func (*Weixin) GetQrcodeImage

func (wx *Weixin) GetQrcodeImage(sceneId uint64) ([]byte, http.Header, int, error)

Get Qrcode Image

func (*Weixin) GetSubscribers

func (wx *Weixin) GetSubscribers(nextOpenId string) (subscribers *Subscribers, err error)

Get Subscribers

func (*Weixin) GetTempQrcodeImage

func (wx *Weixin) GetTempQrcodeImage(sceneId uint64, expireSeconds uint) ([]byte, http.Header, int, error)

Get Temperary Qrcode Image

func (*Weixin) GetUser

func (wx *Weixin) GetUser(openId string, lang string) (user *User, err error)

Get User Info

func (*Weixin) GetUserGroup

func (wx *Weixin) GetUserGroup(openId string) (group *Group, err error)

Get User Group

func (*Weixin) HandleFunc

func (wx *Weixin) HandleFunc(pattern string, handler HandlerFunc)

Register request callback.

func (*Weixin) PostImage

func (wx *Weixin) PostImage(touser string, mediaId string) error

Post image message

func (*Weixin) PostMusic

func (wx *Weixin) PostMusic(touser string, music *Music) error

Post music message

func (*Weixin) PostNews

func (wx *Weixin) PostNews(touser string, articles []Article) error

Post news message

func (*Weixin) PostText

func (wx *Weixin) PostText(touser string, text string) error

Post text message

func (*Weixin) PostVideo

func (wx *Weixin) PostVideo(touser string, m string, t string, d string) error

Post video message

func (*Weixin) PostVoice

func (wx *Weixin) PostVoice(touser string, mediaId string) error

Post voice message

func (*Weixin) ServeHTTP

func (wx *Weixin) ServeHTTP(w http.ResponseWriter, r *http.Request)

Process weixin request and send response.

func (*Weixin) SetDb

func (wx *Weixin) SetDb(db *pg.DB)

func (*Weixin) UploadMedia

func (wx *Weixin) UploadMedia(mediaType string, filename string, reader io.Reader) (string, error)

Upload media with media

func (*Weixin) UploadMediaFromFile

func (wx *Weixin) UploadMediaFromFile(mediaType string, fp string) (string, error)

Upload media from local file

Directories

Path Synopsis
cmd
weixin command

Jump to

Keyboard shortcuts

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