The wechat SDK developed by Golang is simple and easy to use.
Quick start
Here is an example of handling a message receive and reply:
// Set wechat parameters config := &wechat.Config{AppID: "XXXX ", AppSecret:" XXXX ", Token: "XXXX ", EncodingAESKey:" XXXX ", Cache: Responsewriterserver := responsewriterServer (responsewriterServer, responsewriterServer, responsewriterServer); ResponseWriter) server.setMessageHandler (func(MSG message.mixmessage) * message.reply { Text := message.newtext (msg.content) return & message.reply {message.msgtext, text} }) server.Serve() server.Send()Copy the code
Complete code: examples/ HTTP /http.go
Request and responseWriter may be obtained differently in different frameworks:
- Beego: ./examples/beego/beego.go
- Gin Framework: ./examples/gin/gin.go
The basic configuration
Memcache := cache.NewMemcache("127.0.0.1:11211") wcConfig := &wechat.Config{AppID: cfg.AppID, AppSecret: CFG.AppSecret, Token: CFG.Token, EncodingAESKey: cfg.EncodingAESKey,Copy the code
The Cache Settings
Cache is used to store global access_token and ticket in JS-SDK. Memcache is used by default. It is also possible to implement the cache/cache.go interface directly
- The message management
- Receiving ordinary messages
- Receiving Event Push
- Passive reply message
- Reply text message
- Reply to picture message
- Reply to video messages
- Reply to music messages
- Reply to graphic message
- Custom menu
- Custom menu creation interface
- Custom menu query interface
- Custom menu delete interface
- Custom menu event push
- Personalized menu interface
- Add personalized menu
- Delete personalized menu
- Test personalized menu matching results
- Obtain the public account menu configuration
- Wechat web page development
- Oauth2 authorization
- By authorized
- Access access_token by code
- Pull user information
- Refresh the access_token
- Verify that the access_token is valid
- Get the JS-SDK configuration
- Oauth2 authorization
- Material management
The message management
Get the server object via wechat.GetServer(Request,responseWriter)
Call SetMessageHandler(func(MSG message.mixmessage){}) to set the message handler.
Type MixMessage struct {CommonToken} MsgID int64 'XML :" MsgID "' Content string `xml:"Content"` PicURL string `xml:"PicUrl"` MediaID string `xml:"MediaId"` Format string `xml:"Format"` ThumbMediaID string `xml:"ThumbMediaId"` LocationX float64 `xml:"Location_X"` LocationY float64 `xml:"Location_Y"` Scale float64 `xml:"Scale"` Label string `xml:"Label"` Title string `xml:"Title"` Description string `xml:"Description"` URL string 'XML :"Url"' // Event-related Event String 'XML :"Event"' EventKey String 'XML :"EventKey"' Ticket string 'XML :"Ticket"' Latitude string `xml:"Latitude"` Longitude string `xml:"Longitude"` Precision string `xml:"Precision"` MenuID string ScanCodeInfo struct {ScanType string 'XML :"ScanType"' ScanResult string 'XML :"ScanResult"'} Struct {Count int32 'XML :"Count"' PicList '[]EventPic' XML :"PicList>item" '} SendLocationInfo struct {LocationX Float64 'XML :"Location_X"' LocationY float64 ' `xml:"Location_Y"` Scale float64 `xml:"Scale"` Label string `xml:"Label"` Poiname string `xml:"Poiname"` } }Copy the code
For details, see the wechat documentation: Receiving Ordinary Messages
Server.setmessagehandler (func(v message.mixmessage) * message.reply {switch v.mstype {// text message case message.msgtypeText: //do something // MsgTypeImage: //do something // MsgTypeVoice: / / do something / / video news case message. MsgTypeVideo: / / do something / / small video news case message. MsgTypeShortVideo: // Do something // Location message case message.MsgTypeLocation: //do something // link message case message.MsgTypeLink: Case message.msgTypeEvent:}}Copy the code
Receiving Event Push
MsgTypeEvent: switch v.vent {// subscribe case message. Subscribe: / / do something / / unsubscribe case message. EventUnsubscribe: // If the user has followed the public account, wechat will push the event with the scene value to the developer case message.EventScan: EventClick: // Do something //do something // / / do something/jump/click menu link in case of event push message. The EventView: / / do something / / scan code push case message. The events of the push EventScancodePush: / / do something / / scan code push event and pop-up "message receiving" prompt box case of event push message. EventScancodeWaitmsg: / / do something / / pop-up system pictures hair figure event push case message. EventPicSysphoto: / / do something / / pop-up pictures or albums hair figure event push case message. EventPicPhotoOrAlbum: // Do something // pop up wechat photo album event push case message.EventPicWeixin: / / do something / / pop-up geographical position selector case of event push message. EventLocationSelect: / / do something}Copy the code
The *message.Reply object has the following structure:
Type Reply struct {MsgType MsgType MsgData interface{}Copy the code
Note: Retrun nil means do nothing, right
Reply text message
Text := message.newtext (" message.msgtypetext ") return & message.reply {message.msgtypetext, text}Copy the code
Image := message.newVideo ("mediaID") return & message.reply {message.msgtypevideo, image}Copy the code
Reply to video messages
Video := message.newVideo ("mediaID", "mediaID", "video description ") return & message.reply {message.msgtypeVideo, video}Copy the code
music := message.NewMusic("title", "description", "musicURL", "hQMusicURL", "thumbMediaID")
return &message.Reply{message.MsgTypeMusic,music}Copy the code
Field Description:
Title: Music Title
Description: Music Description
MusicURL: Music links
HQMusicUrl: High quality music link, WIFI environment preferentially use this link to play music
ThumbMediaId: The media ID of the thumbnail, obtained by uploading multimedia files through the Image Management interface
Reply to graphic message
articles := make([]*message.Article, 1) article := new(message.article) article.Title = "Title" article.Description = "Description" article "http://ww1.sinaimg.cn/large/65209136gw1f7vhjw95eqj20wt0zk40z.jpg" article.URL = "https://github.com/silenceper/wechat" articles[0] = article news := message.NewNews(articles) return &message.Reply{message.MsgTypeNews,news}Copy the code
Field Description:
Title: Graphic message Title
Description: Description of the text message
PicUrl: image link, support JPG, PNG format, the better effect is 360200, small image 200200
Url: Click the text message jump link
Obtain the menu instance through wechat.GetMenu(req, writer)
Custom menu creation interface
Here is an example of creating a secondary menu
mu := wc.GetMenu(c.Request, c.Writer) buttons := make([]*menu.Button, 1) BTN := new(menu.Button) // create click menu BTN.SetClickButton("name", Buttons [0] = btn2 := new(menu.Button) btn2.SetSubButton("subButton", Buttons) buttons2 := make([]*menu.Button, 1) buttons2[0] = btn2 // Err := mu.setmenu (buttons2) if err! = nil { fmt.Printf("err= %v", err) return }Copy the code
Create other types of menus:
Func (BTN *Button) SetViewButton(name, Func (BTN *Button) SetScanCodePushButton(name, SetScanCodePushButton) Key string) / / SetScanCodeWaitMsgButton sweep code push event set and the pop-up "message receivers" prompt box func (BTN * Button) SetScanCodeWaitMsgButton (name, Func (BTN *Button) SetPicSysPhotoButton(name, SetPicSysPhotoButton) Key string) / / SetPicPhotoOrAlbumButton pop up pictures or albums hair figure type Button func (BTN * Button) SetPicPhotoOrAlbumButton (name, Func (BTN *Button) SetPicWeixinButton(name, SetPicWeixinButton) Func (BTN *Button) SetLocationSelectButton(name, SetLocationSelectButton) Func (BTN *Button) SetMediaIDButton(name, SetMediaIDButton) Func (BTN *Button) SetViewLimitedButton(name, mediaID String) {SetViewLimitedButton(BTN *Button) {Copy the code
mu := wc.GetMenu(c.Request, c.Writer)
resMenu,err:=mu.GetMenu()Copy the code
Return Result resMenu structure reference resMenu structure in./menu/menu.go
Custom menu delete interface
mu := wc.GetMenu(c.Request, c.Writer)
err:=mu.DeleteMenu()Copy the code
See Message Management – Event Push
Personalized menu interface
Add personalized menu
func (menu *Menu) AddConditional(buttons []*Button, matchRule *MatchRule) errorCopy the code
Delete personalized menu
// Delete personalized menu func (menu * menu) DeleteConditional(menuID INT64) errorCopy the code
Test personalized menu matching results
Func (menu * menu) MenuTryMatch(userID string) (buttons []Button, err Error) {func (menu * menu) MenuTryMatch(userID string) (buttons []Button, err Error) {Copy the code
Func (menu * menu) GetCurrentSelfMenuInfo() (resSelfMenuInfo resSelfMenuInfo, err Error)Copy the code
Wechat web page development
Please refer to wechat document: Webpage Authorization for specific authorization process
1. Initiate authorization
Oauth := Wc.getoauth (c. balance, c. Riter) err := Oauth. Redirect(" Absolute address to Redirect ", "snsapi_userinfo", "123DD123 ") if err! = nil { fmt.Println(err) }Copy the code
If you do not want to go to the url directly, run oauth.GetRedirectURL to obtain the url
2. Exchange the access_token using code
code := c.Query("code") resToken, err := oauth.GetUserAccessToken(code) if err ! = nil { fmt.Println(err) return }Copy the code
3. Pull user information (scope is snsapi_userinfo)
//getUserInfo userInfo, err := oauth.GetUserInfo(resToken.AccessToken, resToken.OpenID) if err ! = nil { fmt.Println(err) return } fmt.Println(userInfo)Copy the code
Refresh the access_token
func (oauth *Oauth) RefreshAccessToken(refreshToken string) (result ResAccessToken, err error)
Copy the code
Verify that the access_token is valid
func (oauth *Oauth) CheckAccessToken(accessToken, openID string) (b bool, err error)Copy the code
Get the JS-SDK configuration
CFG, err := js.getConfig (" pass in the required url to call js-SDK ") if err! = nil { fmt.Println(err) return } fmt.Println(cfg)Copy the code
The CFG structure is as follows:
type Config struct {
AppID string
TimeStamp int64
NonceStr string
Signature string
}
Copy the code
Story management API
For more API usage, see godoc: godoc.org/github.com/…
License
The Apache License, Version 2.0