1 Star 0 Fork 0

陆海空 / wechat

Create your Gitee Account
Explore and code with more than 12 million developers,Free private repositories !:)
Sign up
Clone or Download
contribute
Sync branch
Cancel
Notice: Creating folder will generate an empty file .keep, because not support in Git
Loading...
README
MIT

WeChat SDK

Build Status Go Report Card GoDoc

微信SDK的golang实现,短小精悍,同时兼容【企业微信/服务号/订阅号/小程序】

快速开始

5行代码,链式消息,快速开启微信API示例:

package main

import (
	"net/http"

	"github.com/esap/wechat" // 微信SDK包
)

func main() {
	wechat.Debug = true
	
	cfg := &wechat.WxConfig{
		Token:          "yourToken",
		AppId:          "yourAppID",
		Secret:         "yourSecret",
		EncodingAESKey: "yourEncodingAesKey",
	}

	app := wechat.New(cfg)
	app.SendText("@all", "Hello,World!")
	
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		app.VerifyURL(w, r).NewText("客服消息1").Send().NewText("客服消息2").Send().NewText("查询OK").Reply()
	})
	
	http.ListenAndServe(":9090", nil)
}

配置方式

	// 创建公众号实例(服务号/订阅号/小程序) 不带aesKey则为明文模式
	cfg := &wechat.WxConfig{
		Token:          "yourToken",
		AppId:          "yourAppID",
		Secret:         "yourSecret",
	}

	// 创建公众号实例(服务号/订阅号/小程序)
	cfg := &wechat.WxConfig{
		Token:          "yourToken",
		AppId:          "yourAppID",
		Secret:         "yourSecret",
		EncodingAESKey: "yourEncodingAesKey",
	}

	// 创建企业微信实例
	cfg := &wechat.WxConfig{
		Token:          "yourToken",
		AppId:          "yourCorpID",
		AgentId:        "yourAgentId",
		Secret:         "yourSecret",
		EncodingAESKey: "yourEncodingAesKey",
		AppType:        1,
	}

定制 HTTP client

import "github.com/esap/wechat/util"

func myCustomHTTPClient() *http.Client {
	// 配置适合自己部署环境的 HTTP client, 例如超时, 代理(可能需要认证)等
	tr := &http.Transport{
		MaxIdleConns:       10,
		IdleConnTimeout:    30 * time.Second,
		DisableCompression: true,
	}
	return &http.Client{Transport: tr}
}

util.SetHTTPClientFactory(myCustomHTTPClient)

主动推送消息

用户关注后,企业微信可以主动推送消息,服务号需要用户48小时内进入过。

	app.SendText(to, msg)
	app.SendImage(to, mediaId)
	app.SendVoice(to, mediaId)
	app.SendFile(to, mediaId)
	app.SendVideo(to, mediaId, title, desc)
	app.SendTextcard(to, title, desc, url)
	app.SendMusic(to, mediaId, title, desc, musicUrl, qhMusicUrl)
	app.SendNews(to, arts...)
	app.SendMpNews(to, arts...)
	app.SendMpNewsId(to, mediaId)
	app.SendMarkDown(to, content)

消息回调

  • 通常将app.VerifyURL(http.ResponseWriter, *http.Request)嵌入http handler

该函数返回*wechat.Context基本对象,其中的Msg为用户消息:

	// 混合用户消息,业务判断的主体
	WxMsg struct {
		XMLName      xml.Name `xml:"xml"`
		ToUserName  
		FromUserName
		CreateTime  64
		MsgId       64
		MsgType     
		Content       // text
		AgentID          // corp
		PicUrl        // image
		MediaId       // image/voice/video/shortvideo
		Format        // voice
		Recognition   // voice
		ThumbMediaId  // video
		LocationX    float32 `xml:"Latitude"`  // location
		LocationY    float32 `xml:"Longitude"` // location
		Precision    float32 // LOCATION
		Scale            // location
		Label         // location
		Title         // link
		Description   // link
		Url           // link
		Event         // event
		EventKey      // event
		SessionFrom   // event|user_enter_tempsession
		Ticket      
		FileKey     
		FileMd5     
		FileTotalLen

		ScanCodeInfo struct {
			ScanType  
			ScanResult
		}
	}
  • 如果使用其他web框架,例如echo/gin/beego等,则把VerifyURL()放入controller或handler
// echo示例 公众号回调接口
func wxApiPost(c echo.Context) error {
	ctx := app.VerifyURL(c.Response().Writer, c.Request())
	
	// TODO: 这里是其他业务操作

	return nil
}

回调回复消息

回调回复消息有两种方式:

  • 被动回复,采用XML格式编码返回(Reply);

  • 客服消息,采用json格式编码返回(Send);

  • 两种方式都可先调用*wechat.Context对象的New方法创建消息,然后调用Reply()或Send()。

  • 支持链式调用,但Reply()只有第一次有效。

	ctx.NewText("正在查询中...").Reply()
	ctx.NewText("客服消息1").Send().NewText("客服消息2").Send()
  • 被动回复可直接调用Reply(),表示已收到,然后调用客服消息。

文本消息

	ctx.NewText("content")

图片/语言/文件消息

	// mediaID 可通过素材管理-上上传多媒体文件获得
	ctx.NewImage("mediaID")
	ctx.NewVoice("mediaID")
	
	// 仅企业号支持
	ctx.NewFile("mediaID")

视频消息

	ctx.NewVideo("mediaID", "title", "description")

音乐消息

	ctx.NewMusic("thumbMediaID","title", "description", "musicURL", "hqMusicURL")

图文消息

	// 先创建三个文章
	art1 := wechat.NewArticle("拥抱AI,享受工作",
		"来自村长的ESAP系统最新技术分享",
		"http://ylin.wang/img/esap18-1.png",
		"http://ylin.wang/2017/07/13/esap18/")
	art2 := wechat.NewArticle("用企业微信代替pda实现扫描入库",
		"来自村长的ESAP系统最新技术分享",
		"http://ylin.wang/img/esap17-2.png",
		"http://ylin.wang/2017/06/23/esap17/")
	art3 := wechat.NewArticle("大道至简的哲学",
		"来自村长的工作日志",
		"http://ylin.wang/img/golang.jpg",
		"http://ylin.wang/2017/01/29/log7/")
	// 打包成新闻
	ctx.NewNews(art1, art2, art3)

模板消息

相关issue

	tlpdata := map[string]struct {
		Value `json:"value"`
		Color `json:"color"`
	}{
		"first": {Value: "我是渣渣涛", Color: "#173177"},
		"keyword1": {Value: "这是一个你从没有玩过的全新游戏", Color: "#173177"},
		"keyword2": {Value: "只要你跟着我一起试玩一下", Color: "#173177"},
		"keyword3": {Value: "你就会爱上这款游戏", Color: "#4B1515"},
		"remark":   {Value: "是兄弟就来砍我", Color: "#071D42"},
	}
	ctx.SendTemplate(
		ctx.Msg.FromUserName,
		"tempid", // 模板ID
		c.Request.Host, // 跳转url
		ctx.AppId, // 跳转小程序,比url优先
		"", // 小程序页面
		tlpdata,
	)

退出

在多微信 app 的情况下, 修改了微信的配置之后, 需要动态地调整微信配置, 这时候需要结束老的实例, 可以调用实例的 Stop 方法.

app.Stop() // Stop 可多次调用

app.AddMsg(app.NewText("zhengzhou", "这条消息不会被发出, 因为在 Stop 方法后, 后台发送消息的 goroutine 已经退出"))  

License

MIT

MIT License Copyright (c) 2017 一零村长 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

About

fork自https://github.com/esap/wechat expand collapse
Go
MIT
Cancel

Releases

No release

Contributors

All

Activities

Load More
can not load any more
Go
1
https://gitee.com/hugh2632/wechat.git
git@gitee.com:hugh2632/wechat.git
hugh2632
wechat
wechat
master

Search

14c37bed 8189591 565d56ea 8189591