beego.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package main
  2. import (
  3. "fmt"
  4. "github.com/astaxie/beego"
  5. "github.com/astaxie/beego/context"
  6. "github.com/yaotian/gowechat"
  7. "github.com/yaotian/gowechat/mp/message"
  8. "github.com/yaotian/gowechat/mp/oauth"
  9. "github.com/yaotian/gowechat/wxcontext"
  10. )
  11. var appURL = "http://localhost:8001"
  12. var config = wxcontext.Config{
  13. AppID: "your app id",
  14. AppSecret: "your app secret",
  15. Token: "your token",
  16. EncodingAESKey: "your encoding aes key",
  17. }
  18. func hello(ctx *context.Context) {
  19. //配置微信参数
  20. wc := gowechat.NewWechat(config)
  21. //微信平台mp
  22. mp, err := wc.MpMgr()
  23. if err != nil {
  24. return
  25. }
  26. // 传入request和responseWriter
  27. msgHandler := mp.GetMsgHandler(ctx.Request, ctx.ResponseWriter)
  28. //设置接收消息的处理方法
  29. msgHandler.SetHandleMessageFunc(func(msg message.MixMessage) *message.Reply {
  30. //回复消息:演示回复用户发送的消息
  31. text := message.NewText(msg.Content)
  32. return &message.Reply{message.MsgTypeText, text}
  33. })
  34. //处理消息接收以及回复
  35. err = msgHandler.Handle()
  36. if err != nil {
  37. fmt.Println(err)
  38. }
  39. }
  40. //wxOAuth 微信公众平台,网页授权
  41. func wxOAuth(ctx *context.Context) {
  42. //配置微信参数
  43. wc := gowechat.NewWechat(config)
  44. //微信公众平台
  45. mp, err := wc.MpMgr()
  46. if err != nil {
  47. return
  48. }
  49. oauthHandler := mp.GetPageOAuthHandler(ctx.Request, ctx.ResponseWriter, appURL+"/oauth")
  50. oauthHandler.SetFuncCheckOpenIDExisting(func(openID string) bool {
  51. //看自己的系统中是否已经存在此openID的用户
  52. //如果已经存在, 调用自己的Login 方法,设置cookie等,return true
  53. //如果还不存在,return false, handler会自动去取用户信息
  54. return true
  55. })
  56. oauthHandler.SetFuncAfterGetUserInfo(func(user oauth.UserInfo) {
  57. //已获得用户信息,这里用信息做注册使用
  58. //调用自己的Login方法,设置cookie等
  59. })
  60. oauthHandler.Handle()
  61. }
  62. func main() {
  63. beego.Any("/", hello)
  64. beego.Any("/oauth", wxOAuth) //需要网页授权的页面url /oauth?target=url
  65. beego.Run(":8001")
  66. }