1 Star 0 Fork 0

刘超 / wechat

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
Apache-2.0

WeChat SDK for Go

Build Status Go Report Card GoDoc

使用Golang开发的微信SDK,简单、易用。

快速开始

以下是一个处理消息接收以及回复的例子:

//使用memcache保存access_token,也可选择redis或自定义cache
memCache=cache.NewMemcache("127.0.0.1:11211")

//配置微信参数
config := &wechat.Config{
	AppID:          "xxxx",
	AppSecret:      "xxxx",
	Token:          "xxxx",
	EncodingAESKey: "xxxx",
	Cache:          memCache
}
wc := wechat.NewWechat(config)

// 传入request和responseWriter
server := wc.GetServer(request, responseWriter)
server.SetMessageHandler(func(msg message.MixMessage) *message.Reply {

	//回复消息:演示回复用户发送的消息
	text := message.NewText(msg.Content)
	return &message.Reply{message.MsgTypeText, text}
})

server.Serve()
server.Send()

完整代码:examples/http/http.go

和主流框架配合使用

主要是request和responseWriter在不同框架中获取方式可能不一样:

基本配置

memcache := cache.NewMemcache("127.0.0.1:11211")

wcConfig := &wechat.Config{
	AppID:          cfg.AppID,
	AppSecret:      cfg.AppSecret,
	Token:          cfg.Token,
	EncodingAESKey: cfg.EncodingAESKey,//消息加解密时用到
	Cache:          memcache,
}

Cache 设置

Cache主要用来保存全局access_token以及js-sdk中的ticket: 默认采用memcache存储。当然也可以直接实现cache/cache.go中的接口

基本API使用

  • 消息管理
    • 接收普通消息
    • 接收事件推送
    • 被动回复消息
      • 回复文本消息
      • 回复图片消息
      • 回复视频消息
      • 回复音乐消息
      • 回复图文消息
  • 自定义菜单
    • 自定义菜单创建接口
    • 自定义菜单查询接口
    • 自定义菜单删除接口
    • 自定义菜单事件推送
    • 个性化菜单接口
      • 添加个性化菜单
      • 删除个性化菜单
      • 测试个性化菜单匹配结果
    • 获取公众号菜单配置
  • 微信网页开发
    • Oauth2 授权
      • 发起授权
      • 通过code换取access_token
      • 拉取用户信息
      • 刷新access_token
      • 检验access_token是否有效
    • 获取js-sdk配置
  • 素材管理
  • 小程序开发
  • 小程序-云开发

消息管理

通过wechat.GetServer(request,responseWriter)获取到server对象之后

调用SetMessageHandler(func(msg message.MixMessage){})设置消息的处理函数,函数参数为message.MixMessage 结构如下:

//MixMessage 存放所有微信发送过来的消息和事件
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     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 `xml:"MenuId"`

	//扫码事件
	ScanCodeInfo struct {
		ScanType   string `xml:"ScanType"`
		ScanResult string `xml:"ScanResult"`
	} `xml:"ScanCodeInfo"`

	//发图事件
	SendPicsInfo struct {
		Count   int32      `xml:"Count"`
		PicList []EventPic `xml:"PicList>item"`
	} `xml:"SendPicsInfo"`

	//发送地理位置事件
	SendLocationInfo struct {
		LocationX float64 `xml:"Location_X"`
		LocationY float64 `xml:"Location_Y"`
		Scale     float64 `xml:"Scale"`
		Label     string  `xml:"Label"`
		Poiname   string  `xml:"Poiname"`
	}
}

具体参数请参考微信文档:接收普通消息

接收普通消息

server.SetMessageHandler(func(v message.MixMessage) *message.Reply {
		switch v.MsgType {
		//文本消息
		case message.MsgTypeText:
			//do something

			//图片消息
		case message.MsgTypeImage:
			//do something

			//语音消息
		case message.MsgTypeVoice:
			//do something

			//视频消息
		case message.MsgTypeVideo:
			//do something

			//小视频消息
		case message.MsgTypeShortVideo:
			//do something

			//地理位置消息
		case message.MsgTypeLocation:
			//do something

			//链接消息
		case message.MsgTypeLink:
			//do something

			//事件推送消息
		case message.MsgTypeEvent:

		}
}

接收事件推送

//事件推送消息
case message.MsgTypeEvent:
	switch v.Event {
		//EventSubscribe 订阅
		case message.EventSubscribe:
			//do something

			//取消订阅
		case message.EventUnsubscribe:
			//do something

			//用户已经关注公众号,则微信会将带场景值扫描事件推送给开发者
		case message.EventScan:
			//do something

			// 上报地理位置事件
		case message.EventLocation:
			//do something

			// 点击菜单拉取消息时的事件推送
		case message.EventClick:
			//do something

			// 点击菜单跳转链接时的事件推送
		case message.EventView:
			//do something

			// 扫码推事件的事件推送
		case message.EventScancodePush:
			//do something

			// 扫码推事件且弹出“消息接收中”提示框的事件推送
		case message.EventScancodeWaitmsg:
			//do something

			// 弹出系统拍照发图的事件推送
		case message.EventPicSysphoto:
			//do something

			// 弹出拍照或者相册发图的事件推送
		case message.EventPicPhotoOrAlbum:
			//do something

			// 弹出微信相册发图器的事件推送
		case message.EventPicWeixin:
			//do something

			// 弹出地理位置选择器的事件推送
		case message.EventLocationSelect:
			//do something

	}

被动回复消息

回复消息需要返回 *message.Reply 对象结构体如下:

type Reply struct {
	MsgType MsgType  //消息类型
	MsgData interface{}  //消息结构
}

注意:return nil表示什么也不做

回复文本消息

	text := message.NewText("回复文本消息")
	return &message.Reply{message.MsgTypeText, text}

回复图片消息

//mediaID 可通过素材管理-上上传多媒体文件获得
image :=message.NewImage("mediaID")
return &message.Reply{message.MsgTypeImage, image}

回复视频消息

video := message.NewVideo("mediaID", "视频标题", "视频描述")
return &message.Reply{message.MsgTypeVideo, video}

回复音乐消息

music := message.NewMusic("title", "description", "musicURL", "hQMusicURL", "thumbMediaID")
return &message.Reply{message.MsgTypeMusic,music}

字段说明:

Title:音乐标题

Description:音乐描述

MusicURL:音乐链接

HQMusicUrl:高质量音乐链接,WIFI环境优先使用该链接播放音乐

ThumbMediaId:缩略图的媒体id,通过素材管理接口上传多媒体文件,得到的id

回复图文消息

articles := make([]*message.Article, 1)

article := new(message.Article)
article.Title = "标题"
article.Description = "描述信息信息信息"
article.PicURL = "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}

字段说明:

Title:图文消息标题

Description:图文消息描述

PicUrl :图片链接,支持JPG、PNG格式,较好的效果为大图360200,小图200200

Url :点击图文消息跳转链接

自定义菜单

通过 wechat.GetMenu()获取menu的实例

自定义菜单创建接口

以下是一个创建二级菜单的例子

mu := wc.GetMenu()

buttons := make([]*menu.Button, 1)
btn := new(menu.Button)

//创建click类型菜单
btn.SetClickButton("name", "key123")
buttons[0] = btn

//设置btn为二级菜单
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
}

创建其他类型的菜单:

//SetViewButton view类型
func (btn *Button) SetViewButton(name, url string)

// SetScanCodePushButton 扫码推事件
func (btn *Button) SetScanCodePushButton(name, key string)

//SetScanCodeWaitMsgButton 设置 扫码推事件且弹出"消息接收中"提示框
func (btn *Button) SetScanCodeWaitMsgButton(name, key string)

//SetPicSysPhotoButton 设置弹出系统拍照发图按钮
func (btn *Button) SetPicSysPhotoButton(name, key string)

//SetPicPhotoOrAlbumButton 设置弹出拍照或者相册发图类型按钮
func (btn *Button) SetPicPhotoOrAlbumButton(name, key string) {

// SetPicWeixinButton 设置弹出微信相册发图器类型按钮
func (btn *Button) SetPicWeixinButton(name, key string)

// SetLocationSelectButton 设置 弹出地理位置选择器 类型按钮
func (btn *Button) SetLocationSelectButton(name, key string)

//SetMediaIDButton  设置 下发消息(除文本消息) 类型按钮
func (btn *Button) SetMediaIDButton(name, mediaID string)

//SetViewLimitedButton  设置 跳转图文消息URL 类型按钮
func (btn *Button) SetViewLimitedButton(name, mediaID string) {

自定义菜单查询接口

mu := wc.GetMenu()
resMenu,err:=mu.GetMenu()

返回结果 resMenu 结构参考 ./menu/menu.go 中ResMenu 结构体

自定义菜单删除接口

mu := wc.GetMenu()
err:=mu.DeleteMenu()

自定义菜单事件推送

请参考 消息管理 - 事件推送

个性化菜单接口

添加个性化菜单


func (menu *Menu) AddConditional(buttons []*Button, matchRule *MatchRule) error

删除个性化菜单

//删除个性化菜单
func (menu *Menu) DeleteConditional(menuID int64) error

测试个性化菜单匹配结果

//菜单匹配
func (menu *Menu) MenuTryMatch(userID string) (buttons []Button, err error) {

获取公众号菜单配置

//获取自定义菜单配置接口
func (menu *Menu) GetCurrentSelfMenuInfo() (resSelfMenuInfo ResSelfMenuInfo, err error)

微信网页开发

Oauth2 授权

具体授权流程请参考微信文档:网页授权

1.发起授权

oauth := wc.GetOauth()
err := oauth.Redirect("跳转的绝对地址", "snsapi_userinfo", "123dd123")
if err != nil {
	fmt.Println(err)
}

如果不希望直接跳转,可通过 oauth.GetRedirectURL 获取跳转的url

2.通过code换取access_token

code := c.Query("code")
resToken, err := oauth.GetUserAccessToken(code)
if err != nil {
	fmt.Println(err)
	return
}

3.拉取用户信息(需scope为 snsapi_userinfo)

//getUserInfo
userInfo, err := oauth.GetUserInfo(resToken.AccessToken, resToken.OpenID)
if err != nil {
	fmt.Println(err)
	return
}
fmt.Println(userInfo)

刷新access_token

func (oauth *Oauth) RefreshAccessToken(refreshToken string) (result ResAccessToken, err error)

检验access_token是否有效

func (oauth *Oauth) CheckAccessToken(accessToken, openID string) (b bool, err error)

获取js-sdk配置

js := wc.GetJs()
cfg, err := js.GetConfig("传入需要的调用js-sdk的url地址")
if err != nil {
	fmt.Println(err)
	return
}
fmt.Println(cfg)

其中返回的cfg结构体如下:

type Config struct {
	AppID     string `json:"app_id"`
	Timestamp int64  `json:"timestamp"`
	NonceStr  string `json:"nonce_str"`
	Signature string `json:"signature"`
}

素材管理

素材管理API

批量获取永久素材

list, err := wc.GetMaterial().BatchGetMaterial(material.PermanentMaterialTypeNews, 0, 10)
if err != nil {
	fmt.Println(err)
	return
}
fmt.Println(list)

小程序开发

获取小程序操作对象

memCache=cache.NewMemcache("127.0.0.1:11211")
config := &wechat.Config{
	AppID:     "xxx",
	AppSecret: "xxx",
	Cache:     memCache=cache.NewMemcache("127.0.0.1:11211"),
}
wc := wechat.NewWechat(config)

wxa := wc.GetMiniProgram()

小程序登录凭证校验

func (wxa *MiniProgram) Code2Session(jsCode string) (result ResCode2Session, err error)

小程序数据统计

获取用户访问小程序日留存

func (wxa *MiniProgram) GetAnalysisDailyRetain(beginDate, endDate string) (result ResAnalysisRetain, err error)

获取用户访问小程序月留存

func (wxa *MiniProgram) GetAnalysisMonthlyRetain(beginDate, endDate string) (result ResAnalysisRetain, err error)

获取用户访问小程序周留存

func (wxa *MiniProgram) GetAnalysisWeeklyRetain(beginDate, endDate string) (result ResAnalysisRetain, err error)

获取用户访问小程序数据概况

func (wxa *MiniProgram) GetAnalysisDailySummary(beginDate, endDate string) (result ResAnalysisDailySummary, err error)

获取用户访问小程序数据日趋势

func (wxa *MiniProgram) GetAnalysisDailyVisitTrend(beginDate, endDate string) (result ResAnalysisVisitTrend, err error)

获取用户访问小程序数据月趋势

func (wxa *MiniProgram) GetAnalysisMonthlyVisitTrend(beginDate, endDate string) (result ResAnalysisVisitTrend, err error)

获取用户访问小程序数据周趋势

func (wxa *MiniProgram) GetAnalysisWeeklyVisitTrend(beginDate, endDate string) (result ResAnalysisVisitTrend, err error)

获取小程序新增或活跃用户的画像分布数据

func (wxa *MiniProgram) GetAnalysisUserPortrait(beginDate, endDate string) (result ResAnalysisUserPortrait, err error)

获取用户小程序访问分布数据

func (wxa *MiniProgram) GetAnalysisVisitDistribution(beginDate, endDate string) (result ResAnalysisVisitDistribution, err error)

获取小程序页面访问数据

func (wxa *MiniProgram) GetAnalysisVisitPage(beginDate, endDate string) (result ResAnalysisVisitPage, err error)

小程序二维码生成

获取小程序二维码,适用于需要的码数量较少的业务场景

func (wxa *MiniProgram) CreateWXAQRCode(coderParams QRCoder) (response []byte, err error)

获取小程序码,适用于需要的码数量较少的业务场景

func (wxa *MiniProgram) GetWXACode(coderParams QRCoder) (response []byte, err error)

获取小程序码,适用于需要的码数量极多的业务场景

func (wxa *MiniProgram) GetWXACodeUnlimit(coderParams QRCoder) (response []byte, err error)

更多API使用请参考 godoc : https://godoc.org/github.com/silenceper/wechat

License

Apache License, Version 2.0

Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

简介

WeChat SDK for Go (微信SDK:简单、易用) 展开 收起
Go
Apache-2.0
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
1
https://gitee.com/liu-chao-piouyou/wechat.git
git@gitee.com:liu-chao-piouyou/wechat.git
liu-chao-piouyou
wechat
wechat
master

搜索帮助