huangrf 6 anni fa
commit
6a423d7e19

+ 27 - 0
.gitignore

@@ -0,0 +1,27 @@
+# Compiled Object files, Static and Dynamic libs (Shared Objects)
+*.o
+*.a
+*.so
+
+# Folders
+_obj
+_test
+
+# Architecture specific extensions/prefixes
+*.[568vq]
+[568vq].out
+
+*.cgo1.go
+*.cgo2.c
+_cgo_defun.c
+_cgo_gotypes.go
+_cgo_export.*
+
+_testmain.go
+
+*.exe
+*.test
+*.prof
+.DS_Store
+.vscode/
+vendor/*/

+ 20 - 0
.travis.yml

@@ -0,0 +1,20 @@
+language: go
+
+go:
+  - 1.9.x
+  - 1.8.x
+  - 1.7.x
+  - 1.6.x
+
+services:
+  - memcached
+  - redis-server
+
+before_script:
+  - GO_FILES=$(find . -iname '*.go' -type f | grep -v /vendor/)
+  - go get github.com/golang/lint/golint
+    
+script:
+  - go test -v -race ./...
+  - go vet ./...
+  - golint -set_exit_status $(go list ./...)

+ 201 - 0
LICENSE

@@ -0,0 +1,201 @@
+                                 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.

+ 538 - 0
README.md

@@ -0,0 +1,538 @@
+# WeChat SDK for Go
+[![Build Status](https://travis-ci.org/silenceper/wechat.svg?branch=master)](https://travis-ci.org/silenceper/wechat)
+[![Go Report Card](https://goreportcard.com/badge/github.com/silenceper/wechat)](https://goreportcard.com/report/github.com/silenceper/wechat)
+[![GoDoc](http://godoc.org/github.com/silenceper/wechat?status.svg)](http://godoc.org/github.com/silenceper/wechat)
+
+
+使用Golang开发的微信SDK,简单、易用。
+
+## 快速开始
+
+以下是一个处理消息接收以及回复的例子:
+
+```go
+//使用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](./examples/http/http.go)
+
+#### 和主流框架配合使用
+
+主要是request和responseWriter在不同框架中获取方式可能不一样:
+
+- Beego: [./examples/beego/beego.go](./examples/beego/beego.go)
+- Gin Framework: [./examples/gin/gin.go](./examples/gin/gin.go)
+
+## 基本配置
+
+```go
+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 结构如下:
+
+```go
+//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"`
+	}
+}
+
+```
+
+具体参数请参考微信文档:[接收普通消息
+](http://mp.weixin.qq.com/wiki/17/f298879f8fb29ab98b2f2971d42552fd.html)
+
+### 接收普通消息
+```go
+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:
+
+		}
+}
+
+
+```
+
+
+### 接收事件推送
+```go
+//事件推送消息
+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` 对象结构体如下:
+
+```go
+type Reply struct {
+	MsgType MsgType  //消息类型
+	MsgData interface{}  //消息结构
+}
+
+```
+注意:`retrun nil`表示什么也不做
+
+####  回复文本消息
+```go
+	text := message.NewText("回复文本消息")
+	return &message.Reply{message.MsgTypeText, text}
+```
+####  回复图片消息
+```go
+//mediaID 可通过素材管理-上上传多媒体文件获得
+image :=message.NewVideo("mediaID")
+return &message.Reply{message.MsgTypeVideo, image}
+```
+####  回复视频消息
+```go
+video := message.NewVideo("mediaID", "视频标题", "视频描述")
+return &message.Reply{message.MsgTypeVideo, video}
+```
+####  回复音乐消息
+```go
+music := message.NewMusic("title", "description", "musicURL", "hQMusicURL", "thumbMediaID")
+return &message.Reply{message.MsgTypeMusic,music}
+```
+**字段说明:**
+
+Title:音乐标题
+
+Description:音乐描述
+
+MusicURL:音乐链接
+
+HQMusicUrl:高质量音乐链接,WIFI环境优先使用该链接播放音乐
+
+ThumbMediaId:缩略图的媒体id,通过素材管理接口上传多媒体文件,得到的id
+
+####  回复图文消息
+
+```go
+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格式,较好的效果为大图360*200,小图200*200
+
+Url	:点击图文消息跳转链接
+
+
+## 自定义菜单
+
+通过` wechat.GetMenu(req, writer)`获取menu的实例
+
+### 自定义菜单创建接口
+
+以下是一个创建二级菜单的例子
+
+```go
+mu := wc.GetMenu(c.Request, c.Writer)
+
+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
+}
+
+```
+
+**创建其他类型的菜单:**
+
+```go
+//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) {
+
+```
+
+### 自定义菜单查询接口
+
+```go
+mu := wc.GetMenu(c.Request, c.Writer)
+resMenu,err:=mu.GetMenu()
+```
+>返回结果 resMenu 结构参考 ./menu/menu.go 中ResMenu 结构体
+
+### 自定义菜单删除接口
+
+```go
+mu := wc.GetMenu(c.Request, c.Writer)
+err:=mu.DeleteMenu()
+```
+
+### 自定义菜单事件推送
+
+ 请参考 消息管理 - 事件推送
+
+### 个性化菜单接口
+**添加个性化菜单**
+
+```go
+
+func (menu *Menu) AddConditional(buttons []*Button, matchRule *MatchRule) error
+```
+
+**删除个性化菜单**
+
+```go
+//删除个性化菜单
+func (menu *Menu) DeleteConditional(menuID int64) error
+
+```
+**测试个性化菜单匹配结果**
+
+```go
+//菜单匹配
+func (menu *Menu) MenuTryMatch(userID string) (buttons []Button, err error) {
+
+```
+
+### 获取公众号菜单配置
+
+```go
+//获取自定义菜单配置接口
+func (menu *Menu) GetCurrentSelfMenuInfo() (resSelfMenuInfo ResSelfMenuInfo, err error)
+
+```
+
+## 微信网页开发
+
+### Oauth2 授权
+
+具体授权流程请参考微信文档:[网页授权](http://mp.weixin.qq.com/wiki/4/9ac2e7b1f1d22e9e57260f6553822520.html)
+
+**1.发起授权**
+
+```go
+oauth := wc.GetOauth(c.Request, c.Writer)
+err := oauth.Redirect("跳转的绝对地址", "snsapi_userinfo", "123dd123")
+if err != nil {
+	fmt.Println(err)
+}
+
+```
+> 如果不希望直接跳转,可通过 oauth.GetRedirectURL 获取跳转的url
+
+**2.通过code换取access_token**
+
+```go
+code := c.Query("code")
+resToken, err := oauth.GetUserAccessToken(code)
+if err != nil {
+	fmt.Println(err)
+	return
+}
+
+```
+**3.拉取用户信息(需scope为 snsapi_userinfo)**
+
+```go
+//getUserInfo
+userInfo, err := oauth.GetUserInfo(resToken.AccessToken, resToken.OpenID)
+if err != nil {
+	fmt.Println(err)
+	return
+}
+fmt.Println(userInfo)
+
+```
+**刷新access_token**
+
+```go
+func (oauth *Oauth) RefreshAccessToken(refreshToken string) (result ResAccessToken, err error)
+
+```
+**检验access_token是否有效**
+
+```go
+func (oauth *Oauth) CheckAccessToken(accessToken, openID string) (b bool, err error)
+```
+
+### 获取js-sdk配置
+
+```go
+js := wc.GetJs(c.Request, c.Writer)
+cfg, err := js.GetConfig("传入需要的调用js-sdk的url地址")
+if err != nil {
+	fmt.Println(err)
+	return
+}
+fmt.Println(cfg)
+```
+其中返回的cfg结构体如下:
+
+```go
+type Config struct {
+	AppID     string `json:"app_id"`
+	Timestamp int64  `json:"timestamp"`
+	NonceStr  string `json:"nonce_str"`
+	Signature string `json:"signature"`
+}
+
+```
+
+## 素材管理
+
+[素材管理API](https://godoc.org/github.com/silenceper/wechat/material#Material)
+
+
+更多API使用请参考 godoc :
+[https://godoc.org/github.com/silenceper/wechat](https://godoc.org/github.com/silenceper/wechat)
+
+## License
+
+Apache License, Version 2.0

+ 11 - 0
cache/cache.go

@@ -0,0 +1,11 @@
+package cache
+
+import "time"
+
+//Cache interface
+type Cache interface {
+	Get(key string) interface{}
+	Set(key string, val interface{}, timeout time.Duration) error
+	IsExist(key string) bool
+	Delete(key string) error
+}

+ 57 - 0
cache/memcache.go

@@ -0,0 +1,57 @@
+package cache
+
+import (
+	"encoding/json"
+	"time"
+
+	"github.com/bradfitz/gomemcache/memcache"
+)
+
+//Memcache struct contains *memcache.Client
+type Memcache struct {
+	conn *memcache.Client
+}
+
+//NewMemcache create new memcache
+func NewMemcache(server ...string) *Memcache {
+	mc := memcache.New(server...)
+	return &Memcache{mc}
+}
+
+//Get return cached value
+func (mem *Memcache) Get(key string) interface{} {
+	var err error
+	var item *memcache.Item
+	if item, err = mem.conn.Get(key); err != nil {
+		return nil
+	}
+	var result interface{}
+	if err = json.Unmarshal(item.Value, &result); err != nil {
+		return nil
+	}
+	return result
+}
+
+// IsExist check value exists in memcache.
+func (mem *Memcache) IsExist(key string) bool {
+	if _, err := mem.conn.Get(key); err != nil {
+		return false
+	}
+	return true
+}
+
+//Set cached value with key and expire time.
+func (mem *Memcache) Set(key string, val interface{}, timeout time.Duration) (err error) {
+	var data []byte
+	if data, err = json.Marshal(val); err != nil {
+		return err
+	}
+
+	item := &memcache.Item{Key: key, Value: data, Expiration: int32(timeout / time.Second)}
+	return mem.conn.Set(item)
+}
+
+//Delete delete value in memcache.
+func (mem *Memcache) Delete(key string) error {
+	return mem.conn.Delete(key)
+}

+ 28 - 0
cache/memcache_test.go

@@ -0,0 +1,28 @@
+package cache
+
+import (
+	"testing"
+	"time"
+)
+
+func TestMemcache(t *testing.T) {
+	mem := NewMemcache("127.0.0.1:11211")
+	var err error
+	timeoutDuration := 10 * time.Second
+	if err = mem.Set("username", "silenceper", timeoutDuration); err != nil {
+		t.Error("set Error", err)
+	}
+
+	if !mem.IsExist("username") {
+		t.Error("IsExist Error")
+	}
+
+	name := mem.Get("username").(string)
+	if name != "silenceper" {
+		t.Error("get Error")
+	}
+
+	if err = mem.Delete("username"); err != nil {
+		t.Errorf("delete Error , err=%v", err)
+	}
+}

+ 104 - 0
cache/redis.go

@@ -0,0 +1,104 @@
+package cache
+
+import (
+	"encoding/json"
+	"time"
+
+	"github.com/garyburd/redigo/redis"
+)
+
+//Redis redis cache
+type Redis struct {
+	conn *redis.Pool
+}
+
+//RedisOpts redis 连接属性
+type RedisOpts struct {
+	Host        string `yml:"host" json:"host"`
+	Password    string `yml:"password" json:"password"`
+	Database    int    `yml:"database" json:"database"`
+	MaxIdle     int    `yml:"max_idle" json:"max_idle"`
+	MaxActive   int    `yml:"max_active" json:"max_active"`
+	IdleTimeout int32  `yml:"idle_timeout" json:"idle_timeout"` //second
+}
+
+//NewRedis 实例化
+func NewRedis(opts *RedisOpts) *Redis {
+	pool := &redis.Pool{
+		MaxActive:   opts.MaxActive,
+		MaxIdle:     opts.MaxIdle,
+		IdleTimeout: time.Second * time.Duration(opts.IdleTimeout),
+		Dial: func() (redis.Conn, error) {
+			return redis.Dial("tcp", opts.Host,
+				redis.DialDatabase(opts.Database),
+				redis.DialPassword(opts.Password),
+			)
+		},
+		TestOnBorrow: func(conn redis.Conn, t time.Time) error {
+			if time.Since(t) < time.Minute {
+				return nil
+			}
+			_, err := conn.Do("PING")
+			return err
+		},
+	}
+	return &Redis{pool}
+}
+
+//Get 获取一个值
+func (r *Redis) Get(key string) interface{} {
+	conn := r.conn.Get()
+	defer conn.Close()
+
+	var data []byte
+	var err error
+	if data, err = redis.Bytes(conn.Do("GET", key)); err != nil {
+		return nil
+	}
+	var reply interface{}
+	if err = json.Unmarshal(data, &reply); err != nil {
+		return nil
+	}
+
+	return reply
+}
+
+//Set 设置一个值
+func (r *Redis) Set(key string, val interface{}, timeout time.Duration) (err error) {
+	conn := r.conn.Get()
+	defer conn.Close()
+
+	var data []byte
+	if data, err = json.Marshal(val); err != nil {
+		return
+	}
+
+	_, err = conn.Do("SETEX", key, int64(timeout/time.Second), data)
+
+	return
+}
+
+//IsExist 判断key是否存在
+func (r *Redis) IsExist(key string) bool {
+	conn := r.conn.Get()
+	defer conn.Close()
+
+	a, _ := conn.Do("EXISTS", key)
+	i := a.(int64)
+	if i > 0 {
+		return true
+	}
+	return false
+}
+
+//Delete 删除
+func (r *Redis) Delete(key string) error {
+	conn := r.conn.Get()
+	defer conn.Close()
+
+	if _, err := conn.Do("DEL", key); err != nil {
+		return err
+	}
+
+	return nil
+}

+ 32 - 0
cache/redis_test.go

@@ -0,0 +1,32 @@
+package cache
+
+import (
+	"testing"
+	"time"
+)
+
+func TestRedis(t *testing.T) {
+	opts := &RedisOpts{
+		Host: "127.0.0.1:6379",
+	}
+	redis := NewRedis(opts)
+	var err error
+	timeoutDuration := 1 * time.Second
+
+	if err = redis.Set("username", "silenceper", timeoutDuration); err != nil {
+		t.Error("set Error", err)
+	}
+
+	if !redis.IsExist("username") {
+		t.Error("IsExist Error")
+	}
+
+	name := redis.Get("username").(string)
+	if name != "silenceper" {
+		t.Error("get Error")
+	}
+
+	if err = redis.Delete("username"); err != nil {
+		t.Errorf("delete Error , err=%v", err)
+	}
+}

+ 75 - 0
context/access_token.go

@@ -0,0 +1,75 @@
+package context
+
+import (
+	"encoding/json"
+	"fmt"
+	"sync"
+	"time"
+
+	"github.com/silenceper/wechat/util"
+)
+
+const (
+	//AccessTokenURL 获取access_token的接口
+	AccessTokenURL = "https://api.weixin.qq.com/cgi-bin/token"
+)
+
+//ResAccessToken struct
+type ResAccessToken struct {
+	util.CommonError
+
+	AccessToken string `json:"access_token"`
+	ExpiresIn   int64  `json:"expires_in"`
+}
+
+//SetAccessTokenLock 设置读写锁(一个appID一个读写锁)
+func (ctx *Context) SetAccessTokenLock(l *sync.RWMutex) {
+	ctx.accessTokenLock = l
+}
+
+//GetAccessToken 获取access_token
+func (ctx *Context) GetAccessToken() (accessToken string, err error) {
+	ctx.accessTokenLock.Lock()
+	defer ctx.accessTokenLock.Unlock()
+
+	accessTokenCacheKey := fmt.Sprintf("access_token_%s", ctx.AppID)
+	val := ctx.Cache.Get(accessTokenCacheKey)
+	if val != nil {
+		accessToken = val.(string)
+		return
+	}
+
+	//从微信服务器获取
+	var resAccessToken ResAccessToken
+	resAccessToken, err = ctx.GetAccessTokenFromServer()
+
+	if err != nil {
+		return
+	}
+
+	accessToken = resAccessToken.AccessToken
+	return
+}
+
+//GetAccessTokenFromServer 强制从微信服务器获取token
+func (ctx *Context) GetAccessTokenFromServer() (resAccessToken ResAccessToken, err error) {
+	url := fmt.Sprintf("%s?grant_type=client_credential&appid=%s&secret=%s", AccessTokenURL, ctx.AppID, ctx.AppSecret)
+	var body []byte
+	body, err = util.HTTPGet(url)
+	if err != nil {
+		return
+	}
+	err = json.Unmarshal(body, &resAccessToken)
+	if err != nil {
+		return
+	}
+	if resAccessToken.ErrMsg != "" {
+		err = fmt.Errorf("get access_token error : errcode=%v , errormsg=%v", resAccessToken.ErrCode, resAccessToken.ErrMsg)
+		return
+	}
+
+	accessTokenCacheKey := fmt.Sprintf("access_token_%s", ctx.AppID)
+	expires := resAccessToken.ExpiresIn - 1500
+	err = ctx.Cache.Set(accessTokenCacheKey, resAccessToken.AccessToken, time.Duration(expires)*time.Second)
+	return
+}

+ 55 - 0
context/context.go

@@ -0,0 +1,55 @@
+package context
+
+import (
+	"net/http"
+	"sync"
+
+	"github.com/silenceper/wechat/cache"
+)
+
+// Context struct
+type Context struct {
+	AppID          string
+	AppSecret      string
+	Token          string
+	EncodingAESKey string
+	PayMchID       string
+	PayNotifyURL   string
+	PayKey         string
+
+	Cache cache.Cache
+
+	Writer  http.ResponseWriter
+	Request *http.Request
+
+	//accessTokenLock 读写锁 同一个AppID一个
+	accessTokenLock *sync.RWMutex
+
+	//jsAPITicket 读写锁 同一个AppID一个
+	jsAPITicketLock *sync.RWMutex
+}
+
+// Query returns the keyed url query value if it exists
+func (ctx *Context) Query(key string) string {
+	value, _ := ctx.GetQuery(key)
+	return value
+}
+
+// GetQuery is like Query(), it returns the keyed url query value
+func (ctx *Context) GetQuery(key string) (string, bool) {
+	req := ctx.Request
+	if values, ok := req.URL.Query()[key]; ok && len(values) > 0 {
+		return values[0], true
+	}
+	return "", false
+}
+
+// SetJsAPITicketLock 设置jsAPITicket的lock
+func (ctx *Context) SetJsAPITicketLock(lock *sync.RWMutex) {
+	ctx.jsAPITicketLock = lock
+}
+
+// GetJsAPITicketLock 获取jsAPITicket 的lock
+func (ctx *Context) GetJsAPITicketLock() *sync.RWMutex {
+	return ctx.jsAPITicketLock
+}

+ 43 - 0
context/render.go

@@ -0,0 +1,43 @@
+package context
+
+import (
+	"encoding/xml"
+	"net/http"
+)
+
+var xmlContentType = []string{"application/xml; charset=utf-8"}
+var plainContentType = []string{"text/plain; charset=utf-8"}
+
+//Render render from bytes
+func (ctx *Context) Render(bytes []byte) {
+	//debug
+	//fmt.Println("response msg = ", string(bytes))
+	ctx.Writer.WriteHeader(200)
+	_, err := ctx.Writer.Write(bytes)
+	if err != nil {
+		panic(err)
+	}
+}
+
+//String render from string
+func (ctx *Context) String(str string) {
+	writeContextType(ctx.Writer, plainContentType)
+	ctx.Render([]byte(str))
+}
+
+//XML render to xml
+func (ctx *Context) XML(obj interface{}) {
+	writeContextType(ctx.Writer, xmlContentType)
+	bytes, err := xml.Marshal(obj)
+	if err != nil {
+		panic(err)
+	}
+	ctx.Render(bytes)
+}
+
+func writeContextType(w http.ResponseWriter, value []string) {
+	header := w.Header()
+	if val := header["Content-Type"]; len(val) == 0 {
+		header["Content-Type"] = value
+	}
+}

+ 33 - 0
doc.go

@@ -0,0 +1,33 @@
+/*
+Package wechat provide wechat sdk for go
+
+使用Golang开发的微信SDK,简单、易用。
+
+以下是一个处理消息接收以及回复的例子:
+
+	//配置微信参数
+	config := &wechat.Config{
+		AppID:          "xxxx",
+		AppSecret:      "xxxx",
+		Token:          "xxxx",
+		EncodingAESKey: "xxxx",
+	}
+	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.MsgText, text}
+	})
+
+	server.Serve()
+	server.Send()
+
+
+更多信息:https://github.com/silenceper/wechat
+
+*/
+package wechat

+ 45 - 0
examples/beego/beego.go

@@ -0,0 +1,45 @@
+package main
+
+import (
+	"fmt"
+
+	"github.com/astaxie/beego"
+	"github.com/astaxie/beego/context"
+	"github.com/silenceper/wechat"
+	"github.com/silenceper/wechat/message"
+)
+
+func hello(ctx *context.Context) {
+	//配置微信参数
+	config := &wechat.Config{
+		AppID:          "wxbb8d22a4653455e7",
+		AppSecret:      "044ac985f5066c0a23716f403bc7b5cc",
+		Token:          "youjia",
+		EncodingAESKey: "nHlUl7WWD0driO5HMez3R63T0mrj2uRSQ64pi3tqHLo",
+	}
+	fmt.Println("-----==++-----333")
+	wc := wechat.NewWechat(config)
+	// 传入request和responseWriter
+	server := wc.GetServer(ctx.Request, ctx.ResponseWriter)
+	//设置接收消息的处理方法
+	server.SetMessageHandler(func(msg message.MixMessage) *message.Reply {
+		//回复消息:演示回复用户发送的消息
+		text := message.NewText(msg.Content)
+		return &message.Reply{MsgType: message.MsgTypeText, MsgData: text}
+	})
+
+	//处理消息接收以及回复
+	err := server.Serve()
+	if err != nil {
+		fmt.Println(err)
+		return
+	}
+
+	//发送回复的消息
+	server.Send()
+}
+
+func main() {
+	beego.Any("/", hello)
+	beego.Run(":7050")
+}

+ 47 - 0
examples/gin/gin.go

@@ -0,0 +1,47 @@
+package main
+
+import (
+	"fmt"
+
+	"github.com/gin-gonic/gin"
+	"github.com/silenceper/wechat"
+	"github.com/silenceper/wechat/message"
+)
+
+func main() {
+	router := gin.Default()
+
+	router.Any("/", hello)
+	router.Run(":8001")
+}
+
+func hello(c *gin.Context) {
+
+	//配置微信参数
+	config := &wechat.Config{
+		AppID:          "your app id",
+		AppSecret:      "your app secret",
+		Token:          "your token",
+		EncodingAESKey: "your encoding aes key",
+	}
+	wc := wechat.NewWechat(config)
+
+	// 传入request和responseWriter
+	server := wc.GetServer(c.Request, c.Writer)
+	//设置接收消息的处理方法
+	server.SetMessageHandler(func(msg message.MixMessage) *message.Reply {
+
+		//回复消息:演示回复用户发送的消息
+		text := message.NewText(msg.Content)
+		return &message.Reply{MsgType: message.MsgTypeText, MsgData: text}
+	})
+
+	//处理消息接收以及回复
+	err := server.Serve()
+	if err != nil {
+		fmt.Println(err)
+		return
+	}
+	//发送回复的消息
+	server.Send()
+}

+ 48 - 0
examples/http/http.go

@@ -0,0 +1,48 @@
+package main
+
+import (
+	"fmt"
+	"net/http"
+
+	"github.com/silenceper/wechat"
+	"github.com/silenceper/wechat/message"
+)
+
+func hello(rw http.ResponseWriter, req *http.Request) {
+
+	//配置微信参数
+	config := &wechat.Config{
+		AppID:          "your app id",
+		AppSecret:      "your app secret",
+		Token:          "your token",
+		EncodingAESKey: "your encoding aes key",
+	}
+	wc := wechat.NewWechat(config)
+
+	// 传入request和responseWriter
+	server := wc.GetServer(req, rw)
+	//设置接收消息的处理方法
+	server.SetMessageHandler(func(msg message.MixMessage) *message.Reply {
+
+		//回复消息:演示回复用户发送的消息
+		text := message.NewText(msg.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("/", hello)
+	err := http.ListenAndServe(":8001", nil)
+	if err != nil {
+		fmt.Printf("start server error , err=%v", err)
+	}
+}

+ 110 - 0
js/js.go

@@ -0,0 +1,110 @@
+package js
+
+import (
+	"encoding/json"
+	"fmt"
+	"time"
+
+	"github.com/silenceper/wechat/context"
+	"github.com/silenceper/wechat/util"
+)
+
+const getTicketURL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi"
+
+// Js struct
+type Js struct {
+	*context.Context
+}
+
+// Config 返回给用户jssdk配置信息
+type Config struct {
+	AppID     string `json:"app_id"`
+	Timestamp int64  `json:"timestamp"`
+	NonceStr  string `json:"nonce_str"`
+	Signature string `json:"signature"`
+}
+
+// resTicket 请求jsapi_tikcet返回结果
+type resTicket struct {
+	util.CommonError
+
+	Ticket    string `json:"ticket"`
+	ExpiresIn int64  `json:"expires_in"`
+}
+
+//NewJs init
+func NewJs(context *context.Context) *Js {
+	js := new(Js)
+	js.Context = context
+	return js
+}
+
+//GetConfig 获取jssdk需要的配置参数
+//uri 为当前网页地址
+func (js *Js) GetConfig(uri string) (config *Config, err error) {
+	config = new(Config)
+	var ticketStr string
+	ticketStr, err = js.GetTicket()
+	if err != nil {
+		fmt.Print(err)
+		return
+	}
+
+	nonceStr := util.RandomStr(16)
+	timestamp := util.GetCurrTs()
+	str := fmt.Sprintf("jsapi_ticket=%s&noncestr=%s&timestamp=%d&url=%s", ticketStr, nonceStr, timestamp, uri)
+	sigStr := util.Signature(str)
+	fmt.Println("----------js.AppID:", js.AppID)
+	config.AppID = js.AppID
+	config.NonceStr = nonceStr
+	config.Timestamp = timestamp
+	config.Signature = sigStr
+	return
+}
+
+//GetTicket 获取jsapi_ticket
+func (js *Js) GetTicket() (ticketStr string, err error) {
+	js.GetJsAPITicketLock().Lock()
+	defer js.GetJsAPITicketLock().Unlock()
+
+	//先从cache中取
+	jsAPITicketCacheKey := fmt.Sprintf("jsapi_ticket_%s", js.AppID)
+	val := js.Cache.Get(jsAPITicketCacheKey)
+	if val != nil {
+		ticketStr = val.(string)
+		return
+	}
+	var ticket resTicket
+	ticket, err = js.getTicketFromServer()
+	if err != nil {
+		return
+	}
+	ticketStr = ticket.Ticket
+	return
+}
+
+//getTicketFromServer 强制从服务器中获取ticket
+func (js *Js) getTicketFromServer() (ticket resTicket, err error) {
+	var accessToken string
+	accessToken, err = js.GetAccessToken()
+	if err != nil {
+		return
+	}
+
+	var response []byte
+	url := fmt.Sprintf(getTicketURL, accessToken)
+	response, err = util.HTTPGet(url)
+	err = json.Unmarshal(response, &ticket)
+	if err != nil {
+		return
+	}
+	if ticket.ErrCode != 0 {
+		err = fmt.Errorf("getTicket Error : errcode=%d , errmsg=%s", ticket.ErrCode, ticket.ErrMsg)
+		return
+	}
+
+	jsAPITicketCacheKey := fmt.Sprintf("jsapi_ticket_%s", js.AppID)
+	expires := ticket.ExpiresIn - 1500
+	err = js.Cache.Set(jsAPITicketCacheKey, ticket.Ticket, time.Duration(expires)*time.Second)
+	return
+}

+ 196 - 0
material/material.go

@@ -0,0 +1,196 @@
+package material
+
+import (
+	"encoding/json"
+	"errors"
+	"fmt"
+
+	"github.com/silenceper/wechat/context"
+	"github.com/silenceper/wechat/util"
+)
+
+const (
+	addNewsURL     = "https://api.weixin.qq.com/cgi-bin/material/add_news"
+	addMaterialURL = "https://api.weixin.qq.com/cgi-bin/material/add_material"
+	delMaterialURL = "https://api.weixin.qq.com/cgi-bin/material/del_material"
+)
+
+//Material 素材管理
+type Material struct {
+	*context.Context
+}
+
+//NewMaterial init
+func NewMaterial(context *context.Context) *Material {
+	material := new(Material)
+	material.Context = context
+	return material
+}
+
+//Article 永久图文素材
+type Article struct {
+	Title            string `json:"title"`
+	ThumbMediaID     string `json:"thumb_media_id"`
+	Author           string `json:"author"`
+	Digest           string `json:"digest"`
+	ShowCoverPic     int    `json:"show_cover_pic"`
+	Content          string `json:"content"`
+	ContentSourceURL string `json:"content_source_url"`
+}
+
+//reqArticles 永久性图文素材请求信息
+type reqArticles struct {
+	Articles []*Article `json:"articles"`
+}
+
+//resArticles 永久性图文素材返回结果
+type resArticles struct {
+	util.CommonError
+
+	MediaID string `json:"media_id"`
+}
+
+//AddNews 新增永久图文素材
+func (material *Material) AddNews(articles []*Article) (mediaID string, err error) {
+	req := &reqArticles{articles}
+
+	var accessToken string
+	accessToken, err = material.GetAccessToken()
+	if err != nil {
+		return
+	}
+
+	uri := fmt.Sprintf("%s?access_token=%s", addNewsURL, accessToken)
+	responseBytes, err := util.PostJSON(uri, req)
+	var res resArticles
+	err = json.Unmarshal(responseBytes, res)
+	if err != nil {
+		return
+	}
+	mediaID = res.MediaID
+	return
+}
+
+//resAddMaterial 永久性素材上传返回的结果
+type resAddMaterial struct {
+	util.CommonError
+
+	MediaID string `json:"media_id"`
+	URL     string `json:"url"`
+}
+
+//AddMaterial 上传永久性素材(处理视频需要单独上传)
+func (material *Material) AddMaterial(mediaType MediaType, filename string) (mediaID string, url string, err error) {
+	if mediaType == MediaTypeVideo {
+		err = errors.New("永久视频素材上传使用 AddVideo 方法")
+	}
+	var accessToken string
+	accessToken, err = material.GetAccessToken()
+	if err != nil {
+		return
+	}
+
+	uri := fmt.Sprintf("%s?access_token=%s&type=%s", addMaterialURL, accessToken, mediaType)
+	var response []byte
+	response, err = util.PostFile("media", filename, uri)
+	if err != nil {
+		return
+	}
+	var resMaterial resAddMaterial
+	err = json.Unmarshal(response, &resMaterial)
+	if err != nil {
+		return
+	}
+	if resMaterial.ErrCode != 0 {
+		err = fmt.Errorf("AddMaterial error : errcode=%v , errmsg=%v", resMaterial.ErrCode, resMaterial.ErrMsg)
+		return
+	}
+	mediaID = resMaterial.MediaID
+	url = resMaterial.URL
+	return
+}
+
+type reqVideo struct {
+	Title        string `json:"title"`
+	Introduction string `json:"introduction"`
+}
+
+//AddVideo 永久视频素材文件上传
+func (material *Material) AddVideo(filename, title, introduction string) (mediaID string, url string, err error) {
+	var accessToken string
+	accessToken, err = material.GetAccessToken()
+	if err != nil {
+		return
+	}
+
+	uri := fmt.Sprintf("%s?access_token=%s&type=video", addMaterialURL, accessToken)
+
+	videoDesc := &reqVideo{
+		Title:        title,
+		Introduction: introduction,
+	}
+	var fieldValue []byte
+	fieldValue, err = json.Marshal(videoDesc)
+	if err != nil {
+		return
+	}
+
+	fields := []util.MultipartFormField{
+		{
+			IsFile:    true,
+			Fieldname: "video",
+			Filename:  filename,
+		},
+		{
+			IsFile:    true,
+			Fieldname: "description",
+			Value:     fieldValue,
+		},
+	}
+
+	var response []byte
+	response, err = util.PostMultipartForm(fields, uri)
+	if err != nil {
+		return
+	}
+
+	var resMaterial resAddMaterial
+	err = json.Unmarshal(response, &resMaterial)
+	if err != nil {
+		return
+	}
+	if resMaterial.ErrCode != 0 {
+		err = fmt.Errorf("AddMaterial error : errcode=%v , errmsg=%v", resMaterial.ErrCode, resMaterial.ErrMsg)
+		return
+	}
+	mediaID = resMaterial.MediaID
+	url = resMaterial.URL
+	return
+}
+
+type reqDeleteMaterial struct {
+	MediaID string `json:"media_id"`
+}
+
+//DeleteMaterial 删除永久素材
+func (material *Material) DeleteMaterial(mediaID string) error {
+	accessToken, err := material.GetAccessToken()
+	if err != nil {
+		return err
+	}
+
+	uri := fmt.Sprintf("%s?access_token=%s", delMaterialURL, accessToken)
+	response, err := util.PostJSON(uri, reqDeleteMaterial{mediaID})
+	if err != nil {
+		return err
+	}
+	var resDeleteMaterial util.CommonError
+	err = json.Unmarshal(response, &resDeleteMaterial)
+	if err != nil {
+		return err
+	}
+	if resDeleteMaterial.ErrCode != 0 {
+		return fmt.Errorf("DeleteMaterial error : errcode=%v , errmsg=%v", resDeleteMaterial.ErrCode, resDeleteMaterial.ErrMsg)
+	}
+	return nil
+}

+ 110 - 0
material/media.go

@@ -0,0 +1,110 @@
+package material
+
+import (
+	"encoding/json"
+	"fmt"
+
+	"github.com/silenceper/wechat/util"
+)
+
+//MediaType 媒体文件类型
+type MediaType string
+
+const (
+	//MediaTypeImage 媒体文件:图片
+	MediaTypeImage MediaType = "image"
+	//MediaTypeVoice 媒体文件:声音
+	MediaTypeVoice = "voice"
+	//MediaTypeVideo 媒体文件:视频
+	MediaTypeVideo = "video"
+	//MediaTypeThumb 媒体文件:缩略图
+	MediaTypeThumb = "thumb"
+)
+
+const (
+	mediaUploadURL      = "https://api.weixin.qq.com/cgi-bin/media/upload"
+	mediaUploadImageURL = "https://api.weixin.qq.com/cgi-bin/media/uploadimg"
+	mediaGetURL         = "https://api.weixin.qq.com/cgi-bin/media/get"
+)
+
+//Media 临时素材上传返回信息
+type Media struct {
+	util.CommonError
+
+	Type      MediaType `json:"type"`
+	MediaID   string    `json:"media_id"`
+	ThumbMediaID string `json:"thumb_media_id"`
+	CreatedAt int64     `json:"created_at"`
+}
+
+//MediaUpload 临时素材上传
+func (material *Material) MediaUpload(mediaType MediaType, filename string) (media Media, err error) {
+	var accessToken string
+	accessToken, err = material.GetAccessToken()
+	if err != nil {
+		return
+	}
+
+	uri := fmt.Sprintf("%s?access_token=%s&type=%s", mediaUploadURL, accessToken, mediaType)
+	var response []byte
+	response, err = util.PostFile("media", filename, uri)
+	if err != nil {
+		return
+	}
+	err = json.Unmarshal(response, &media)
+	if err != nil {
+		return
+	}
+	if media.ErrCode != 0 {
+		err = fmt.Errorf("MediaUpload error : errcode=%v , errmsg=%v", media.ErrCode, media.ErrMsg)
+		return
+	}
+	return
+}
+
+//GetMediaURL 返回临时素材的下载地址供用户自己处理
+//NOTICE: URL 不可公开,因为含access_token 需要立即另存文件
+func (material *Material) GetMediaURL(mediaID string) (mediaURL string, err error) {
+	var accessToken string
+	accessToken, err = material.GetAccessToken()
+	if err != nil {
+		return
+	}
+	mediaURL = fmt.Sprintf("%s?access_token=%s&media_id=%s", mediaGetURL, accessToken, mediaID)
+	return
+}
+
+//resMediaImage 图片上传返回结果
+type resMediaImage struct {
+	util.CommonError
+
+	URL string `json:"url"`
+}
+
+//ImageUpload 图片上传
+func (material *Material) ImageUpload(filename string) (url string, err error) {
+	var accessToken string
+	accessToken, err = material.GetAccessToken()
+	if err != nil {
+		return
+	}
+
+	uri := fmt.Sprintf("%s?access_token=%s", mediaUploadImageURL, accessToken)
+	var response []byte
+	response, err = util.PostFile("media", filename, uri)
+	if err != nil {
+		return
+	}
+	var image resMediaImage
+	err = json.Unmarshal(response, &image)
+	if err != nil {
+		return
+	}
+	if image.ErrCode != 0 {
+		err = fmt.Errorf("UploadImage error : errcode=%v , errmsg=%v", image.ErrCode, image.ErrMsg)
+		return
+	}
+	url = image.URL
+	return
+
+}

+ 128 - 0
menu/button.go

@@ -0,0 +1,128 @@
+package menu
+
+//Button 菜单按钮
+type Button struct {
+	Type       string    `json:"type,omitempty"`
+	Name       string    `json:"name,omitempty"`
+	Key        string    `json:"key,omitempty"`
+	URL        string    `json:"url,omitempty"`
+	MediaID    string    `json:"media_id,omitempty"`
+	SubButtons []*Button `json:"sub_button,omitempty"`
+}
+
+//SetSubButton 设置二级菜单
+func (btn *Button) SetSubButton(name string, subButtons []*Button) {
+	btn.Name = name
+	btn.SubButtons = subButtons
+	btn.Type = ""
+	btn.Key = ""
+	btn.URL = ""
+	btn.MediaID = ""
+}
+
+//SetClickButton btn 为click类型
+func (btn *Button) SetClickButton(name, key string) {
+	btn.Type = "click"
+	btn.Name = name
+	btn.Key = key
+	btn.URL = ""
+	btn.MediaID = ""
+	btn.SubButtons = nil
+}
+
+//SetViewButton view类型
+func (btn *Button) SetViewButton(name, url string) {
+	btn.Type = "view"
+	btn.Name = name
+	btn.URL = url
+	btn.Key = ""
+	btn.MediaID = ""
+	btn.SubButtons = nil
+}
+
+// SetScanCodePushButton 扫码推事件
+func (btn *Button) SetScanCodePushButton(name, key string) {
+	btn.Type = "scancode_push"
+	btn.Name = name
+	btn.Key = key
+	btn.URL = ""
+	btn.MediaID = ""
+	btn.SubButtons = nil
+}
+
+//SetScanCodeWaitMsgButton 设置 扫码推事件且弹出"消息接收中"提示框
+func (btn *Button) SetScanCodeWaitMsgButton(name, key string) {
+	btn.Type = "scancode_waitmsg"
+	btn.Name = name
+	btn.Key = key
+
+	btn.URL = ""
+	btn.MediaID = ""
+	btn.SubButtons = nil
+}
+
+//SetPicSysPhotoButton 设置弹出系统拍照发图按钮
+func (btn *Button) SetPicSysPhotoButton(name, key string) {
+	btn.Type = "pic_sysphoto"
+	btn.Name = name
+	btn.Key = key
+
+	btn.URL = ""
+	btn.MediaID = ""
+	btn.SubButtons = nil
+}
+
+//SetPicPhotoOrAlbumButton 设置弹出拍照或者相册发图类型按钮
+func (btn *Button) SetPicPhotoOrAlbumButton(name, key string) {
+	btn.Type = "pic_photo_or_album"
+	btn.Name = name
+	btn.Key = key
+
+	btn.URL = ""
+	btn.MediaID = ""
+	btn.SubButtons = nil
+}
+
+// SetPicWeixinButton 设置弹出微信相册发图器类型按钮
+func (btn *Button) SetPicWeixinButton(name, key string) {
+	btn.Type = "pic_weixin"
+	btn.Name = name
+	btn.Key = key
+
+	btn.URL = ""
+	btn.MediaID = ""
+	btn.SubButtons = nil
+}
+
+// SetLocationSelectButton 设置 弹出地理位置选择器 类型按钮
+func (btn *Button) SetLocationSelectButton(name, key string) {
+	btn.Type = "location_select"
+	btn.Name = name
+	btn.Key = key
+
+	btn.URL = ""
+	btn.MediaID = ""
+	btn.SubButtons = nil
+}
+
+//SetMediaIDButton  设置 下发消息(除文本消息) 类型按钮
+func (btn *Button) SetMediaIDButton(name, mediaID string) {
+	btn.Type = "media_id"
+	btn.Name = name
+	btn.MediaID = mediaID
+
+	btn.Key = ""
+	btn.URL = ""
+	btn.SubButtons = nil
+}
+
+//SetViewLimitedButton  设置 跳转图文消息URL 类型按钮
+func (btn *Button) SetViewLimitedButton(name, mediaID string) {
+	btn.Type = "view_limited"
+	btn.Name = name
+	btn.MediaID = mediaID
+
+	btn.Key = ""
+	btn.URL = ""
+	btn.SubButtons = nil
+}

+ 299 - 0
menu/menu.go

@@ -0,0 +1,299 @@
+package menu
+
+import (
+	"encoding/json"
+	"fmt"
+
+	"github.com/silenceper/wechat/context"
+	"github.com/silenceper/wechat/util"
+)
+
+const (
+	menuCreateURL            = "https://api.weixin.qq.com/cgi-bin/menu/create"
+	menuGetURL               = "https://api.weixin.qq.com/cgi-bin/menu/get"
+	menuDeleteURL            = "https://api.weixin.qq.com/cgi-bin/menu/delete"
+	menuAddConditionalURL    = "https://api.weixin.qq.com/cgi-bin/menu/addconditional"
+	menuDeleteConditionalURL = "https://api.weixin.qq.com/cgi-bin/menu/delconditional"
+	menuTryMatchURL          = "https://api.weixin.qq.com/cgi-bin/menu/trymatch"
+	menuSelfMenuInfoURL      = "https://api.weixin.qq.com/cgi-bin/get_current_selfmenu_info"
+)
+
+//Menu struct
+type Menu struct {
+	*context.Context
+}
+
+//reqMenu 设置菜单请求数据
+type reqMenu struct {
+	Button    []*Button  `json:"button,omitempty"`
+	MatchRule *MatchRule `json:"matchrule,omitempty"`
+}
+
+//reqDeleteConditional 删除个性化菜单请求数据
+type reqDeleteConditional struct {
+	MenuID int64 `json:"menuid"`
+}
+
+//reqMenuTryMatch 菜单匹配请求
+type reqMenuTryMatch struct {
+	UserID string `json:"user_id"`
+}
+
+//resConditionalMenu 个性化菜单返回结果
+type resConditionalMenu struct {
+	Button    []Button  `json:"button"`
+	MatchRule MatchRule `json:"matchrule"`
+	MenuID    int64     `json:"menuid"`
+}
+
+//resMenuTryMatch 菜单匹配请求结果
+type resMenuTryMatch struct {
+	util.CommonError
+
+	Button []Button `json:"button"`
+}
+
+//ResMenu 查询菜单的返回数据
+type ResMenu struct {
+	util.CommonError
+
+	Menu struct {
+		Button []Button `json:"button"`
+		MenuID int64    `json:"menuid"`
+	} `json:"menu"`
+	Conditionalmenu []resConditionalMenu `json:"conditionalmenu"`
+}
+
+//ResSelfMenuInfo 自定义菜单配置返回结果
+type ResSelfMenuInfo struct {
+	util.CommonError
+
+	IsMenuOpen   int32 `json:"is_menu_open"`
+	SelfMenuInfo struct {
+		Button []SelfMenuButton `json:"button"`
+	} `json:"selfmenu_info"`
+}
+
+//SelfMenuButton 自定义菜单配置详情
+type SelfMenuButton struct {
+	Type      string `json:"type"`
+	Name      string `json:"name"`
+	Key       string `json:"key"`
+	URL       string `json:"url,omitempty"`
+	Value     string `json:"value,omitempty"`
+	SubButton struct {
+		List []SelfMenuButton `json:"list"`
+	} `json:"sub_button,omitempty"`
+	NewsInfo struct {
+		List []ButtonNew `json:"list"`
+	} `json:"news_info,omitempty"`
+}
+
+//ButtonNew 图文消息菜单
+type ButtonNew struct {
+	Title      string `json:"title"`
+	Author     string `json:"author"`
+	Digest     string `json:"digest"`
+	ShowCover  int32  `json:"show_cover"`
+	CoverURL   string `json:"cover_url"`
+	ContentURL string `json:"content_url"`
+	SourceURL  string `json:"source_url"`
+}
+
+//MatchRule 个性化菜单规则
+type MatchRule struct {
+	GroupID            int32  `json:"group_id,omitempty"`
+	Sex                int32  `json:"sex,omitempty"`
+	Country            string `json:"country,omitempty"`
+	Province           string `json:"province,omitempty"`
+	City               string `json:"city,omitempty"`
+	ClientPlatformType int32  `json:"client_platform_type,omitempty"`
+	Language           string `json:"language,omitempty"`
+}
+
+//NewMenu 实例
+func NewMenu(context *context.Context) *Menu {
+	menu := new(Menu)
+	menu.Context = context
+	return menu
+}
+
+//SetMenu 设置按钮
+func (menu *Menu) SetMenu(buttons []*Button) error {
+	accessToken, err := menu.GetAccessToken()
+	if err != nil {
+		return err
+	}
+
+	uri := fmt.Sprintf("%s?access_token=%s", menuCreateURL, accessToken)
+	reqMenu := &reqMenu{
+		Button: buttons,
+	}
+
+	response, err := util.PostJSON(uri, reqMenu)
+	if err != nil {
+		return err
+	}
+	var commError util.CommonError
+	err = json.Unmarshal(response, &commError)
+	if err != nil {
+		return err
+	}
+	if commError.ErrCode != 0 {
+		return fmt.Errorf("SetMenu Error , errcode=%d , errmsg=%s", commError.ErrCode, commError.ErrMsg)
+	}
+	return nil
+}
+
+//GetMenu 获取菜单配置
+func (menu *Menu) GetMenu() (resMenu ResMenu, err error) {
+	var accessToken string
+	accessToken, err = menu.GetAccessToken()
+	if err != nil {
+		return
+	}
+	uri := fmt.Sprintf("%s?access_token=%s", menuGetURL, accessToken)
+	var response []byte
+	response, err = util.HTTPGet(uri)
+	if err != nil {
+		return
+	}
+	err = json.Unmarshal(response, &resMenu)
+	if err != nil {
+		return
+	}
+	if resMenu.ErrCode != 0 {
+		err = fmt.Errorf("GetMenu Error , errcode=%d , errmsg=%s", resMenu.ErrCode, resMenu.ErrMsg)
+		return
+	}
+	return
+}
+
+//DeleteMenu 删除菜单
+func (menu *Menu) DeleteMenu() error {
+	accessToken, err := menu.GetAccessToken()
+	if err != nil {
+		return err
+	}
+	uri := fmt.Sprintf("%s?access_token=%s", menuDeleteURL, accessToken)
+	response, err := util.HTTPGet(uri)
+	if err != nil {
+		return err
+	}
+	var commError util.CommonError
+	err = json.Unmarshal(response, &commError)
+	if err != nil {
+		return err
+	}
+	if commError.ErrCode != 0 {
+		return fmt.Errorf("GetMenu Error , errcode=%d , errmsg=%s", commError.ErrCode, commError.ErrMsg)
+	}
+	return nil
+}
+
+//AddConditional 添加个性化菜单
+func (menu *Menu) AddConditional(buttons []*Button, matchRule *MatchRule) error {
+	accessToken, err := menu.GetAccessToken()
+	if err != nil {
+		return err
+	}
+
+	uri := fmt.Sprintf("%s?access_token=%s", menuAddConditionalURL, accessToken)
+	reqMenu := &reqMenu{
+		Button:    buttons,
+		MatchRule: matchRule,
+	}
+
+	response, err := util.PostJSON(uri, reqMenu)
+	if err != nil {
+		return err
+	}
+	var commError util.CommonError
+	err = json.Unmarshal(response, &commError)
+	if err != nil {
+		return err
+	}
+	if commError.ErrCode != 0 {
+		return fmt.Errorf("AddConditional Error , errcode=%d , errmsg=%s", commError.ErrCode, commError.ErrMsg)
+	}
+	return nil
+}
+
+//DeleteConditional 删除个性化菜单
+func (menu *Menu) DeleteConditional(menuID int64) error {
+	accessToken, err := menu.GetAccessToken()
+	if err != nil {
+		return err
+	}
+
+	uri := fmt.Sprintf("%s?access_token=%s", menuDeleteConditionalURL, accessToken)
+	reqDeleteConditional := &reqDeleteConditional{
+		MenuID: menuID,
+	}
+
+	response, err := util.PostJSON(uri, reqDeleteConditional)
+	if err != nil {
+		return err
+	}
+	var commError util.CommonError
+	err = json.Unmarshal(response, &commError)
+	if err != nil {
+		return err
+	}
+	if commError.ErrCode != 0 {
+		return fmt.Errorf("DeleteConditional Error , errcode=%d , errmsg=%s", commError.ErrCode, commError.ErrMsg)
+	}
+	return nil
+}
+
+//MenuTryMatch 菜单匹配
+func (menu *Menu) MenuTryMatch(userID string) (buttons []Button, err error) {
+	var accessToken string
+	accessToken, err = menu.GetAccessToken()
+	if err != nil {
+		return
+	}
+	uri := fmt.Sprintf("%s?access_token=%s", menuTryMatchURL, accessToken)
+	reqMenuTryMatch := &reqMenuTryMatch{userID}
+	var response []byte
+	response, err = util.PostJSON(uri, reqMenuTryMatch)
+	if err != nil {
+		return
+	}
+	var resMenuTryMatch resMenuTryMatch
+	err = json.Unmarshal(response, &resMenuTryMatch)
+	if err != nil {
+		return
+	}
+	if resMenuTryMatch.ErrCode != 0 {
+		err = fmt.Errorf("MenuTryMatch Error , errcode=%d , errmsg=%s", resMenuTryMatch.ErrCode, resMenuTryMatch.ErrMsg)
+		return
+	}
+	buttons = resMenuTryMatch.Button
+	return
+}
+
+//GetCurrentSelfMenuInfo 获取自定义菜单配置接口
+func (menu *Menu) GetCurrentSelfMenuInfo() (resSelfMenuInfo ResSelfMenuInfo, err error) {
+	var accessToken string
+	accessToken, err = menu.GetAccessToken()
+	if err != nil {
+		return
+	}
+	uri := fmt.Sprintf("%s?access_token=%s", menuSelfMenuInfoURL, accessToken)
+	var response []byte
+	response, err = util.HTTPGet(uri)
+	if err != nil {
+		return
+	}
+	fmt.Println(string(response))
+	err = json.Unmarshal(response, &resSelfMenuInfo)
+	if err != nil {
+		return
+	}
+	if resSelfMenuInfo.ErrCode != 0 {
+		err = fmt.Errorf("GetCurrentSelfMenuInfo Error , errcode=%d , errmsg=%s", resSelfMenuInfo.ErrCode, resSelfMenuInfo.ErrMsg)
+		return
+	}
+	return
+}

+ 17 - 0
message/image.go

@@ -0,0 +1,17 @@
+package message
+
+//Image 图片消息
+type Image struct {
+	CommonToken
+
+	Image struct {
+		MediaID string `xml:"MediaId"`
+	} `xml:"Image"`
+}
+
+//NewImage 回复图片消息
+func NewImage(mediaID string) *Image {
+	image := new(Image)
+	image.Image.MediaID = mediaID
+	return image
+}

+ 162 - 0
message/message.go

@@ -0,0 +1,162 @@
+package message
+
+import "encoding/xml"
+
+// MsgType 基本消息类型
+type MsgType string
+
+// EventType 事件类型
+type EventType string
+
+const (
+	//MsgTypeText 表示文本消息
+	MsgTypeText MsgType = "text"
+	//MsgTypeImage 表示图片消息
+	MsgTypeImage = "image"
+	//MsgTypeVoice 表示语音消息
+	MsgTypeVoice = "voice"
+	//MsgTypeVideo 表示视频消息
+	MsgTypeVideo = "video"
+	//MsgTypeShortVideo 表示短视频消息[限接收]
+	MsgTypeShortVideo = "shortvideo"
+	//MsgTypeLocation 表示坐标消息[限接收]
+	MsgTypeLocation = "location"
+	//MsgTypeLink 表示链接消息[限接收]
+	MsgTypeLink = "link"
+	//MsgTypeMusic 表示音乐消息[限回复]
+	MsgTypeMusic = "music"
+	//MsgTypeNews 表示图文消息[限回复]
+	MsgTypeNews = "news"
+	//MsgTypeTransfer 表示消息消息转发到客服
+	MsgTypeTransfer = "transfer_customer_service"
+	//MsgTypeEvent 表示事件推送消息
+	MsgTypeEvent = "event"
+)
+
+const (
+	//EventSubscribe 订阅
+	EventSubscribe EventType = "subscribe"
+	//EventUnsubscribe 取消订阅
+	EventUnsubscribe = "unsubscribe"
+	//EventScan 用户已经关注公众号,则微信会将带场景值扫描事件推送给开发者
+	EventScan = "SCAN"
+	//EventLocation 上报地理位置事件
+	EventLocation = "LOCATION"
+	//EventClick 点击菜单拉取消息时的事件推送
+	EventClick = "CLICK"
+	//EventView 点击菜单跳转链接时的事件推送
+	EventView = "VIEW"
+	//EventScancodePush 扫码推事件的事件推送
+	EventScancodePush = "scancode_push"
+	//EventScancodeWaitmsg 扫码推事件且弹出“消息接收中”提示框的事件推送
+	EventScancodeWaitmsg = "scancode_waitmsg"
+	//EventPicSysphoto 弹出系统拍照发图的事件推送
+	EventPicSysphoto = "pic_sysphoto"
+	//EventPicPhotoOrAlbum 弹出拍照或者相册发图的事件推送
+	EventPicPhotoOrAlbum = "pic_photo_or_album"
+	//EventPicWeixin 弹出微信相册发图器的事件推送
+	EventPicWeixin = "pic_weixin"
+	//EventLocationSelect 弹出地理位置选择器的事件推送
+	EventLocationSelect = "location_select"
+	//EventTemplateSendJobFinish 发送模板消息推送通知
+	EventTemplateSendJobFinish = "TEMPLATESENDJOBFINISH"
+)
+
+//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     EventType `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"`
+	Status    string    `xml:"Status"`
+	SessionFrom string  `xml:"SessionFrom"`
+
+	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"`
+	}
+}
+
+//EventPic 发图事件推送
+type EventPic struct {
+	PicMd5Sum string `xml:"PicMd5Sum"`
+}
+
+//EncryptedXMLMsg 安全模式下的消息体
+type EncryptedXMLMsg struct {
+	XMLName      struct{} `xml:"xml" json:"-"`
+	ToUserName   string   `xml:"ToUserName" json:"ToUserName"`
+	EncryptedMsg string   `xml:"Encrypt"    json:"Encrypt"`
+}
+
+//ResponseEncryptedXMLMsg 需要返回的消息体
+type ResponseEncryptedXMLMsg struct {
+	XMLName      struct{} `xml:"xml" json:"-"`
+	EncryptedMsg string   `xml:"Encrypt"      json:"Encrypt"`
+	MsgSignature string   `xml:"MsgSignature" json:"MsgSignature"`
+	Timestamp    int64    `xml:"TimeStamp"    json:"TimeStamp"`
+	Nonce        string   `xml:"Nonce"        json:"Nonce"`
+}
+
+// CommonToken 消息中通用的结构
+type CommonToken struct {
+	XMLName      xml.Name `xml:"xml"`
+	ToUserName   string   `xml:"ToUserName"`
+	FromUserName string   `xml:"FromUserName"`
+	CreateTime   int64    `xml:"CreateTime"`
+	MsgType      MsgType  `xml:"MsgType"`
+}
+
+//SetToUserName set ToUserName
+func (msg *CommonToken) SetToUserName(toUserName string) {
+	msg.ToUserName = toUserName
+}
+
+//SetFromUserName set FromUserName
+func (msg *CommonToken) SetFromUserName(fromUserName string) {
+	msg.FromUserName = fromUserName
+}
+
+//SetCreateTime set createTime
+func (msg *CommonToken) SetCreateTime(createTime int64) {
+	msg.CreateTime = createTime
+}
+
+//SetMsgType set MsgType
+func (msg *CommonToken) SetMsgType(msgType MsgType) {
+	msg.MsgType = msgType
+}

+ 24 - 0
message/music.go

@@ -0,0 +1,24 @@
+package message
+
+//Music 音乐消息
+type Music struct {
+	CommonToken
+
+	Music struct {
+		Title        string `xml:"Title"        `
+		Description  string `xml:"Description"  `
+		MusicURL     string `xml:"MusicUrl"     `
+		HQMusicURL   string `xml:"HQMusicUrl"   `
+		ThumbMediaID string `xml:"ThumbMediaId"`
+	} `xml:"Music"`
+}
+
+//NewMusic  回复音乐消息
+func NewMusic(title, description, musicURL, hQMusicURL, thumbMediaID string) *Music {
+	music := new(Music)
+	music.Music.Title = title
+	music.Music.Description = description
+	music.Music.MusicURL = musicURL
+	music.Music.ThumbMediaID = thumbMediaID
+	return music
+}

+ 35 - 0
message/news.go

@@ -0,0 +1,35 @@
+package message
+
+//News 图文消息
+type News struct {
+	CommonToken
+
+	ArticleCount int        `xml:"ArticleCount"`
+	Articles     []*Article `xml:"Articles>item,omitempty"`
+}
+
+//NewNews 初始化图文消息
+func NewNews(articles []*Article) *News {
+	news := new(News)
+	news.ArticleCount = len(articles)
+	news.Articles = articles
+	return news
+}
+
+//Article 单篇文章
+type Article struct {
+	Title       string `xml:"Title,omitempty"`
+	Description string `xml:"Description,omitempty"`
+	PicURL      string `xml:"PicUrl,omitempty"`
+	URL         string `xml:"Url,omitempty"`
+}
+
+//NewArticle 初始化文章
+func NewArticle(title, description, picURL, url string) *Article {
+	article := new(Article)
+	article.Title = title
+	article.Description = description
+	article.PicURL = picURL
+	article.URL = url
+	return article
+}

+ 24 - 0
message/ransfer_customer.go

@@ -0,0 +1,24 @@
+package message
+
+//TransferCustomer 转发客服消息
+type TransferCustomer struct {
+	CommonToken
+
+	TransInfo *TransInfo `xml:"TransInfo,omitempty"`
+}
+
+//TransInfo 转发到指定客服
+type TransInfo struct {
+	KfAccount string `xml:"KfAccount"`
+}
+
+//NewTransferCustomer 实例化
+func NewTransferCustomer(KfAccount string) *TransferCustomer {
+	tc := new(TransferCustomer)
+	if KfAccount != "" {
+		transInfo := new(TransInfo)
+		transInfo.KfAccount = KfAccount
+		tc.TransInfo = transInfo
+	}
+	return tc
+}

+ 15 - 0
message/reply.go

@@ -0,0 +1,15 @@
+package message
+
+import "errors"
+
+//ErrInvalidReply 无效的回复
+var ErrInvalidReply = errors.New("无效的回复消息")
+
+//ErrUnsupportReply 不支持的回复类型
+var ErrUnsupportReply = errors.New("不支持的回复消息")
+
+//Reply 消息回复
+type Reply struct {
+	MsgType MsgType
+	MsgData interface{}
+}

+ 14 - 0
message/text.go

@@ -0,0 +1,14 @@
+package message
+
+//Text 文本消息
+type Text struct {
+	CommonToken
+	Content string `xml:"Content"`
+}
+
+//NewText 初始化文本消息
+func NewText(content string) *Text {
+	text := new(Text)
+	text.Content = content
+	return text
+}

+ 21 - 0
message/video.go

@@ -0,0 +1,21 @@
+package message
+
+//Video 视频消息
+type Video struct {
+	CommonToken
+
+	Video struct {
+		MediaID     string `xml:"MediaId"`
+		Title       string `xml:"Title,omitempty"`
+		Description string `xml:"Description,omitempty"`
+	} `xml:"Video"`
+}
+
+//NewVideo 回复图片消息
+func NewVideo(mediaID, title, description string) *Video {
+	video := new(Video)
+	video.Video.MediaID = mediaID
+	video.Video.Title = title
+	video.Video.Description = description
+	return video
+}

+ 17 - 0
message/voice.go

@@ -0,0 +1,17 @@
+package message
+
+//Voice 语音消息
+type Voice struct {
+	CommonToken
+
+	Voice struct {
+		MediaID string `xml:"MediaId"`
+	} `xml:"Voice"`
+}
+
+//NewVoice 回复语音消息
+func NewVoice(mediaID string) *Voice {
+	voice := new(Voice)
+	voice.Voice.MediaID = mediaID
+	return voice
+}

+ 152 - 0
oauth/oauth.go

@@ -0,0 +1,152 @@
+package oauth
+
+import (
+	"encoding/json"
+	"fmt"
+	"net/http"
+	"net/url"
+
+	"github.com/silenceper/wechat/context"
+	"github.com/silenceper/wechat/util"
+)
+
+const (
+	redirectOauthURL      = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s#wechat_redirect"
+	accessTokenURL        = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code"
+	refreshAccessTokenURL = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=%s&grant_type=refresh_token&refresh_token=%s"
+	userInfoURL           = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN"
+	checkAccessTokenURL   = "https://api.weixin.qq.com/sns/auth?access_token=%s&openid=%s"
+)
+
+//Oauth 保存用户授权信息
+type Oauth struct {
+	*context.Context
+}
+
+//NewOauth 实例化授权信息
+func NewOauth(context *context.Context) *Oauth {
+	auth := new(Oauth)
+	auth.Context = context
+	return auth
+}
+
+//GetRedirectURL 获取跳转的url地址
+func (oauth *Oauth) GetRedirectURL(redirectURI, scope, state string) (string, error) {
+	//url encode
+	urlStr := url.QueryEscape(redirectURI)
+	return fmt.Sprintf(redirectOauthURL, oauth.AppID, urlStr, scope, state), nil
+}
+
+//Redirect 跳转到网页授权
+func (oauth *Oauth) Redirect(writer http.ResponseWriter, req *http.Request, redirectURI, scope, state string) error {
+	location, err := oauth.GetRedirectURL(redirectURI, scope, state)
+	if err != nil {
+		return err
+	}
+	http.Redirect(writer, req, location, 302)
+	return nil
+}
+
+// ResAccessToken 获取用户授权access_token的返回结果
+type ResAccessToken struct {
+	util.CommonError
+
+	AccessToken  string `json:"access_token"`
+	ExpiresIn    int64  `json:"expires_in"`
+	RefreshToken string `json:"refresh_token"`
+	OpenID       string `json:"openid"`
+	Scope        string `json:"scope"`
+}
+
+// GetUserAccessToken 通过网页授权的code 换取access_token(区别于context中的access_token)
+func (oauth *Oauth) GetUserAccessToken(code string) (result ResAccessToken, err error) {
+	urlStr := fmt.Sprintf(accessTokenURL, oauth.AppID, oauth.AppSecret, code)
+	var response []byte
+	response, err = util.HTTPGet(urlStr)
+	if err != nil {
+		return
+	}
+	err = json.Unmarshal(response, &result)
+	if err != nil {
+		return
+	}
+	if result.ErrCode != 0 {
+		err = fmt.Errorf("GetUserAccessToken error : errcode=%v , errmsg=%v", result.ErrCode, result.ErrMsg)
+		return
+	}
+	return
+}
+
+//RefreshAccessToken 刷新access_token
+func (oauth *Oauth) RefreshAccessToken(refreshToken string) (result ResAccessToken, err error) {
+	urlStr := fmt.Sprintf(refreshAccessTokenURL, oauth.AppID, refreshToken)
+	var response []byte
+	response, err = util.HTTPGet(urlStr)
+	if err != nil {
+		return
+	}
+	err = json.Unmarshal(response, &result)
+	if err != nil {
+		return
+	}
+	if result.ErrCode != 0 {
+		err = fmt.Errorf("GetUserAccessToken error : errcode=%v , errmsg=%v", result.ErrCode, result.ErrMsg)
+		return
+	}
+	return
+}
+
+//CheckAccessToken 检验access_token是否有效
+func (oauth *Oauth) CheckAccessToken(accessToken, openID string) (b bool, err error) {
+	urlStr := fmt.Sprintf(checkAccessTokenURL, accessToken, openID)
+	var response []byte
+	response, err = util.HTTPGet(urlStr)
+	if err != nil {
+		return
+	}
+	var result util.CommonError
+	err = json.Unmarshal(response, &result)
+	if err != nil {
+		return
+	}
+	if result.ErrCode != 0 {
+		b = false
+		return
+	}
+	b = true
+	return
+}
+
+//UserInfo 用户授权获取到用户信息
+type UserInfo struct {
+	util.CommonError
+
+	OpenID     string   `json:"openid"`
+	Nickname   string   `json:"nickname"`
+	Sex        int32    `json:"sex"`
+	Province   string   `json:"province"`
+	City       string   `json:"city"`
+	Country    string   `json:"country"`
+	HeadImgURL string   `json:"headimgurl"`
+	Privilege  []string `json:"privilege"`
+	Unionid    string   `json:"unionid"`
+}
+
+//GetUserInfo 如果scope为 snsapi_userinfo 则可以通过此方法获取到用户基本信息
+func (oauth *Oauth) GetUserInfo(accessToken, openID string) (result UserInfo, err error) {
+	urlStr := fmt.Sprintf(userInfoURL, accessToken, openID)
+	var response []byte
+	response, err = util.HTTPGet(urlStr)
+	if err != nil {
+		return
+	}
+	err = json.Unmarshal(response, &result)
+	if err != nil {
+		return
+	}
+	if result.ErrCode != 0 {
+		err = fmt.Errorf("GetUserInfo error : errcode=%v , errmsg=%v", result.ErrCode, result.ErrMsg)
+		return
+	}
+	return
+}

+ 219 - 0
pay/pay.go

@@ -0,0 +1,219 @@
+package pay
+
+import (
+	"encoding/json"
+	"encoding/xml"
+	"errors"
+	"fmt"
+
+	"github.com/silenceper/wechat/context"
+	"github.com/silenceper/wechat/util"
+)
+
+var payGateway = "https://api.mch.weixin.qq.com/pay/unifiedorder"
+
+// Pay struct extends context
+type Pay struct {
+	*context.Context
+}
+
+// Params was NEEDED when request unifiedorder
+// 传入的参数,用于生成 prepay_id 的必需参数
+type Params struct {
+	TotalFee   string
+	CreateIP   string
+	Body       string
+	Attach     string
+	OutTradeNo string
+	OpenID     string
+}
+
+// Config 是传出用于 jsdk 用的参数
+type Config struct {
+	Timestamp int64
+	NonceStr  string
+	PrePayID  string
+	SignType  string
+	Sign      string
+}
+
+// notifyResult 是 支付成功后回调返回
+type NotifyResult struct {
+	AppID         string `xml:"appid,omitempty"`
+	Attach        string `xml:"attach,omitempty"`
+	BankType      string `xml:"bank_type,omitempty"`
+	FeeType       string `xml:"fee_type,omitempty"`
+	IsSubscribe   string `xml:"is_subscribe,omitempty"`
+	MchId         string `xml:"mch_id,omitempty"`
+	NonceStr      string `xml:"nonce_str,omitempty"`
+	Openid        string `xml:"openid,omitempty"`
+	OutTradeNo    string `xml:"out_trade_no,omitempty"`
+	ResultCode    string `xml:"result_code,omitempty"`
+	ReturnCode    string `xml:"return_code,omitempty"`
+	Sign          string `xml:"sign,omitempty"`
+	SubMchId      string `xml:"sub_mch_id,omitempty"`
+	TimeEnd       string `xml:"time_end,omitempty"`
+	TotalFee      string `xml:"total_fee,omitempty"`
+	CouponFee     string `xml:"coupon_fee,omitempty"`
+	CouponCount   string `xml:"coupon_count,omitempty"`
+	CouponType    string `xml:"coupon_type,omitempty"`
+	CouponId      string `xml:"coupon_id,omitempty"`
+	TradeType     string `xml:"trade_type,omitempty"`
+	TransactionId string `xml:"transaction_id,omitempty"`
+}
+
+// notifyResult 是 支付成功后回调返回
+type NotifyResponse struct {
+	ReturnCode string `xml:"return_code"`
+	ReturnMsg  string `xml:"return_msg"`
+}
+
+// payResult 是 unifie order 接口的返回
+type payResult struct {
+	ReturnCode string `xml:"return_code"`
+	ReturnMsg  string `xml:"return_msg"`
+	AppID      string `xml:"appid,omitempty"`
+	MchID      string `xml:"mch_id,omitempty"`
+	NonceStr   string `xml:"nonce_str,omitempty"`
+	Sign       string `xml:"sign,omitempty"`
+	ResultCode string `xml:"result_code,omitempty"`
+	TradeType  string `xml:"trade_type,omitempty"`
+	PrePayID   string `xml:"prepay_id,omitempty"`
+	CodeURL    string `xml:"code_url,omitempty"`
+	ErrCode    string `xml:"err_code,omitempty"`
+	ErrCodeDes string `xml:"err_code_des,omitempty"`
+}
+
+//payRequest 接口请求参数
+type payRequest struct {
+	AppID          string `xml:"appid"`
+	MchID          string `xml:"mch_id"`
+	DeviceInfo     string `xml:"device_info,omitempty"`
+	NonceStr       string `xml:"nonce_str"`
+	Sign           string `xml:"sign"`
+	SignType       string `xml:"sign_type,omitempty"`
+	Body           string `xml:"body"`
+	Detail         string `xml:"detail,omitempty"`
+	Attach         string `xml:"attach,omitempty"`      //附加数据
+	OutTradeNo     string `xml:"out_trade_no"`          //商户订单号
+	FeeType        string `xml:"fee_type,omitempty"`    //标价币种
+	TotalFee       string `xml:"total_fee"`             //标价金额
+	SpbillCreateIP string `xml:"spbill_create_ip"`      //终端IP
+	TimeStart      string `xml:"time_start,omitempty"`  //交易起始时间
+	TimeExpire     string `xml:"time_expire,omitempty"` //交易结束时间
+	GoodsTag       string `xml:"goods_tag,omitempty"`   //订单优惠标记
+	NotifyURL      string `xml:"notify_url"`            //通知地址
+	TradeType      string `xml:"trade_type"`            //交易类型
+	ProductID      string `xml:"product_id,omitempty"`  //商品ID
+	LimitPay       string `xml:"limit_pay,omitempty"`   //
+	OpenID         string `xml:"openid,omitempty"`      //用户标识
+	SceneInfo      string `xml:"scene_info,omitempty"`  //场景信息
+}
+
+// NewPay return an instance of Pay package
+func NewPay(ctx *context.Context) *Pay {
+	pay := Pay{Context: ctx}
+	return &pay
+}
+
+// PrePayID will request wechat merchant api and request for a pre payment order id
+func (pcf *Pay) PrePayID(p *Params) (prePayID string, err error) {
+	nonceStr := util.RandomStr(32)
+	tradeType := "JSAPI"
+	//tradeType := "MWEB"
+	template := "appid=%s&body=%s&mch_id=%s&nonce_str=%s&notify_url=%s&openid=%s&out_trade_no=%s&spbill_create_ip=%s&total_fee=%s&trade_type=%s&key=%s"
+	str := fmt.Sprintf(template, pcf.AppID, p.Body, pcf.PayMchID, nonceStr, pcf.PayNotifyURL, p.OpenID, p.OutTradeNo, p.CreateIP, p.TotalFee, tradeType, pcf.PayKey)
+	sign := util.MD5Sum(str)
+	request := payRequest{
+		AppID:          pcf.AppID,
+		MchID:          pcf.PayMchID,
+		NonceStr:       nonceStr,
+		Sign:           sign,
+		Body:           p.Body,
+		OutTradeNo:     p.OutTradeNo,
+		TotalFee:       p.TotalFee,
+		SpbillCreateIP: p.CreateIP,
+		NotifyURL:      pcf.PayNotifyURL,
+		TradeType:      tradeType,
+		OpenID:         p.OpenID,
+	}
+	rawRet, err := util.PostXML(payGateway, request)
+
+	if err != nil {
+		return "", errors.New(err.Error() + " parameters : " + str)
+	}
+	payRet := payResult{}
+	err = xml.Unmarshal(rawRet, &payRet)
+
+	s, _ := json.Marshal(payRet)
+	fmt.Println("return pay msg:", string(s))
+	if err != nil {
+		return "", errors.New(err.Error())
+	}
+	if payRet.ReturnCode == "SUCCESS" {
+		//pay success
+		if payRet.ResultCode == "SUCCESS" {
+			return payRet.PrePayID, nil
+		}
+		return "", errors.New(payRet.ErrCode + payRet.ErrCodeDes)
+	}
+	return "", errors.New("[msg : xmlUnmarshalError] [rawReturn : " + string(rawRet) + "] [params : " + str + "] [sign : " + sign + "]")
+}
+
+type PayResult struct {
+	ReturnCode string `xml:"return_code"`
+	ReturnMsg  string `xml:"return_msg"`
+	AppID      string `xml:"appid,omitempty"`
+	MchID      string `xml:"mch_id,omitempty"`
+	NonceStr   string `xml:"nonce_str,omitempty"`
+	Sign       string `xml:"sign,omitempty"`
+	ResultCode string `xml:"result_code,omitempty"`
+	TradeType  string `xml:"trade_type,omitempty"`
+	PrePayID   string `xml:"prepay_id,omitempty"`
+	CodeURL    string `xml:"code_url,omitempty"`
+	ErrCode    string `xml:"err_code,omitempty"`
+	ErrCodeDes string `xml:"err_code_des,omitempty"`
+}
+
+func (pcf *Pay) PreNative(p *Params) (*PayResult, error) {
+	nonceStr := util.RandomStr(32)
+	tradeType := "NATIVE"
+	template := "appid=%s&attach=%s&body=%s&mch_id=%s&nonce_str=%s&notify_url=%s&out_trade_no=%s&spbill_create_ip=%s&total_fee=%s&trade_type=%s&key=%s"
+	str := fmt.Sprintf(template, pcf.AppID, p.Attach, p.Body, pcf.PayMchID, nonceStr, pcf.PayNotifyURL, p.OutTradeNo, p.CreateIP, p.TotalFee, tradeType, pcf.PayKey)
+	sign := util.MD5Sum(str)
+	request := payRequest{
+		AppID:          pcf.AppID,
+		MchID:          pcf.PayMchID,
+		NonceStr:       nonceStr,
+		Sign:           sign,
+		Body:           p.Body,
+		OutTradeNo:     p.OutTradeNo,
+		TotalFee:       p.TotalFee,
+		SpbillCreateIP: p.CreateIP,
+		NotifyURL:      pcf.PayNotifyURL,
+		TradeType:      tradeType,
+		OpenID:         p.OpenID,
+		Attach:         p.Attach,
+	}
+	rawRet, err := util.PostXML(payGateway, request)
+
+	if err != nil {
+		return nil, errors.New(err.Error() + " parameters : " + str)
+	}
+	payRet := PayResult{}
+	err = xml.Unmarshal(rawRet, &payRet)
+
+	s, _ := json.Marshal(payRet)
+	fmt.Println("return pay msg:", string(s))
+	if err != nil {
+		return nil, errors.New(err.Error())
+	}
+	if payRet.ReturnCode == "SUCCESS" {
+		//pay success
+		if payRet.ResultCode == "SUCCESS" {
+			return &payRet, nil
+		}
+		return nil, errors.New(payRet.ErrCode + payRet.ErrCodeDes)
+	}
+	return nil, errors.New("[msg : xmlUnmarshalError] [rawReturn : " + string(rawRet) + "] [params : " + str + "] [sign : " + sign + "]")
+}

+ 232 - 0
server/server.go

@@ -0,0 +1,232 @@
+package server
+
+import (
+	"encoding/xml"
+	"errors"
+	"fmt"
+	"io/ioutil"
+	"reflect"
+	"runtime/debug"
+	"strconv"
+
+	"github.com/silenceper/wechat/context"
+	"github.com/silenceper/wechat/message"
+	"github.com/silenceper/wechat/util"
+)
+
+//Server struct
+type Server struct {
+	*context.Context
+
+	openID string
+
+	messageHandler func(message.MixMessage) *message.Reply
+
+	requestRawXMLMsg  []byte
+	requestMsg        message.MixMessage
+	responseRawXMLMsg []byte
+	responseMsg       interface{}
+
+	isSafeMode bool
+	random     []byte
+	nonce      string
+	timestamp  int64
+}
+
+//NewServer init
+func NewServer(context *context.Context) *Server {
+	srv := new(Server)
+	srv.Context = context
+	return srv
+}
+
+//Serve 处理微信的请求消息
+func (srv *Server) Serve() error {
+	if !srv.Validate() {
+		return fmt.Errorf("请求校验失败")
+	}
+
+	echostr, exists := srv.GetQuery("echostr")
+	if exists {
+		srv.String(echostr)
+		return nil
+	}
+
+	response, err := srv.handleRequest()
+	if err != nil {
+		return err
+	}
+
+	//debug
+	//fmt.Println("request msg = ", string(srv.requestRawXMLMsg))
+
+	return srv.buildResponse(response)
+}
+
+//Validate 校验请求是否合法
+func (srv *Server) Validate() bool {
+	timestamp := srv.Query("timestamp")
+	nonce := srv.Query("nonce")
+	signature := srv.Query("signature")
+	return signature == util.Signature(srv.Token, timestamp, nonce)
+}
+
+//HandleRequest 处理微信的请求
+func (srv *Server) handleRequest() (reply *message.Reply, err error) {
+	//set isSafeMode
+	srv.isSafeMode = false
+	encryptType := srv.Query("encrypt_type")
+	if encryptType == "aes" {
+		srv.isSafeMode = true
+	}
+
+	//set openID
+	srv.openID = srv.Query("openid")
+
+	var msg interface{}
+	msg, err = srv.getMessage()
+	if err != nil {
+		return
+	}
+	mixMessage, success := msg.(message.MixMessage)
+	if !success {
+		err = errors.New("消息类型转换失败")
+	}
+	srv.requestMsg = mixMessage
+	reply = srv.messageHandler(mixMessage)
+	return
+}
+
+//GetOpenID return openID
+func (srv *Server) GetOpenID() string {
+	return srv.openID
+}
+
+//getMessage 解析微信返回的消息
+func (srv *Server) getMessage() (interface{}, error) {
+	var rawXMLMsgBytes []byte
+	var err error
+	if srv.isSafeMode {
+		var encryptedXMLMsg message.EncryptedXMLMsg
+		if err := xml.NewDecoder(srv.Request.Body).Decode(&encryptedXMLMsg); err != nil {
+			return nil, fmt.Errorf("从body中解析xml失败,err=%v", err)
+		}
+
+		//验证消息签名
+		timestamp := srv.Query("timestamp")
+		srv.timestamp, err = strconv.ParseInt(timestamp, 10, 32)
+		if err != nil {
+			return nil, err
+		}
+		nonce := srv.Query("nonce")
+		srv.nonce = nonce
+		msgSignature := srv.Query("msg_signature")
+		msgSignatureGen := util.Signature(srv.Token, timestamp, nonce, encryptedXMLMsg.EncryptedMsg)
+		if msgSignature != msgSignatureGen {
+			return nil, fmt.Errorf("消息不合法,验证签名失败")
+		}
+
+		//解密
+		srv.random, rawXMLMsgBytes, err = util.DecryptMsg(srv.AppID, encryptedXMLMsg.EncryptedMsg, srv.EncodingAESKey)
+		if err != nil {
+			return nil, fmt.Errorf("消息解密失败, err=%v", err)
+		}
+	} else {
+		rawXMLMsgBytes, err = ioutil.ReadAll(srv.Request.Body)
+		if err != nil {
+			return nil, fmt.Errorf("从body中解析xml失败, err=%v", err)
+		}
+	}
+
+	srv.requestRawXMLMsg = rawXMLMsgBytes
+
+	return srv.parseRequestMessage(rawXMLMsgBytes)
+}
+
+func (srv *Server) parseRequestMessage(rawXMLMsgBytes []byte) (msg message.MixMessage, err error) {
+	msg = message.MixMessage{}
+	err = xml.Unmarshal(rawXMLMsgBytes, &msg)
+	return
+}
+
+//SetMessageHandler 设置用户自定义的回调方法
+func (srv *Server) SetMessageHandler(handler func(message.MixMessage) *message.Reply) {
+	srv.messageHandler = handler
+}
+
+func (srv *Server) buildResponse(reply *message.Reply) (err error) {
+	defer func() {
+		if e := recover(); e != nil {
+			err = fmt.Errorf("panic error: %v\n%s", e, debug.Stack())
+		}
+	}()
+	if reply == nil {
+		//do nothing
+		return nil
+	}
+	msgType := reply.MsgType
+	switch msgType {
+	case message.MsgTypeText:
+	case message.MsgTypeImage:
+	case message.MsgTypeVoice:
+	case message.MsgTypeVideo:
+	case message.MsgTypeMusic:
+	case message.MsgTypeNews:
+	case message.MsgTypeTransfer:
+	default:
+		err = message.ErrUnsupportReply
+		return
+	}
+
+	msgData := reply.MsgData
+	value := reflect.ValueOf(msgData)
+	//msgData must be a ptr
+	kind := value.Kind().String()
+	if "ptr" != kind {
+		return message.ErrUnsupportReply
+	}
+
+	params := make([]reflect.Value, 1)
+	params[0] = reflect.ValueOf(srv.requestMsg.FromUserName)
+	value.MethodByName("SetToUserName").Call(params)
+
+	params[0] = reflect.ValueOf(srv.requestMsg.ToUserName)
+	value.MethodByName("SetFromUserName").Call(params)
+
+	params[0] = reflect.ValueOf(msgType)
+	value.MethodByName("SetMsgType").Call(params)
+
+	params[0] = reflect.ValueOf(util.GetCurrTs())
+	value.MethodByName("SetCreateTime").Call(params)
+
+	srv.responseMsg = msgData
+	srv.responseRawXMLMsg, err = xml.Marshal(msgData)
+	return
+}
+
+//Send 将自定义的消息发送
+func (srv *Server) Send() (err error) {
+	replyMsg := srv.responseMsg
+	if srv.isSafeMode {
+		//安全模式下对消息进行加密
+		var encryptedMsg []byte
+		encryptedMsg, err = util.EncryptMsg(srv.random, srv.responseRawXMLMsg, srv.AppID, srv.EncodingAESKey)
+		if err != nil {
+			return
+		}
+		//TODO 如果获取不到timestamp nonce 则自己生成
+		timestamp := srv.timestamp
+		timestampStr := strconv.FormatInt(timestamp, 10)
+		msgSignature := util.Signature(srv.Token, timestampStr, srv.nonce, string(encryptedMsg))
+		replyMsg = message.ResponseEncryptedXMLMsg{
+			EncryptedMsg: string(encryptedMsg),
+			MsgSignature: msgSignature,
+			Timestamp:    timestamp,
+			Nonce:        srv.nonce,
+		}
+	}
+	if replyMsg != nil {
+		srv.XML(replyMsg)
+	}
+	return
+}

+ 74 - 0
template/template.go

@@ -0,0 +1,74 @@
+package template
+
+import (
+	"encoding/json"
+	"fmt"
+
+	"github.com/silenceper/wechat/context"
+	"github.com/silenceper/wechat/util"
+)
+
+const (
+	templateSendURL = "https://api.weixin.qq.com/cgi-bin/message/template/send"
+)
+
+//Template 模板消息
+type Template struct {
+	*context.Context
+}
+
+//NewTemplate 实例化
+func NewTemplate(context *context.Context) *Template {
+	tpl := new(Template)
+	tpl.Context = context
+	return tpl
+}
+
+//Message 发送的模板消息内容
+type Message struct {
+	ToUser     string               `json:"touser"`          // 必须, 接受者OpenID
+	TemplateID string               `json:"template_id"`     // 必须, 模版ID
+	URL        string               `json:"url,omitempty"`   // 可选, 用户点击后跳转的URL, 该URL必须处于开发者在公众平台网站中设置的域中
+	Color      string               `json:"color,omitempty"` // 可选, 整个消息的颜色, 可以不设置
+	Data       map[string]*DataItem `json:"data"`            // 必须, 模板数据
+
+	MiniProgram struct {
+		AppID    string `json:"appid"`    //所需跳转到的小程序appid(该小程序appid必须与发模板消息的公众号是绑定关联关系)
+		PagePath string `json:"pagepath"` //所需跳转到小程序的具体页面路径,支持带参数,(示例index?foo=bar)
+	} `json:"miniprogram"` //可选,跳转至小程序地址
+}
+
+//DataItem 模版内某个 .DATA 的值
+type DataItem struct {
+	Value string `json:"value"`
+	Color string `json:"color,omitempty"`
+}
+
+type resTemplateSend struct {
+	util.CommonError
+
+	MsgID int64 `json:"msgid"`
+}
+
+//Send 发送模板消息
+func (tpl *Template) Send(msg *Message) (msgID int64, err error) {
+	var accessToken string
+	accessToken, err = tpl.GetAccessToken()
+	if err != nil {
+		return
+	}
+	uri := fmt.Sprintf("%s?access_token=%s", templateSendURL, accessToken)
+	response, err := util.PostJSON(uri, msg)
+
+	var result resTemplateSend
+	err = json.Unmarshal(response, &result)
+	if err != nil {
+		return
+	}
+	if result.ErrCode != 0 {
+		err = fmt.Errorf("template msg send error : errcode=%v , errmsg=%v", result.ErrCode, result.ErrMsg)
+		return
+	}
+	msgID = result.MsgID
+	return
+}

+ 71 - 0
user/user.go

@@ -0,0 +1,71 @@
+package user
+
+import (
+	"encoding/json"
+	"fmt"
+
+	"github.com/silenceper/wechat/context"
+	"github.com/silenceper/wechat/util"
+)
+
+const (
+	userInfoURL = "https://api.weixin.qq.com/cgi-bin/user/info"
+)
+
+//User 用户管理
+type User struct {
+	*context.Context
+}
+
+//NewUser 实例化
+func NewUser(context *context.Context) *User {
+	user := new(User)
+	user.Context = context
+	return user
+}
+
+//Info 用户基本信息
+type Info struct {
+	util.CommonError
+
+	Subscribe     int32    `json:"subscribe"`
+	OpenID        string   `json:"openid"`
+	Nickname      string   `json:"nickname"`
+	Sex           int32    `json:"sex"`
+	City          string   `json:"city"`
+	Country       string   `json:"country"`
+	Province      string   `json:"province"`
+	Language      string   `json:"language"`
+	Headimgurl    string   `json:"headimgurl"`
+	SubscribeTime int32    `json:"subscribe_time"`
+	UnionID       string   `json:"unionid"`
+	Remark        string   `json:"remark"`
+	GroupID       int32    `json:"groupid"`
+	TagidList     []string `json:"tagid_list"`
+}
+
+//GetUserInfo 获取用户基本信息
+func (user *User) GetUserInfo(openID string) (userInfo *Info, err error) {
+	var accessToken string
+	accessToken, err = user.GetAccessToken()
+	if err != nil {
+		return
+	}
+
+	uri := fmt.Sprintf("%s?access_token=%s&openid=%s&lang=zh_CN", userInfoURL, accessToken, openID)
+	var response []byte
+	response, err = util.HTTPGet(uri)
+	if err != nil {
+		return
+	}
+	userInfo = new(Info)
+	err = json.Unmarshal(response, userInfo)
+	if err != nil {
+		return
+	}
+	if userInfo.ErrCode != 0 {
+		err = fmt.Errorf("GetUserInfo Error , errcode=%d , errmsg=%s", userInfo.ErrCode, userInfo.ErrMsg)
+		return
+	}
+	return
+}

+ 199 - 0
util/crypto.go

@@ -0,0 +1,199 @@
+package util
+
+import (
+	"bufio"
+	"bytes"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/md5"
+	"encoding/base64"
+	"encoding/hex"
+	"fmt"
+)
+
+//EncryptMsg 加密消息
+func EncryptMsg(random, rawXMLMsg []byte, appID, aesKey string) (encrtptMsg []byte, err error) {
+	defer func() {
+		if e := recover(); e != nil {
+			err = fmt.Errorf("panic error: err=%v", e)
+			return
+		}
+	}()
+	var key []byte
+	key, err = aesKeyDecode(aesKey)
+	if err != nil {
+		panic(err)
+	}
+	ciphertext := AESEncryptMsg(random, rawXMLMsg, appID, key)
+	encrtptMsg = []byte(base64.StdEncoding.EncodeToString(ciphertext))
+	return
+}
+
+//AESEncryptMsg ciphertext = AES_Encrypt[random(16B) + msg_len(4B) + rawXMLMsg + appId]
+//参考:github.com/chanxuehong/wechat.v2
+func AESEncryptMsg(random, rawXMLMsg []byte, appID string, aesKey []byte) (ciphertext []byte) {
+	const (
+		BlockSize = 32            // PKCS#7
+		BlockMask = BlockSize - 1 // BLOCK_SIZE 为 2^n 时, 可以用 mask 获取针对 BLOCK_SIZE 的余数
+	)
+
+	appIDOffset := 20 + len(rawXMLMsg)
+	contentLen := appIDOffset + len(appID)
+	amountToPad := BlockSize - contentLen&BlockMask
+	plaintextLen := contentLen + amountToPad
+
+	plaintext := make([]byte, plaintextLen)
+
+	// 拼接
+	copy(plaintext[:16], random)
+	encodeNetworkByteOrder(plaintext[16:20], uint32(len(rawXMLMsg)))
+	copy(plaintext[20:], rawXMLMsg)
+	copy(plaintext[appIDOffset:], appID)
+
+	// PKCS#7 补位
+	for i := contentLen; i < plaintextLen; i++ {
+		plaintext[i] = byte(amountToPad)
+	}
+
+	// 加密
+	block, err := aes.NewCipher(aesKey[:])
+	if err != nil {
+		panic(err)
+	}
+	mode := cipher.NewCBCEncrypter(block, aesKey[:16])
+	mode.CryptBlocks(plaintext, plaintext)
+
+	ciphertext = plaintext
+	return
+}
+
+//DecryptMsg 消息解密
+func DecryptMsg(appID, encryptedMsg, aesKey string) (random, rawMsgXMLBytes []byte, err error) {
+	defer func() {
+		if e := recover(); e != nil {
+			err = fmt.Errorf("panic error: err=%v", e)
+			return
+		}
+	}()
+	var encryptedMsgBytes, key, getAppIDBytes []byte
+	encryptedMsgBytes, err = base64.StdEncoding.DecodeString(encryptedMsg)
+	if err != nil {
+		return
+	}
+	key, err = aesKeyDecode(aesKey)
+	if err != nil {
+		panic(err)
+	}
+	random, rawMsgXMLBytes, getAppIDBytes, err = AESDecryptMsg(encryptedMsgBytes, key)
+	if err != nil {
+		err = fmt.Errorf("消息解密失败,%v", err)
+		return
+	}
+	if appID != string(getAppIDBytes) {
+		err = fmt.Errorf("消息解密校验APPID失败")
+		return
+	}
+	return
+}
+
+func aesKeyDecode(encodedAESKey string) (key []byte, err error) {
+	if len(encodedAESKey) != 43 {
+		err = fmt.Errorf("the length of encodedAESKey must be equal to 43")
+		return
+	}
+	key, err = base64.StdEncoding.DecodeString(encodedAESKey + "=")
+	if err != nil {
+		return
+	}
+	if len(key) != 32 {
+		err = fmt.Errorf("encodingAESKey invalid")
+		return
+	}
+	return
+}
+
+// AESDecryptMsg ciphertext = AES_Encrypt[random(16B) + msg_len(4B) + rawXMLMsg + appId]
+//参考:github.com/chanxuehong/wechat.v2
+func AESDecryptMsg(ciphertext []byte, aesKey []byte) (random, rawXMLMsg, appID []byte, err error) {
+	const (
+		BlockSize = 32            // PKCS#7
+		BlockMask = BlockSize - 1 // BLOCK_SIZE 为 2^n 时, 可以用 mask 获取针对 BLOCK_SIZE 的余数
+	)
+
+	if len(ciphertext) < BlockSize {
+		err = fmt.Errorf("the length of ciphertext too short: %d", len(ciphertext))
+		return
+	}
+	if len(ciphertext)&BlockMask != 0 {
+		err = fmt.Errorf("ciphertext is not a multiple of the block size, the length is %d", len(ciphertext))
+		return
+	}
+
+	plaintext := make([]byte, len(ciphertext)) // len(plaintext) >= BLOCK_SIZE
+
+	// 解密
+	block, err := aes.NewCipher(aesKey)
+	if err != nil {
+		panic(err)
+	}
+	mode := cipher.NewCBCDecrypter(block, aesKey[:16])
+	mode.CryptBlocks(plaintext, ciphertext)
+
+	// PKCS#7 去除补位
+	amountToPad := int(plaintext[len(plaintext)-1])
+	if amountToPad < 1 || amountToPad > BlockSize {
+		err = fmt.Errorf("the amount to pad is incorrect: %d", amountToPad)
+		return
+	}
+	plaintext = plaintext[:len(plaintext)-amountToPad]
+
+	// 反拼接
+	// len(plaintext) == 16+4+len(rawXMLMsg)+len(appId)
+	if len(plaintext) <= 20 {
+		err = fmt.Errorf("plaintext too short, the length is %d", len(plaintext))
+		return
+	}
+	rawXMLMsgLen := int(decodeNetworkByteOrder(plaintext[16:20]))
+	if rawXMLMsgLen < 0 {
+		err = fmt.Errorf("incorrect msg length: %d", rawXMLMsgLen)
+		return
+	}
+	appIDOffset := 20 + rawXMLMsgLen
+	if len(plaintext) <= appIDOffset {
+		err = fmt.Errorf("msg length too large: %d", rawXMLMsgLen)
+		return
+	}
+
+	random = plaintext[:16:20]
+	rawXMLMsg = plaintext[20:appIDOffset:appIDOffset]
+	appID = plaintext[appIDOffset:]
+	return
+}
+
+// 把整数 n 格式化成 4 字节的网络字节序
+func encodeNetworkByteOrder(orderBytes []byte, n uint32) {
+	orderBytes[0] = byte(n >> 24)
+	orderBytes[1] = byte(n >> 16)
+	orderBytes[2] = byte(n >> 8)
+	orderBytes[3] = byte(n)
+}
+
+// 从 4 字节的网络字节序里解析出整数
+func decodeNetworkByteOrder(orderBytes []byte) (n uint32) {
+	return uint32(orderBytes[0])<<24 |
+		uint32(orderBytes[1])<<16 |
+		uint32(orderBytes[2])<<8 |
+		uint32(orderBytes[3])
+}
+
+// MD5Sum 计算 32 位长度的 MD5 sum
+func MD5Sum(txt string) (sum string) {
+	h := md5.New()
+	buf := bufio.NewWriterSize(h, 128)
+	buf.WriteString(txt)
+	buf.Flush()
+	sign := make([]byte, hex.EncodedLen(h.Size()))
+	hex.Encode(sign, h.Sum(nil))
+	sum = string(bytes.ToUpper(sign))
+	return
+}

+ 7 - 0
util/error.go

@@ -0,0 +1,7 @@
+package util
+
+// CommonError 微信返回的通用错误json
+type CommonError struct {
+	ErrCode int64  `json:"errcode"`
+	ErrMsg  string `json:"errmsg"`
+}

+ 154 - 0
util/http.go

@@ -0,0 +1,154 @@
+package util
+
+import (
+	"bytes"
+	"crypto/tls"
+	"encoding/json"
+	"encoding/xml"
+	"fmt"
+	"io"
+	"io/ioutil"
+	"mime/multipart"
+	"net/http"
+	"os"
+)
+
+//HTTPGet get 请求
+func HTTPGet(uri string) ([]byte, error) {
+	response, err := http.Get(uri)
+	if err != nil {
+		return nil, err
+	}
+
+	defer response.Body.Close()
+	if response.StatusCode != http.StatusOK {
+		return nil, fmt.Errorf("http get error : uri=%v , statusCode=%v", uri, response.StatusCode)
+	}
+	return ioutil.ReadAll(response.Body)
+}
+
+//PostJSON post json 数据请求
+func PostJSON(uri string, obj interface{}) ([]byte, error) {
+	jsonData, err := json.Marshal(obj)
+	if err != nil {
+		return nil, err
+	}
+
+	jsonData = bytes.Replace(jsonData, []byte("\\u003c"), []byte("<"), -1)
+	jsonData = bytes.Replace(jsonData, []byte("\\u003e"), []byte(">"), -1)
+	jsonData = bytes.Replace(jsonData, []byte("\\u0026"), []byte("&"), -1)
+
+	body := bytes.NewBuffer(jsonData)
+	response, err := http.Post(uri, "application/json;charset=utf-8", body)
+	if err != nil {
+		return nil, err
+	}
+	defer response.Body.Close()
+
+	if response.StatusCode != http.StatusOK {
+		return nil, fmt.Errorf("http get error : uri=%v , statusCode=%v", uri, response.StatusCode)
+	}
+	return ioutil.ReadAll(response.Body)
+}
+
+//PostFile 上传文件
+func PostFile(fieldname, filename, uri string) ([]byte, error) {
+	fields := []MultipartFormField{
+		{
+			IsFile:    true,
+			Fieldname: fieldname,
+			Filename:  filename,
+		},
+	}
+	return PostMultipartForm(fields, uri)
+}
+
+//MultipartFormField 保存文件或其他字段信息
+type MultipartFormField struct {
+	IsFile    bool
+	Fieldname string
+	Value     []byte
+	Filename  string
+}
+
+//PostMultipartForm 上传文件或其他多个字段
+func PostMultipartForm(fields []MultipartFormField, uri string) (respBody []byte, err error) {
+	bodyBuf := &bytes.Buffer{}
+	bodyWriter := multipart.NewWriter(bodyBuf)
+
+	for _, field := range fields {
+		if field.IsFile {
+			fileWriter, e := bodyWriter.CreateFormFile(field.Fieldname, field.Filename)
+			if e != nil {
+				err = fmt.Errorf("error writing to buffer , err=%v", e)
+				return
+			}
+
+			fh, e := os.Open(field.Filename)
+			if e != nil {
+				err = fmt.Errorf("error opening file , err=%v", e)
+				return
+			}
+			defer fh.Close()
+
+			if _, err = io.Copy(fileWriter, fh); err != nil {
+				return
+			}
+		} else {
+			partWriter, e := bodyWriter.CreateFormField(field.Fieldname)
+			if e != nil {
+				err = e
+				return
+			}
+			valueReader := bytes.NewReader(field.Value)
+			if _, err = io.Copy(partWriter, valueReader); err != nil {
+				return
+			}
+		}
+	}
+
+	contentType := bodyWriter.FormDataContentType()
+	bodyWriter.Close()
+
+	resp, e := http.Post(uri, contentType, bodyBuf)
+	if e != nil {
+		err = e
+		return
+	}
+	defer resp.Body.Close()
+	if resp.StatusCode != http.StatusOK {
+		return nil, err
+	}
+	respBody, err = ioutil.ReadAll(resp.Body)
+	return
+}
+
+//PostXML perform a HTTP/POST request with XML body
+func PostXML(uri string, obj interface{}) ([]byte, error) {
+	xmlData, err := xml.Marshal(obj)
+	fmt.Println(string(xmlData))
+	if err != nil {
+		return nil, err
+	}
+
+	body := bytes.NewBuffer(xmlData)
+	//response, err := http.Post(uri, "application/xml;charset=utf-8", body)
+	fmt.Println("---------PostXML-----------")
+	tr := &http.Transport{
+		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
+	}
+
+	client := &http.Client{Transport: tr}
+
+	response, err := client.Post(uri, "application/xml;charset=utf-8", body)
+
+	if err != nil {
+		return nil, err
+	}
+	defer response.Body.Close()
+
+	if response.StatusCode != http.StatusOK {
+		return nil, fmt.Errorf("http code error : uri=%v , statusCode=%v", uri, response.StatusCode)
+	}
+	return ioutil.ReadAll(response.Body)
+}

+ 18 - 0
util/signature.go

@@ -0,0 +1,18 @@
+package util
+
+import (
+	"crypto/sha1"
+	"fmt"
+	"io"
+	"sort"
+)
+
+//Signature sha1签名
+func Signature(params ...string) string {
+	sort.Strings(params)
+	h := sha1.New()
+	for _, s := range params {
+		io.WriteString(h, s)
+	}
+	return fmt.Sprintf("%x", h.Sum(nil))
+}

+ 11 - 0
util/signature_test.go

@@ -0,0 +1,11 @@
+package util
+
+import "testing"
+
+func TestSignature(t *testing.T) {
+	//abc sig
+	abc := "a9993e364706816aba3e25717850c26c9cd0d89d"
+	if abc != Signature("a", "b", "c") {
+		t.Error("test Signature Error")
+	}
+}

+ 18 - 0
util/string.go

@@ -0,0 +1,18 @@
+package util
+
+import (
+	"math/rand"
+	"time"
+)
+
+//RandomStr 随机生成字符串
+func RandomStr(length int) string {
+	str := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
+	bytes := []byte(str)
+	result := []byte{}
+	r := rand.New(rand.NewSource(time.Now().UnixNano()))
+	for i := 0; i < length; i++ {
+		result = append(result, bytes[r.Intn(len(bytes))])
+	}
+	return string(result)
+}

+ 8 - 0
util/time.go

@@ -0,0 +1,8 @@
+package util
+
+import "time"
+
+//GetCurrTs return current timestamps
+func GetCurrTs() int64 {
+	return time.Now().Unix()
+}

+ 120 - 0
vendor/vendor.json

@@ -0,0 +1,120 @@
+{
+	"comment": "",
+	"ignore": "test",
+	"package": [
+		{
+			"checksumSHA1": "ZZ4FL7s5f8QK4RysjZObSBYGOLY=",
+			"path": "github.com/astaxie/beego",
+			"revision": "2d87d4feafeea0a133d217a82e6e02df0348fed5",
+			"revisionTime": "2016-09-22T15:18:45Z"
+		},
+		{
+			"checksumSHA1": "LwEiQ/Hyb7Ul28TSlwowN9cpWDY=",
+			"path": "github.com/astaxie/beego/config",
+			"revision": "2d87d4feafeea0a133d217a82e6e02df0348fed5",
+			"revisionTime": "2016-09-22T15:18:45Z"
+		},
+		{
+			"checksumSHA1": "s+gj1rES9SvvCIyF8W2tzlziSPE=",
+			"path": "github.com/astaxie/beego/context",
+			"revision": "2d87d4feafeea0a133d217a82e6e02df0348fed5",
+			"revisionTime": "2016-09-22T15:18:45Z"
+		},
+		{
+			"checksumSHA1": "PDNn16w89zWODshT9zlPzSmWZFA=",
+			"path": "github.com/astaxie/beego/grace",
+			"revision": "2d87d4feafeea0a133d217a82e6e02df0348fed5",
+			"revisionTime": "2016-09-22T15:18:45Z"
+		},
+		{
+			"checksumSHA1": "Iz/p1UTvFNe5HFeohX7cvKEOQW0=",
+			"path": "github.com/astaxie/beego/logs",
+			"revision": "2d87d4feafeea0a133d217a82e6e02df0348fed5",
+			"revisionTime": "2016-09-22T15:18:45Z"
+		},
+		{
+			"checksumSHA1": "R797q1pCbp086SraUETxX1rsJYw=",
+			"path": "github.com/astaxie/beego/session",
+			"revision": "2d87d4feafeea0a133d217a82e6e02df0348fed5",
+			"revisionTime": "2016-09-22T15:18:45Z"
+		},
+		{
+			"checksumSHA1": "rxxln8GHFToVnaEJz4JMv0WbaKc=",
+			"path": "github.com/astaxie/beego/toolbox",
+			"revision": "2d87d4feafeea0a133d217a82e6e02df0348fed5",
+			"revisionTime": "2016-09-22T15:18:45Z"
+		},
+		{
+			"checksumSHA1": "fRJk3RZPPz6ovbautfsfxAk+CrI=",
+			"path": "github.com/astaxie/beego/utils",
+			"revision": "2d87d4feafeea0a133d217a82e6e02df0348fed5",
+			"revisionTime": "2016-09-22T15:18:45Z"
+		},
+		{
+			"checksumSHA1": "fNAC4qgZDqF3kxq74/yyk3PWdy8=",
+			"path": "github.com/bradfitz/gomemcache/memcache",
+			"revision": "fb1f79c6b65acda83063cbc69f6bba1522558bfc",
+			"revisionTime": "2016-01-17T19:21:50Z"
+		},
+		{
+			"checksumSHA1": "RsNwOto8G8aXIiRrlFn4dtU9q/g=",
+			"path": "github.com/gin-gonic/gin",
+			"revision": "e2212d40c62a98b388a5eb48ecbdcf88534688ba",
+			"revisionTime": "2016-12-04T22:13:08Z"
+		},
+		{
+			"checksumSHA1": "UsILDoIB2S7ra+w2fMdb85mX3HM=",
+			"path": "github.com/gin-gonic/gin/binding",
+			"revision": "e2212d40c62a98b388a5eb48ecbdcf88534688ba",
+			"revisionTime": "2016-12-04T22:13:08Z"
+		},
+		{
+			"checksumSHA1": "PHv9FNb7YavJWtAHcY6ZgXmkmHs=",
+			"path": "github.com/gin-gonic/gin/render",
+			"revision": "e2212d40c62a98b388a5eb48ecbdcf88534688ba",
+			"revisionTime": "2016-12-04T22:13:08Z"
+		},
+		{
+			"checksumSHA1": "kBeNcaKk56FguvPSUCEaH6AxpRc=",
+			"path": "github.com/golang/protobuf/proto",
+			"revision": "8ee79997227bf9b34611aee7946ae64735e6fd93",
+			"revisionTime": "2016-11-17T03:31:26Z"
+		},
+		{
+			"checksumSHA1": "b0T0Hzd+zYk+OCDTFMps+jwa/nY=",
+			"path": "github.com/manucorporat/sse",
+			"revision": "ee05b128a739a0fb76c7ebd3ae4810c1de808d6d",
+			"revisionTime": "2016-01-26T18:01:36Z"
+		},
+		{
+			"checksumSHA1": "xZuhljnmBysJPta/lMyYmJdujCg=",
+			"path": "github.com/mattn/go-isatty",
+			"revision": "30a891c33c7cde7b02a981314b4228ec99380cca",
+			"revisionTime": "2016-11-23T14:36:37Z"
+		},
+		{
+			"checksumSHA1": "pancewZW3HwGvpDwfH5Imrbadc4=",
+			"path": "golang.org/x/net/context",
+			"revision": ""
+		},
+		{
+			"checksumSHA1": "8fD/im5Kwvy3JgmxulDTambmE8w=",
+			"path": "golang.org/x/sys/unix",
+			"revision": "a646d33e2ee3172a661fc09bca23bb4889a41bc8",
+			"revisionTime": "2016-07-15T05:43:45Z"
+		},
+		{
+			"checksumSHA1": "39V1idWER42Lmcmg2Uy40wMzOlo=",
+			"path": "gopkg.in/go-playground/validator.v8",
+			"revision": "5f57d2222ad794d0dffb07e664ea05e2ee07d60c",
+			"revisionTime": "2016-07-18T13:41:25Z"
+		},
+		{
+			"checksumSHA1": "12GqsW8PiRPnezDDy0v4brZrndM=",
+			"path": "gopkg.in/yaml.v2",
+			"revision": "a5b47d31c556af34a302ce5d659e6fea44d90de0",
+			"revisionTime": "2016-09-28T15:37:09Z"
+		}
+	],
+	"rootPath": "github.com/silenceper/wechat"
+}

+ 101 - 0
wechat.go

@@ -0,0 +1,101 @@
+package wechat
+
+import (
+	"net/http"
+	"sync"
+
+	"github.com/silenceper/wechat/cache"
+	"github.com/silenceper/wechat/context"
+	"github.com/silenceper/wechat/js"
+	"github.com/silenceper/wechat/material"
+	"github.com/silenceper/wechat/menu"
+	"github.com/silenceper/wechat/oauth"
+	"github.com/silenceper/wechat/pay"
+	"github.com/silenceper/wechat/server"
+	"github.com/silenceper/wechat/template"
+	"github.com/silenceper/wechat/user"
+)
+
+// Wechat struct
+type Wechat struct {
+	Context *context.Context
+}
+
+// Config for user
+type Config struct {
+	AppID          string
+	AppSecret      string
+	Token          string
+	EncodingAESKey string
+	PayMchID       string //支付 - 商户 ID
+	PayNotifyURL   string //支付 - 接受微信支付结果通知的接口地址
+	PayKey         string //支付 - 商户后台设置的支付 key
+	Cache          cache.Cache
+}
+
+// NewWechat init
+func NewWechat(cfg *Config) *Wechat {
+	context := new(context.Context)
+	copyConfigToContext(cfg, context)
+	return &Wechat{context}
+}
+
+func copyConfigToContext(cfg *Config, context *context.Context) {
+	context.AppID = cfg.AppID
+	context.AppSecret = cfg.AppSecret
+	context.Token = cfg.Token
+	context.EncodingAESKey = cfg.EncodingAESKey
+	context.PayMchID = cfg.PayMchID
+	context.PayKey = cfg.PayKey
+	context.PayNotifyURL = cfg.PayNotifyURL
+	context.Cache = cfg.Cache
+	context.SetAccessTokenLock(new(sync.RWMutex))
+	context.SetJsAPITicketLock(new(sync.RWMutex))
+}
+
+// GetServer 消息管理
+func (wc *Wechat) GetServer(req *http.Request, writer http.ResponseWriter) *server.Server {
+	wc.Context.Request = req
+	wc.Context.Writer = writer
+	return server.NewServer(wc.Context)
+}
+
+//GetAccessToken 获取access_token
+func (wc *Wechat) GetAccessToken() (string, error) {
+	return wc.Context.GetAccessToken()
+}
+
+// GetOauth oauth2网页授权
+func (wc *Wechat) GetOauth() *oauth.Oauth {
+	return oauth.NewOauth(wc.Context)
+}
+
+// GetMaterial 素材管理
+func (wc *Wechat) GetMaterial() *material.Material {
+	return material.NewMaterial(wc.Context)
+}
+
+// GetJs js-sdk配置
+func (wc *Wechat) GetJs() *js.Js {
+	return js.NewJs(wc.Context)
+}
+
+// GetMenu 菜单管理接口
+func (wc *Wechat) GetMenu() *menu.Menu {
+	return menu.NewMenu(wc.Context)
+}
+
+// GetUser 用户管理接口
+func (wc *Wechat) GetUser() *user.User {
+	return user.NewUser(wc.Context)
+}
+
+// GetTemplate 模板消息接口
+func (wc *Wechat) GetTemplate() *template.Template {
+	return template.NewTemplate(wc.Context)
+}
+
+// GetPay 返回支付消息的实例
+func (wc *Wechat) GetPay() *pay.Pay {
+	return pay.NewPay(wc.Context)
+}