chanxuehong/wechat

调用 demo

daotianya opened this issue · 0 comments

package main

import (
"log"
"net/http"

"github.com/chanxuehong/wechat.v2/mp/core"
"github.com/chanxuehong/wechat.v2/mp/menu"
"github.com/chanxuehong/wechat.v2/mp/message/callback/request"
"github.com/chanxuehong/wechat.v2/mp/message/callback/response"
"fmt"

)

const (
//看看的内容
wxAppId = " "
wxAppSecret = " "

wxOriId         = " "
wxToken         = " "
wxEncodedAESKey = " "

)

var (
// 下面两个变量不一定非要作为全局变量, 根据自己的场景来选择.
msgHandler core.Handler
msgServer *core.Server

accessTokenServer core.AccessTokenServer = core.NewDefaultAccessTokenServer(wxAppId, wxAppSecret, nil)
wechatClient      *core.Client           = core.NewClient(accessTokenServer, nil)

)

func init() {
//不知道为什么必须放到初始化当中,在 main 上不行
//创建菜单
var subButtons = make([]menu.Button, 2)
subButtons[0].SetAsViewButton("搜索", "http://www.soso.com/")
subButtons[1].SetAsClickButton("赞一下我们", "V1001_GOOD")

var mn menu.Menu
mn.Buttons = make([]menu.Button, 3)
mn.Buttons[0].SetAsScanCodePushButton("测试汤中", "rselfmenu_0_0")
mn.Buttons[1].SetAsViewButton("视频", "http://v.qq.com/")
mn.Buttons[2].SetAsSubMenuButton("子菜单", subButtons)

if err := menu.Create(wechatClient, &mn); err != nil {
	fmt.Println(err)
	return
}
fmt.Println("ok")

mux := core.NewServeMux()
mux.DefaultMsgHandleFunc(defaultMsgHandler)
mux.DefaultEventHandleFunc(defaultEventHandler)

mux.MsgHandleFunc(request.MsgTypeText, textMsgHandler)
mux.EventHandleFunc(menu.EventTypeClick, menuClickEventHandler)

msgHandler = mux
msgServer = core.NewServer(wxOriId, wxAppId, wxToken, wxEncodedAESKey, msgHandler, nil)

http.HandleFunc("/weixin", wxCallbackHandler)

}

func textMsgHandler(ctx *core.Context) {
fmt.Println("收到文本消息:\n%s\n", string(ctx.MsgPlaintext))

msg := request.GetText(ctx.MixedMsg)
resp := response.NewText(msg.FromUserName, msg.ToUserName, msg.CreateTime, msg.Content)
ctx.RawResponse(resp) // 明文回复
//ctx.AESResponse(resp, 0, "", nil) // aes密文回复

fmt.Println("老子拿到了你的消息",msg.Content)

}

func defaultMsgHandler(ctx *core.Context) {
fmt.Println("收到消息:\n%s\n", string(ctx.MsgPlaintext))
ctx.NoneResponse()
}

func menuClickEventHandler(ctx *core.Context) {
fmt.Println("收到菜单 click 事件:\n%s\n", string(ctx.MsgPlaintext))

event := menu.GetClickEvent(ctx.MixedMsg)
resp := response.NewText(event.FromUserName, event.ToUserName, event.CreateTime, "收到 click 类型的事件")
ctx.RawResponse(resp) // 明文回复
//ctx.AESResponse(resp, 0, "", nil) // aes密文回复

}

func defaultEventHandler(ctx *core.Context) {
fmt.Println("收到事件:\n%s\n", string(ctx.MsgPlaintext))
ctx.NoneResponse()
}

// wxCallbackHandler 是处理回调请求的 http handler.
// 1. 不同的 web 框架有不同的实现
// 2. 一般一个 handler 处理一个公众号的回调请求(当然也可以处理多个, 这里我只处理一个)
func wxCallbackHandler(w http.ResponseWriter, r *http.Request) {
fmt.Printf("老子信了你的邪")

msgServer.ServeHTTP(w, r, nil)
fmt.Printf("老子信了你的邪2")

}

func main() {
log.Println(http.ListenAndServe(":3080", nil))
}