├── static
├── coffee
└── js
│ └── weichat.js
├── README.md
├── controllers
├── get_location_controller.go
├── controller.go
└── wechat_controller.go
├── models
├── model.go
└── global
│ └── ck_http.go
├── routers
└── router.go
├── .gitignore
├── wechat
├── wechat.go
├── wx_amr.go
├── msg
│ ├── wx_msg.go
│ ├── image.go
│ ├── voice.go
│ ├── video.go
│ ├── link.go
│ ├── location.go
│ └── text.go
├── event
│ ├── wx_event.go
│ ├── view.go
│ ├── scribe.go
│ ├── click.go
│ ├── subscribe.go
│ ├── location.go
│ └── scan.go
├── wx_qr.go
├── wx_server.go
├── wx_web.go
├── jsapi
│ └── js_api.go
└── wx_user.go
├── conf
├── config.go
└── app.conf
├── main.go
├── views
└── get_location.tpl
└── LICENSE
/static/coffee:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/static/js/weichat.js:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # beeweichat
2 | 基于Beego的微信公众平台框架
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/controllers/get_location_controller.go:
--------------------------------------------------------------------------------
1 | package controllers
2 |
--------------------------------------------------------------------------------
/models/model.go:
--------------------------------------------------------------------------------
1 | package models
2 |
3 | import (
4 | // "github.com/astaxie/beego/orm"
5 | // "github.com/ckeyer/beewechat/wechat"
6 | )
7 |
--------------------------------------------------------------------------------
/controllers/controller.go:
--------------------------------------------------------------------------------
1 | package controllers
2 |
3 | import (
4 | "github.com/ckeyer/beewechat/conf"
5 | )
6 |
7 | var (
8 | config *conf.CkConfig
9 | )
10 |
11 | func init() {
12 | config = conf.NewConfig()
13 | }
14 |
--------------------------------------------------------------------------------
/routers/router.go:
--------------------------------------------------------------------------------
1 | package routers
2 |
3 | import (
4 | "github.com/astaxie/beego"
5 | "github.com/ckeyer/beewechat/controllers"
6 | )
7 |
8 | func init() {
9 | beego.Router("/", &controllers.WeChatController{})
10 | beego.Router("/home", &controllers.WeChatController{})
11 |
12 | // beego.Router("/test", &controllers.TestController{})
13 | // beego.Router("/b", &controllers.BController{})
14 | }
15 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Compiled Object files, Static and Dynamic libs (Shared Objects)
2 | *.o
3 | *.a
4 | *.so
5 | \#*
6 | .#*
7 | *~
8 |
9 | # Folders
10 | _obj
11 | _test
12 |
13 | # Architecture specific extensions/prefixes
14 | *.[568vq]
15 | [568vq].out
16 | *.conf
17 | *.cgo1.go
18 | *.cgo2.c
19 | _cgo_defun.c
20 | _cgo_gotypes.go
21 | _cgo_export.*
22 | beeweichat
23 | _testmain.go
24 |
25 | *.exe
26 | *.test
27 | *.prof
28 |
--------------------------------------------------------------------------------
/wechat/wechat.go:
--------------------------------------------------------------------------------
1 | package wechat
2 |
3 | import (
4 | "github.com/astaxie/beego/orm"
5 | "github.com/ckeyer/beewechat/conf"
6 | "github.com/ckeyer/beewechat/wechat/event"
7 | "github.com/ckeyer/beewechat/wechat/msg"
8 | _ "github.com/go-sql-driver/mysql"
9 | "github.com/hoisie/redis"
10 | )
11 |
12 | var (
13 | redcli redis.Client
14 | config *conf.CkConfig
15 | )
16 |
17 | func init() {
18 | config = conf.NewConfig()
19 | redcli.Addr = config.REDIS_ADDR
20 | }
21 |
22 | func RegDB() {
23 | msg.RegDB()
24 | event.RegDB()
25 | orm.RegisterModel(new(WebUserInfo))
26 | }
27 |
--------------------------------------------------------------------------------
/wechat/wx_amr.go:
--------------------------------------------------------------------------------
1 | package wechat
2 |
3 | type WX_AMR struct {
4 | Id int64
5 | ToUserName string `xml : "ToUserName"` //开发者微信号
6 | FromUserName string `xml : "FromUserName"` //发送方帐号(一个OpenID)
7 | CreateTime string `xml : "CreateTime"` //消息创建时间 (整型)
8 | MsgType string `xml : "MsgType"` //语音为voice
9 | MediaID string `xml : "MediaID"` //语音消息媒体id,可以调用多媒体文件下载接口拉取该媒体
10 | Format string `xml : "Format"` //语音格式:amr
11 | Recognition string `xml : "Recognition"` //语音识别结果,UTF8编码
12 | MsgID int64 `xml : "MsgID"` //消息id,64位整型
13 | }
14 |
--------------------------------------------------------------------------------
/conf/config.go:
--------------------------------------------------------------------------------
1 | package conf
2 |
3 | import (
4 | "github.com/astaxie/beego"
5 | )
6 |
7 | type CkConfig struct {
8 | WX_MYSQL_CONN string
9 | WECHAT_TOKEN string
10 | WECHAT_APPID string
11 | WECHAT_SECRET string
12 | REDIS_ADDR string
13 | }
14 |
15 | func NewConfig() *CkConfig {
16 | return &CkConfig{
17 | WX_MYSQL_CONN: beego.AppConfig.String("wx_mysql_connstr"),
18 | WECHAT_TOKEN: beego.AppConfig.String("Token"),
19 | WECHAT_APPID: beego.AppConfig.String("appid"),
20 | WECHAT_SECRET: beego.AppConfig.String("app_secret"),
21 | REDIS_ADDR: beego.AppConfig.String("redis_addr"),
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "github.com/astaxie/beego"
5 | "github.com/astaxie/beego/orm"
6 | // "github.com/ckeyer/beewechat/models"
7 | "github.com/ckeyer/beewechat/conf"
8 | _ "github.com/ckeyer/beewechat/routers"
9 | "github.com/ckeyer/beewechat/wechat"
10 | )
11 |
12 | func init() {
13 | config := conf.NewConfig()
14 | force := false // 强制重新建表
15 | verbose := false // 打印SQL语句
16 | orm.Debug = true
17 |
18 | orm.RegisterDriver("mysql", orm.DR_MySQL)
19 | orm.RegisterDataBase("default", "mysql", config.WX_MYSQL_CONN)
20 | wechat.RegDB()
21 | orm.RunSyncdb("default", force, verbose)
22 | }
23 |
24 | func main() {
25 | beego.Run()
26 | }
27 |
--------------------------------------------------------------------------------
/conf/app.conf:
--------------------------------------------------------------------------------
1 | appname = beeweichat
2 | httpport = 8080
3 | runmode = dev
4 |
5 |
6 | ### Server ###
7 | site_url = http://localhost/
8 | static_url = http://localhost/
9 |
10 | static_url_js = http://localhost/static/js/
11 | static_url_css = http://localhost/static/css/
12 | static_url_img = http://localhost/static/img/
13 |
14 | custom_url_js = http://localhost/static/js/
15 | custom_url_css = http://localhost/static/css/
16 | custom_url_img = http://localhost/static/img/
17 |
18 | redis_addr= 127.0.0.1:6379
19 |
20 | max_conn=1000
21 |
22 | ### WeiXin ###
23 | token =
24 | appId =
25 | app_secret =
26 |
27 |
28 | ### WX_MySQL ###
29 | wx_mysql_connstr = root:root@/lab204?charset=utf8
30 |
--------------------------------------------------------------------------------
/wechat/msg/wx_msg.go:
--------------------------------------------------------------------------------
1 | package msg
2 |
3 | import (
4 | "github.com/astaxie/beego/orm"
5 | )
6 |
7 | func RegDB() {
8 | orm.RegisterModel(new(TextMsg),
9 | new(ImageMsg),
10 | new(LinkMsg),
11 | new(LocationMsg),
12 | new(VideoMsg),
13 | new(VoiceMsg))
14 | }
15 |
16 | func ReceiveMsg(content string, msgtype string) (r string) {
17 | r = ""
18 | switch msgtype {
19 | case "text":
20 | r = ReceiveTextMsg(content)
21 | case "image":
22 | r = ReceiveImageMsg(content)
23 | case "voice":
24 | r = ReceiveVoiceMsg(content)
25 | case "video":
26 | r = ReceiveVideoMsg(content)
27 | case "location":
28 | r = ReceiveLocationMsg(content)
29 | case "link":
30 | r = ReceiveLinkMsg(content)
31 | default:
32 | r = "error"
33 | }
34 | return
35 | }
36 |
--------------------------------------------------------------------------------
/wechat/event/wx_event.go:
--------------------------------------------------------------------------------
1 | package event
2 |
3 | import (
4 | "github.com/astaxie/beego/orm"
5 | )
6 |
7 | func RegDB() {
8 | orm.RegisterModel(new(ClickEvent),
9 | new(LocationEvent),
10 | new(ScanEvent),
11 | new(ScribeEvent),
12 | new(SubscribeEvent),
13 | new(ViewEvent))
14 | }
15 |
16 | func ReceiveEvent(content string, msgtype string) string {
17 | switch msgtype {
18 | case "subscribe":
19 | return ReceiveSubscribeEvent(content)
20 | case "unsubscribe":
21 | return ReceiveUnsubscribeEvent(content)
22 | case "SCAN":
23 | return ReceiveScanEvent(content)
24 | case "LOCATION":
25 | return ReceiveLocationvent(content)
26 | case "CLICK":
27 | return ReceiveClickvent(content)
28 | case "VIEW":
29 | return ReceiveViewEvent(content)
30 | }
31 | return ""
32 | }
33 |
--------------------------------------------------------------------------------
/wechat/event/view.go:
--------------------------------------------------------------------------------
1 | package event
2 |
3 | import (
4 | "encoding/xml"
5 | "github.com/astaxie/beego/orm"
6 | "time"
7 | )
8 |
9 | type ViewEvent struct {
10 | Id int64
11 | ToUserName string `xml:"ToUserName"`
12 | FromUserName string `xml:"FromUserName"`
13 | CreateTime int `xml:"CreateTime"`
14 | MsgType string `xml:"MsgType"`
15 | Event string `xml:"Event"`
16 | EventKey string `xml:"EventKey"`
17 | Created time.Time `orm:"auto_now_add;type(datetime)"`
18 | }
19 |
20 | func ReceiveViewEvent(content string) string {
21 | var msg ViewEvent
22 | err := xml.Unmarshal([]byte(content), &msg)
23 | if err != nil {
24 | return ""
25 | }
26 | return ""
27 | }
28 |
29 | func (this *ViewEvent) Insert() error {
30 | o := orm.NewOrm()
31 |
32 | id, err := o.Insert(this)
33 | if err == nil {
34 | this.Id = id
35 | }
36 | return err
37 | }
38 |
--------------------------------------------------------------------------------
/wechat/event/scribe.go:
--------------------------------------------------------------------------------
1 | package event
2 |
3 | import (
4 | // "github.com/astaxie/beego"
5 | "encoding/xml"
6 | "github.com/astaxie/beego/orm"
7 | "time"
8 | )
9 |
10 | type ScribeEvent struct {
11 | Id int64
12 | ToUserName string `xml:"ToUserName"`
13 | FromUserName string `xml:"FromUserName"`
14 | CreateTime int `xml:"CreateTime"`
15 | MsgType string `xml:"MsgType"`
16 | Event string `xml:"Event"`
17 | Created time.Time `orm:"auto_now_add;type(datetime)"`
18 | }
19 |
20 | func ReceiveSubscribeEvent(content string) string {
21 | var msg SubscribeEvent
22 | err := xml.Unmarshal([]byte(content), &msg)
23 | if err != nil {
24 | return ""
25 | }
26 | return ""
27 | }
28 |
29 | func (this *ScribeEvent) Insert() error {
30 | o := orm.NewOrm()
31 |
32 | id, err := o.Insert(this)
33 | if err == nil {
34 | this.Id = id
35 | }
36 | return err
37 | }
38 |
--------------------------------------------------------------------------------
/wechat/event/click.go:
--------------------------------------------------------------------------------
1 | package event
2 |
3 | import (
4 | "encoding/xml"
5 | "github.com/astaxie/beego/orm"
6 | "time"
7 | )
8 |
9 | // 点击事件结构体
10 | type ClickEvent struct {
11 | Id int64
12 | ToUserName string `xml:"ToUserName"`
13 | FromUserName string `xml:"FromUserName"`
14 | CreateTime int `xml:"CreateTime"`
15 | MsgType string `xml:"MsgType"`
16 | Event string `xml:"Event"`
17 | EventKey string `xml:"EventKey"`
18 | Created time.Time `orm:"auto_now_add;type(datetime)"`
19 | }
20 |
21 | func ReceiveClickvent(content string) string {
22 | var msg ClickEvent
23 | err := xml.Unmarshal([]byte(content), &msg)
24 | if err != nil {
25 | return ""
26 | }
27 | return ""
28 | }
29 |
30 | func (this *ClickEvent) Insert() error {
31 | o := orm.NewOrm()
32 |
33 | id, err := o.Insert(this)
34 | if err == nil {
35 | this.Id = id
36 | }
37 | return err
38 | }
39 |
--------------------------------------------------------------------------------
/wechat/msg/image.go:
--------------------------------------------------------------------------------
1 | package msg
2 |
3 | import (
4 | "encoding/xml"
5 | "github.com/astaxie/beego/orm"
6 | "time"
7 | )
8 |
9 | type ImageMsg struct {
10 | Id int64
11 | ToUserName string `xml:"ToUserName"`
12 | FromUserName string `xml:"FromUserName"`
13 | CreateTime int `xml:"CreateTime"`
14 | MsgType string `xml:"MsgType"`
15 | PicUrl string `xml:"PicUrl"`
16 | MediaId int `xml:"MediaId"`
17 | MsgId int64 `xml:"MsgId"`
18 | Created time.Time `orm:"auto_now_add;type(datetime)"`
19 | }
20 |
21 | func (this *ImageMsg) Insert() error {
22 | o := orm.NewOrm()
23 | _, e := o.Insert(this)
24 | if e != nil {
25 | return e
26 | }
27 | return nil
28 | }
29 |
30 | func ReceiveImageMsg(content string) string {
31 | var msg ImageMsg
32 | err := xml.Unmarshal([]byte(content), &msg)
33 | if err != nil {
34 | return ""
35 | }
36 | return ""
37 | }
38 |
--------------------------------------------------------------------------------
/wechat/msg/voice.go:
--------------------------------------------------------------------------------
1 | package msg
2 |
3 | import (
4 | "encoding/xml"
5 | "github.com/astaxie/beego/orm"
6 | "time"
7 | )
8 |
9 | type VoiceMsg struct {
10 | Id int64
11 | ToUserName string `xml:"ToUserName"`
12 | FromUserName string `xml:"FromUserName"`
13 | CreateTime int `xml:"CreateTime"`
14 | MsgType string `xml:"MsgType"`
15 | MediaId string `xml:"MediaId"`
16 | Format string `xml:"Format"`
17 | MsgId int64 `xml:"MsgId"`
18 | Created time.Time `orm:"auto_now_add;type(datetime)"`
19 | }
20 |
21 | func ReceiveVoiceMsg(content string) string {
22 | var msg VoiceMsg
23 | err := xml.Unmarshal([]byte(content), &msg)
24 | if err != nil {
25 | return ""
26 | }
27 | return ""
28 | }
29 |
30 | func (this *VoiceMsg) Insert() error {
31 | o := orm.NewOrm()
32 | _, e := o.Insert(this)
33 | if e != nil {
34 | return e
35 | }
36 | return nil
37 | }
38 |
--------------------------------------------------------------------------------
/wechat/msg/video.go:
--------------------------------------------------------------------------------
1 | package msg
2 |
3 | import (
4 | "encoding/xml"
5 | "github.com/astaxie/beego/orm"
6 | "time"
7 | )
8 |
9 | type VideoMsg struct {
10 | Id int64
11 | ToUserName string `xml:"ToUserName"`
12 | FromUserName string `xml:"FromUserName"`
13 | CreateTime int `xml:"CreateTime"`
14 | MsgType string `xml:"MsgType"`
15 | MediaId int `xml:"MediaId"`
16 | ThumbMediaId string `xml:"ThumbMediaId"`
17 | MsgId int64 `xml:"MsgId"`
18 | Created time.Time `orm:"auto_now_add;type(datetime)"`
19 | }
20 |
21 | func ReceiveVideoMsg(content string) string {
22 | var msg VideoMsg
23 | err := xml.Unmarshal([]byte(content), &msg)
24 | if err != nil {
25 | return ""
26 | }
27 | return ""
28 | }
29 |
30 | func (this *VideoMsg) Insert() error {
31 | o := orm.NewOrm()
32 | _, e := o.Insert(this)
33 | if e != nil {
34 | return e
35 | }
36 | return nil
37 | }
38 |
--------------------------------------------------------------------------------
/wechat/event/subscribe.go:
--------------------------------------------------------------------------------
1 | package event
2 |
3 | import (
4 | "encoding/xml"
5 | "github.com/astaxie/beego/orm"
6 | "time"
7 | )
8 |
9 | type SubscribeEvent struct {
10 | Id int64
11 | ToUserName string `xml:"ToUserName"`
12 | FromUserName string `xml:"FromUserName"`
13 | CreateTime int `xml:"CreateTime"`
14 | MsgType string `xml:"MsgType"`
15 | Event string `xml:"Event"`
16 | EventKey int32 `xml:"EventKey"`
17 | Ticket string `xml:"Ticket"`
18 | Created time.Time `orm:"auto_now_add;type(datetime)"`
19 | }
20 |
21 | func ReceiveUnsubscribeEvent(content string) string {
22 | var msg ScribeEvent
23 | err := xml.Unmarshal([]byte(content), &msg)
24 | if err != nil {
25 | return ""
26 | }
27 | return ""
28 | }
29 |
30 | func (this *SubscribeEvent) Insert() error {
31 | o := orm.NewOrm()
32 |
33 | id, err := o.Insert(this)
34 | if err == nil {
35 | this.Id = id
36 | }
37 | return err
38 | }
39 |
--------------------------------------------------------------------------------
/wechat/msg/link.go:
--------------------------------------------------------------------------------
1 | package msg
2 |
3 | import (
4 | "encoding/xml"
5 | "github.com/astaxie/beego/orm"
6 | "time"
7 | )
8 |
9 | type LinkMsg struct {
10 | Id int64
11 | ToUserName string `xml: "ToUserName"`
12 | FromUserName string `xml: "FromUserName"`
13 | CreateTime int `xml: "CreateTime"`
14 | MsgType string `xml: "MsgType"`
15 | Title string `xml: "Title"`
16 | Description string `xml: "Description"`
17 | Url string `xml: "Url"`
18 | MsgId int64 `xml: "MsgId"`
19 | Created time.Time `orm:"auto_now_add;type(datetime)"`
20 | }
21 |
22 | func ReceiveLinkMsg(content string) string {
23 | var msg LinkMsg
24 | err := xml.Unmarshal([]byte(content), &msg)
25 | if err != nil {
26 | return ""
27 | }
28 | return ""
29 | }
30 |
31 | func (this *LinkMsg) Insert() error {
32 | o := orm.NewOrm()
33 | _, e := o.Insert(this)
34 | if e != nil {
35 | return e
36 | }
37 | return nil
38 | }
39 |
--------------------------------------------------------------------------------
/wechat/event/location.go:
--------------------------------------------------------------------------------
1 | package event
2 |
3 | import (
4 | "encoding/xml"
5 | "github.com/astaxie/beego/orm"
6 | "time"
7 | )
8 |
9 | // 地理位置推送事件结构体
10 | type LocationEvent struct {
11 | Id int64
12 | ToUserName string `xml:"ToUserName"`
13 | FromUserName string `xml:"FromUserName"`
14 | CreateTime int `xml:"CreateTime"`
15 | MsgType string `xml:"MsgType"`
16 | Event string `xml:"Event"`
17 | Latitude float64 `xml:"Latitude"`
18 | Longitude float64 `xml:"Longitude"`
19 | Precision int `xml:"Precision"`
20 | Created time.Time `orm:"auto_now_add;type(datetime)"`
21 | }
22 |
23 | func ReceiveLocationvent(content string) string {
24 | var msg LocationEvent
25 | err := xml.Unmarshal([]byte(content), &msg)
26 | if err != nil {
27 | return ""
28 | }
29 | return ""
30 | }
31 |
32 | func (this *LocationEvent) Insert() error {
33 | o := orm.NewOrm()
34 |
35 | id, err := o.Insert(this)
36 | if err == nil {
37 | this.Id = id
38 | }
39 | return err
40 | }
41 |
--------------------------------------------------------------------------------
/wechat/msg/location.go:
--------------------------------------------------------------------------------
1 | package msg
2 |
3 | import (
4 | "encoding/xml"
5 | "github.com/astaxie/beego/orm"
6 | "time"
7 | )
8 |
9 | type LocationMsg struct {
10 | Id int64
11 | ToUserName string `xml: "ToUserName"`
12 | FromUserName string `xml: "FromUserName"`
13 | CreateTime int `xml: "CreateTime"`
14 | MsgType string `xml: "MsgType"`
15 | Location_X float64 `xml: "Location_X"`
16 | Location_Y float64 `xml: "Location_Y"`
17 | Scale int `xml: "Scale"`
18 | Label string `xml: "Label"`
19 | MsgId int64 `xml: "MsgId"`
20 | Created time.Time `orm:"auto_now_add;type(datetime)"`
21 | }
22 |
23 | func ReceiveLocationMsg(content string) string {
24 | var msg LocationMsg
25 | err := xml.Unmarshal([]byte(content), &msg)
26 | if err != nil {
27 | return ""
28 | }
29 | return ""
30 | }
31 |
32 | func (this *LocationMsg) Insert() error {
33 | o := orm.NewOrm()
34 | _, e := o.Insert(this)
35 | if e != nil {
36 | return e
37 | }
38 | return nil
39 | }
40 |
--------------------------------------------------------------------------------
/models/global/ck_http.go:
--------------------------------------------------------------------------------
1 | package global
2 |
3 | import (
4 | "bytes"
5 | "io/ioutil"
6 | "net/http"
7 | )
8 |
9 | // 返回Get数据
10 | func HttpGet(url string) (content string, statusCode int) {
11 | resp, err1 := http.Get(url)
12 | if err1 != nil {
13 | statusCode = -100
14 | return
15 | }
16 | defer resp.Body.Close()
17 | data, err2 := ioutil.ReadAll(resp.Body)
18 | if err2 != nil {
19 | statusCode = -200
20 | return
21 | }
22 | statusCode = resp.StatusCode
23 | content = string(data)
24 | return
25 | }
26 |
27 | // 返回Get数据
28 | func HttpGetToBytes(url string) (content []byte, statusCode int) {
29 | resp, err1 := http.Get(url)
30 | if err1 != nil {
31 | statusCode = -100
32 | return
33 | }
34 | defer resp.Body.Close()
35 | data, err2 := ioutil.ReadAll(resp.Body)
36 | if err2 != nil {
37 | statusCode = -200
38 | return
39 | }
40 | statusCode = resp.StatusCode
41 | content = data
42 | return
43 | }
44 |
45 | // 返回Post数据
46 | func HttpPost(url string, post_data string) (content string, statusCode int) {
47 | client := &http.Client{}
48 | postBytesReader := bytes.NewReader([]byte(post_data))
49 | resp, err1 := client.Post(url, "posttext", postBytesReader)
50 | // resp, err1 := http.NewRequest("POST", url, postBytesReader)
51 | // resp, err1 := http.Post(url, "bodyType", body)
52 | if err1 != nil {
53 | statusCode = -100
54 | return
55 | }
56 | defer resp.Body.Close()
57 | data, err2 := ioutil.ReadAll(resp.Body)
58 | if err2 != nil {
59 | statusCode = -200
60 | return
61 | }
62 | content = string(data)
63 | return
64 | }
65 |
--------------------------------------------------------------------------------
/controllers/wechat_controller.go:
--------------------------------------------------------------------------------
1 | package controllers
2 |
3 | import (
4 | "crypto/sha1"
5 | "fmt"
6 | "github.com/astaxie/beego"
7 | wx "github.com/ckeyer/beewechat/wechat"
8 | "io"
9 | "log"
10 | // "net/http"
11 | "sort"
12 | )
13 |
14 | type WeChatController struct {
15 | beego.Controller
16 | }
17 |
18 | func (this *WeChatController) Get() {
19 | //Start 微信服务器认证部分
20 | signature := this.GetString("signature")
21 | timestamp := this.GetString("timestamp")
22 | nonce := this.GetString("nonce")
23 | echostr := this.GetString("echostr")
24 |
25 | tmps := []string{config.WECHAT_TOKEN, timestamp, nonce}
26 | sort.Strings(tmps)
27 | tmpStr := tmps[0] + tmps[1] + tmps[2]
28 |
29 | tmp := func(data string) string {
30 | t := sha1.New()
31 | io.WriteString(t, data)
32 | return fmt.Sprintf("%x", t.Sum(nil))
33 | }(tmpStr)
34 | if tmp == signature {
35 | this.Ctx.WriteString(echostr)
36 | return
37 | }
38 | //Over 微信服务器认证部分
39 |
40 | //Start 微信网页认证部分
41 | code := this.GetString("code")
42 | log.Println(this.GetString("code"))
43 | log.Println(this.GetString("status"))
44 | if code != "" {
45 | wat := wx.GetWebAccessToken(code)
46 | u := wat.GetUserInfo()
47 | u.Insert()
48 | }
49 | //Over 微信网页认证部分
50 |
51 | // this.Data["QRImgUrl"] = wx.GetTempTicket(120, 1214, "FUNX_HOME")
52 | // this.Data["PageTitle"] = "FANX-HOME"
53 | // this.Data["Website"] = "beego.me"
54 | // this.Data["Email"] = "astaxie@gmail.com"
55 | // this.TplNames = ".tpl"
56 | }
57 |
58 | func (this *WeChatController) Post() {
59 | s := fmt.Sprintf("%s", this.Ctx.Input.CopyBody())
60 | // log.Println(s)
61 | r := wx.ReceiveMsg(s)
62 | // log.Println(r)
63 | this.Ctx.WriteString(r)
64 | }
65 |
--------------------------------------------------------------------------------
/wechat/event/scan.go:
--------------------------------------------------------------------------------
1 | package event
2 |
3 | import (
4 | "encoding/xml"
5 | "fmt"
6 | "github.com/astaxie/beego"
7 | "github.com/astaxie/beego/orm"
8 | "github.com/hoisie/redis"
9 | "time"
10 | )
11 |
12 | // 二维码扫码事件结构体
13 | type ScanEvent struct {
14 | Id int64
15 | ToUserName string `xml:"ToUserName"`
16 | FromUserName string `xml:"FromUserName"`
17 | CreateTime int `xml:"CreateTime"`
18 | MsgType string `xml:"MsgType"`
19 | Event string `xml:"Event"`
20 | EventKey string `xml:"EventKey"`
21 | Ticket string `xml:"Ticket"`
22 | Created time.Time `orm:"auto_now_add;type(datetime)"`
23 | }
24 |
25 | func ReceiveScanEvent(content string) string {
26 | var this ScanEvent
27 | fmt.Println(content)
28 | err := xml.Unmarshal([]byte(content), &this)
29 | if err != nil {
30 | return ""
31 | }
32 | data := "请联系系统管理员进行身份认证"
33 | if "101" == this.EventKey &&
34 | "oecJ3jhN5usPBQMIXqc9bVP0toi4" == this.Ticket {
35 | data = "吼吼吼"
36 | var redcli redis.Client
37 | redcli.Addr = beego.AppConfig.String("redis_addr")
38 | redcli.Hset(this.Ticket, "scan", []byte("true"))
39 | }
40 | fmt.Println(data)
41 | rcontent := `
42 |
43 |
44 | ` + fmt.Sprint((time.Now().Unix())) + `
45 |
46 |
47 | `
48 | return rcontent
49 | }
50 |
51 | func (this *ScanEvent) Insert() error {
52 | o := orm.NewOrm()
53 |
54 | id, err := o.Insert(this)
55 | if err == nil {
56 | this.Id = id
57 | }
58 | return err
59 | }
60 |
--------------------------------------------------------------------------------
/wechat/wx_qr.go:
--------------------------------------------------------------------------------
1 | package wechat
2 |
3 | import (
4 | "encoding/json"
5 | "github.com/astaxie/beego"
6 | "github.com/ckeyer/beewechat/models/global"
7 | "github.com/hoisie/redis"
8 | "io"
9 | "log"
10 | "strconv"
11 | "strings"
12 | )
13 |
14 | type Ticket struct {
15 | Ticket string `json : "ticket"` // 获取的二维码ticket
16 | Expire_seconds int `json : "expire_seconds"` //二维码的有效时间,以秒为单位。最大不超过1800。
17 | Url string `json : "url"`
18 | }
19 |
20 | func GetTempTicket(expire_seconds int, scene_id int, scene_str string) string {
21 | url := `https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=` + GetAccessToken()
22 | data := `{"expire_seconds": ` + strconv.Itoa(expire_seconds) +
23 | `, "action_name": "QR_SCENE", ` +
24 | `"action_info": {"scene": {"scene_id": ` + strconv.Itoa(scene_id) +
25 | `,"scene_str":"` + scene_str + `"}}}`
26 | if ticket := getTicket(url, data); len(ticket) < 1 {
27 | return ""
28 | } else {
29 | var redcli redis.Client
30 | redcli.Addr = beego.AppConfig.String("redis_addr")
31 | redcli.Hset(ticket, "scene_id", []byte(strconv.Itoa(scene_id)))
32 | redcli.Expire(ticket, 120)
33 | return ticket
34 | }
35 | }
36 | func GetTempQrUrl(expire_seconds int, scene_id int, scene_str string) string {
37 | return "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + GetTempTicket(expire_seconds, scene_id, scene_str)
38 | }
39 | func getTicket(url string, data string) string {
40 | c, status := global.HttpPost(url, data)
41 | if status < 0 {
42 | log.Fatal(status)
43 | }
44 | var v Ticket
45 | dec := json.NewDecoder(strings.NewReader(c))
46 | for {
47 | if err := dec.Decode(&v); err == io.EOF {
48 | break
49 | } else if err != nil {
50 | log.Fatal(err)
51 | return ""
52 | }
53 | }
54 | return v.Ticket
55 | }
56 |
--------------------------------------------------------------------------------
/views/get_location.tpl:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | .PageTitle?>
8 |
9 |
10 |
11 |
12 |
13 |
55 |
56 |
57 |
58 |
--------------------------------------------------------------------------------
/wechat/msg/text.go:
--------------------------------------------------------------------------------
1 | package msg
2 |
3 | import (
4 | "encoding/xml"
5 | "fmt"
6 | "github.com/astaxie/beego"
7 | "github.com/astaxie/beego/logs"
8 | "github.com/astaxie/beego/orm"
9 | "time"
10 | )
11 |
12 | var CKLog *logs.BeeLogger
13 |
14 | func init() {
15 | CKLog = beego.BeeLogger
16 | CKLog.SetLevel(beego.LevelDebug)
17 | }
18 |
19 | type TextMsg struct {
20 | Id int64 `xml:"-"`
21 | ToUserName string `xml:"ToUserName"`
22 | FromUserName string `xml:"FromUserName"`
23 | CreateTime int `xml:"CreateTime"`
24 | MsgType string `xml:"MsgType"`
25 | Content string `xml:"Content"`
26 | MsgId int64 `xml:"MsgId"`
27 | Created time.Time `orm:"auto_now_add;type(datetime)"`
28 | }
29 |
30 | func (this *TextMsg) Insert() error {
31 | o := orm.NewOrm()
32 | _, e := o.Insert(this)
33 | if e != nil {
34 | return e
35 | }
36 | return nil
37 | }
38 |
39 | func ReceiveTextMsg(content string) string {
40 | var msg TextMsg
41 | err := xml.Unmarshal([]byte(content), &msg)
42 | if err != nil {
43 | return ""
44 | }
45 | msg.Insert()
46 | CKLog.Debug(msg.Content)
47 | return msg.ReplyTextMsg(`/::D/::D
48 | 服务器维护中
49 | /::D/::D`)
50 | }
51 | func (this *TextMsg) ReplyTextMsg(data string) string {
52 | xmldata := `
53 |
54 |
55 | ` + fmt.Sprint((time.Now().Unix())) + `
56 |
57 |
58 | `
59 | CKLog.Info("回复:%s", data)
60 | return xmldata
61 | }
62 |
63 | // func FindUserByName(uname string) (*TextMsg, error) {
64 | // o := orm.NewOrm()
65 | // user := new(User)
66 | // qs := o.QueryTable("user")
67 | // err := qs.Filter("username", uname).One(user)
68 | // if err != nil {
69 | // return nil, err
70 | // }
71 | // return user, nil
72 | // }
73 |
--------------------------------------------------------------------------------
/wechat/wx_server.go:
--------------------------------------------------------------------------------
1 | /*
2 | * 与腾讯服务器的相关交互
3 | **/
4 | package wechat
5 |
6 | import (
7 | "encoding/json"
8 | "encoding/xml"
9 | "errors"
10 | "fmt"
11 | "github.com/ckeyer/beewechat/models/global"
12 | // "github.com/astaxie/beego"
13 | "github.com/ckeyer/beewechat/wechat/event"
14 | "github.com/ckeyer/beewechat/wechat/msg"
15 | "io"
16 | "log"
17 | "strconv"
18 | "strings"
19 | "time"
20 | )
21 |
22 | const (
23 | // redis中微信 AccessToken 的key
24 | REDIS_KEY_WC_ACCESS_TOKEN = "wx_AccessToken"
25 | )
26 |
27 | type AccessToken struct {
28 | Access_token string `json: "access_token"`
29 | Expires_in int64 `json:"expires_in"`
30 | }
31 |
32 | type MsgType struct {
33 | MsgType string `xml:"MsgType"`
34 | Event string `xml:"Event"`
35 | }
36 |
37 | func (this *AccessToken) Decode(jsonstr []byte) error {
38 | return json.Unmarshal(jsonstr, &this)
39 | }
40 |
41 | // 更新微信的AccessToken到Redis中 key=REDIS_KEY_WC_ACCESS_TOKEN
42 | func UpdateAccessToken() (expires_in int, err error) {
43 | url := "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + config.WECHAT_APPID +
44 | "&secret=" + config.WECHAT_SECRET
45 | if c, status := global.HttpGet(url); status < 0 {
46 | err = errors.New("access_token 获取异常 " + strconv.Itoa(status))
47 | } else {
48 | log.Println(c)
49 | var v AccessToken
50 | dec := json.NewDecoder(strings.NewReader(c))
51 | for {
52 | if err = dec.Decode(&v); err == io.EOF {
53 | break
54 | } else if err != nil {
55 | log.Fatal(err)
56 | return
57 | }
58 | }
59 |
60 | expires_in = (int)(v.Expires_in)
61 | err = redcli.Setex(REDIS_KEY_WC_ACCESS_TOKEN, v.Expires_in, []byte(v.Access_token))
62 | if err != nil {
63 | log.Println(err.Error())
64 | } else {
65 | log.Println("Successful: get AccessToken ")
66 | }
67 | }
68 | return
69 | }
70 |
71 | func AutoGetAccessToken() {
72 | ei, err := UpdateAccessToken()
73 | if err != nil {
74 | log.Fatal(err.Error())
75 | return
76 | }
77 | outtime := (time.Duration)(ei-100) * time.Second
78 | go time.AfterFunc(outtime, AutoGetAccessToken)
79 | }
80 |
81 | func GetAccessToken() string {
82 | b, e := redcli.Get(REDIS_KEY_WC_ACCESS_TOKEN)
83 | if e != nil {
84 | log.Println(e.Error())
85 | }
86 | return fmt.Sprintf("%s", b)
87 | }
88 |
89 | func ReceiveMsg(content string) (r string) {
90 | r = ""
91 |
92 | var msgtype MsgType
93 | err := xml.Unmarshal([]byte(content), &msgtype)
94 | if err != nil {
95 | return
96 | }
97 | switch msgtype.MsgType {
98 | // case "text", "image", "voice", "video", "location", "link":
99 | case "event":
100 | r = event.ReceiveEvent(content, msgtype.Event)
101 | default:
102 | r = msg.ReceiveMsg(content, msgtype.Event)
103 | }
104 | return
105 | }
106 |
--------------------------------------------------------------------------------
/wechat/wx_web.go:
--------------------------------------------------------------------------------
1 | /*
2 | * 通过网页授权获取用户基本信息
3 | **/
4 | package wechat
5 |
6 | import (
7 | "encoding/json"
8 | "github.com/astaxie/beego/orm"
9 | "github.com/ckeyer/beewechat/models/global"
10 | "io"
11 | "log"
12 | "strings"
13 | )
14 |
15 | type WebAccessToken struct {
16 | Access_token string `json:"access_token"`
17 | Expires_in int `json:"expires_in"`
18 | Refresh_token string `json:"refresh_token"`
19 | Openid string `json:"openid"`
20 | Scope string `json:"scope"`
21 | }
22 |
23 | type WebUserInfo struct {
24 | Id int64
25 | Openid string `json:"openid"` // 用户的唯一标识
26 | Nickname string `json:"nickname"` // 用户昵称
27 | Sex int `json:"sex"` // 用户的性别,值为1时是男性,值为2时是女性,值为0时是未知
28 | Province string `json:"province"` // 用户个人资料填写的省份
29 | City string `json:"city"` // 普通用户个人资料填写的城市
30 | Country string `json:"country"` // 国家,如中国为CN
31 | Headimgurl string `json:"headimgurl"` // 用户头像,最后一个数值代表正方形头像大小
32 | Privilege []string `orm:"-"` // 用户特权信息,json 数组,如微信沃卡用户为(chinaunicom)
33 | Unionid int64 `json:"unionid"` //
34 | }
35 |
36 | // 获取网页端的 AccessToken
37 | func GetWebAccessToken(code string) *WebAccessToken {
38 | url := "https://api.weixin.qq.com/sns/oauth2/access_token?" +
39 | "appid=" + config.WECHAT_APPID +
40 | "&secret=" + config.WECHAT_SECRET +
41 | "&code=" + code +
42 | "&grant_type=authorization_code"
43 | content, status := global.HttpGet(url)
44 | if status >= 0 {
45 | log.Println(content)
46 | dec := json.NewDecoder(strings.NewReader(content))
47 | var v WebAccessToken
48 | for {
49 | if err := dec.Decode(&v); err == io.EOF {
50 | break
51 | } else if err != nil {
52 | log.Fatal(err)
53 | }
54 | }
55 | return &v
56 | }
57 | return nil
58 | }
59 |
60 | // 获取用户信息
61 | func (this *WebAccessToken) GetUserInfo() *WebUserInfo {
62 | url := "https://api.weixin.qq.com/sns/userinfo?access_token=" + this.Access_token +
63 | "&openid=" + this.Openid + "&lang=zh_CN"
64 | content, status := global.HttpGet(url)
65 | if status >= 0 {
66 | log.Println(content)
67 | dec := json.NewDecoder(strings.NewReader(content))
68 | var v WebUserInfo
69 | for {
70 | if err := dec.Decode(&v); err == io.EOF {
71 | break
72 | } else if err != nil {
73 | log.Fatal(err)
74 | }
75 | }
76 | return &v
77 | }
78 | return nil
79 | }
80 |
81 | func (this *WebUserInfo) Insert() error {
82 | o := orm.NewOrm()
83 |
84 | id, err := o.Insert(this)
85 | if err == nil {
86 | this.Id = id
87 | }
88 | return err
89 | }
90 |
91 | // 刷新网页端 AccessToken
92 | func (this *WebAccessToken) RefreshAccessToken() {
93 | url := "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + config.WECHAT_APPID +
94 | "&grant_type=refresh_token&refresh_token=" + this.Refresh_token
95 | content, status := global.HttpGet(url)
96 | if status >= 0 {
97 | log.Println(content)
98 | dec := json.NewDecoder(strings.NewReader(content))
99 | var v WebAccessToken
100 | for {
101 | if err := dec.Decode(&v); err == io.EOF {
102 | break
103 | } else if err != nil {
104 | log.Fatal(err)
105 | }
106 | }
107 | this = &v
108 | }
109 | }
110 |
111 | /// https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
112 |
--------------------------------------------------------------------------------
/wechat/jsapi/js_api.go:
--------------------------------------------------------------------------------
1 | /*
2 | * 文件描述: 微信JS-SDK的相关服务
3 | * 创建日期: 2015/3/18
4 | * 作者: ckeyer
5 | * 功能: 微信SDK初始化
6 | **/
7 | package jsapi
8 |
9 | import (
10 | "encoding/json"
11 | "fmt"
12 | // "github.com/astaxie/beego"
13 | "github.com/ckeyer/beewechat/conf"
14 | "github.com/ckeyer/beewechat/models/global"
15 | "github.com/hoisie/redis"
16 | logpkg "log"
17 | "os"
18 | "time"
19 | )
20 |
21 | var (
22 | redcli redis.Client
23 | log *logpkg.Logger
24 | config *conf.CkConfig
25 | )
26 |
27 | const (
28 | // redis 中 微信 jsapi_ticket的 key
29 | REDIS_KEY_WC_JSAPI_TICKET = "wx_JsapiTicket"
30 | // redis中 微信JS-sdk的 NONCESTR key 一个随机字符串
31 | REDIS_KEY_WC_JSAPI_NONCESTR = "wx_jsapiNoncestr"
32 | // redis中 微信JS-sdk的 timestamp key 一个随机字符串
33 | REDIS_KEY_WC_JSAPI_TIME_STAMP = "wx_jsapiTimestamp"
34 | )
35 |
36 | // 用于解析腾讯服务器发来的 JS_SDK ticket信息的结构体
37 | type JsapiTicket struct {
38 | Errcode int `json:"errcode"`
39 | Errmsg string `json:"errmsg"`
40 | Ticket string `json:"ticket"`
41 | ExpiresIn int64 `json:"expires_in"`
42 | }
43 |
44 | func init() {
45 | config = conf.NewConfig()
46 | redcli.Addr = config.REDIS_ADDR
47 | log = log.New(os.Stdout, "CKEYER - ", log.LstdFlags)
48 | }
49 |
50 | // 获取jsasp_ticket 字符串/
51 | func GetJsApiTicket() string {
52 | ts := getJsApiTicketFromLocal()
53 | if ts != "" {
54 | return ts
55 | } else {
56 | ots, err := getJsapiTicketFromServer()
57 | if err != nil {
58 | log.Println("jsapi - " + err.Error())
59 | return ""
60 | } else {
61 | ots.saveToRedis()
62 | return ots.Ticket
63 | }
64 | }
65 | }
66 |
67 | // 从本地redis中获取 jsasp_ticket 字符串
68 | func getJsApiTicketFromLocal() (ts string) {
69 |
70 | bs, err := redcli.Get(REDIS_KEY_WC_JSAPI_TICKET)
71 | if err != nil {
72 | return ""
73 | } else {
74 | ts = string(bs)
75 | }
76 | return
77 | }
78 |
79 | // 从腾讯服务器获取获取 jsapi_ticket 对象
80 | func getJsapiTicketFromServer() (jsapi_ticket *JsapiTicket, err error) {
81 | url := `https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=` + GetAccessToken() + `&type=jsapi`
82 | jsonBlob, status := global.HttpGetToBytes(url)
83 | // log.Println(string(jsonBlob))
84 | if status > 0 {
85 | err = json.Unmarshal(jsonBlob, &jsapi_ticket)
86 | if err != nil {
87 | log.Println(err)
88 | } else {
89 | // log.Println(jsapi_ticket.Ticket)
90 | return
91 | }
92 | }
93 | return
94 | }
95 |
96 | // 将 jsapi_ticket 存储到redis中
97 | func (this *JsapiTicket) saveToRedis() {
98 |
99 | err := redcli.Setex(REDIS_KEY_WC_JSAPI_TICKET, this.ExpiresIn, []byte(this.Ticket))
100 | if err != nil {
101 | log.Println(err.Error())
102 | } else {
103 | log.Println("Successful: get JS-SDK Ticket from server")
104 | }
105 | }
106 |
107 | // 获取 jsapi的noncestr 随机字符串
108 | // 如果redis中存在, 则直接取出, 如果不存在, 则随机产生, 并保存到redis中, 过期时间7200秒
109 | func GetJsApiNoncestr() string {
110 | bs, err := redcli.Get(REDIS_KEY_WC_JSAPI_NONCESTR)
111 | if err != nil {
112 | noncestr := global.GetRandString(16)
113 | err = redcli.Setex(REDIS_KEY_WC_JSAPI_NONCESTR, 7200, []byte(noncestr))
114 | if err != nil {
115 | log.Println("jsapi_noncestr-" + err.Error())
116 | }
117 | return noncestr
118 | }
119 | return string(bs)
120 | }
121 |
122 | // 获取 jsapi的timestamp 随机字符串
123 | // 如果redis中存在, 则直接取出, 如果不存在, 则随机产生, 并保存到redis中, 过期时间7200秒
124 | func GetJsApiTimeStamp() string {
125 | bs, err := redcli.Get(REDIS_KEY_WC_JSAPI_TIME_STAMP)
126 | if err != nil {
127 | timestamp := fmt.Sprint(time.Now().Unix())
128 | err = redcli.Setex(REDIS_KEY_WC_JSAPI_TIME_STAMP, 7200, []byte(timestamp))
129 | if err != nil {
130 | log.Println("jsapi_noncestr-" + err.Error())
131 | }
132 | return timestamp
133 | }
134 | return fmt.Sprintf("%s", bs)
135 | }
136 |
137 | // 得到用于JS_SDK的signature
138 | func GetJsApiSignature(url string) string {
139 | ticket := GetJsApiTicket()
140 | timestamp := GetJsApiTimeStamp()
141 | nonce := GetJsApiNoncestr()
142 | tmpStr := `jsapi_ticket=` + ticket +
143 | `&noncestr=` + nonce +
144 | `×tamp=` + timestamp +
145 | `&url=` + url
146 | return global.GetSHA1(tmpStr)
147 | }
148 |
--------------------------------------------------------------------------------
/wechat/wx_user.go:
--------------------------------------------------------------------------------
1 | package wechat
2 |
3 | import (
4 | "database/sql"
5 | "encoding/json"
6 | "fmt"
7 | "github.com/astaxie/beego"
8 | "github.com/ckeyer/beewechat/models/global"
9 | "github.com/hoisie/redis"
10 | "io"
11 | "log"
12 | // "errors"
13 | "strings"
14 | )
15 |
16 | type WXOpenIDList struct {
17 | Openid []string `json:openid`
18 | }
19 | type WXUserList struct {
20 | Total int `json:total`
21 | Count int `json:count`
22 | Data WXOpenIDList `json:data`
23 | Next_openid string `json:next_openid`
24 | }
25 | type WXUserInfo struct {
26 | Id int64 `json:"-"`
27 | Subscribe int `json:"subscribe"` // 用户是否订阅该公众号标识
28 | Openid string `json:"openid"` // 用户的标识,对当前公众号唯一
29 | Nickname string `json:"nickname"` // 用户的昵称
30 | Sex int `json:"sex"` // 用户的性别,值为1时是男性,值为2时是女性
31 | City string `json:"city"` // 用户所在城市
32 | Country string `json:"country"` // 用户所在国家
33 | Province string `json:"province"` // 用户所在省份
34 | Language string `json:"language"` // 用户的语言,简体中文为zh_CN
35 | Headimgurl string `json:"headimgurl"` // 用户头像
36 | Subscribe_time int64 `json:"subscribe_time"` // 用户关注时间,为时间戳
37 | Unionid int `json:"unionid"` // 只有在用户将公众号绑定到微信开放平台帐号后,才会出现该字段。
38 | }
39 |
40 | /// 获取用户列表并报错到redis数据库中 KEY=wx_UserList
41 | func GetUserList() {
42 | url := "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + GetAccessToken()
43 | key := "wx_UserList"
44 | var v WXUserList
45 | c, status := global.HttpGet(url)
46 | if status >= 0 {
47 | dec := json.NewDecoder(strings.NewReader(c))
48 | for {
49 | if err := dec.Decode(&v); err == io.EOF {
50 | break
51 | } else if err != nil {
52 | log.Fatal(err)
53 | }
54 | }
55 |
56 | var redcli redis.Client
57 | redcli.Addr = beego.AppConfig.String("redis_addr")
58 |
59 | if ok, err := redcli.Exists(key); err != nil {
60 | log.Println(err.Error())
61 | } else {
62 | if ok {
63 | redcli.Del(key)
64 | }
65 | }
66 | for _, value := range v.Data.Openid {
67 | redcli.Rpush(key, []byte(value))
68 | }
69 | log.Println("Successful: Add Userlist ")
70 | }
71 | }
72 |
73 | /// 获取用户基本信息,并保存到mysql 表tb_wx_user_info 中
74 | func GetUserInfo(openid string) (this *WXUserInfo) {
75 | url := "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + GetAccessToken() + "&openid=" + openid + "&lang=zh_CN"
76 | c, status := global.HttpGet(url)
77 | this = &WXUserInfo{}
78 | if status >= 0 {
79 | dec := json.NewDecoder(strings.NewReader(c))
80 | for {
81 | if err := dec.Decode(this); err == io.EOF {
82 | break
83 | } else if err != nil {
84 | log.Println(err)
85 | }
86 | }
87 | }
88 | this.saveUserInfo()
89 | return
90 | }
91 |
92 | /// 保存用户信息到数据库
93 | func (this *WXUserInfo) saveUserInfo() bool {
94 | db, err := connectDB()
95 | defer db.Close()
96 | if err != nil {
97 | return false
98 | } else {
99 | sql := "insert into tb_wx_user_info ( subscribe, openid, nickname, sex, " +
100 | "city, country, province, language, headimgurl, subscribe_time, unionid)" +
101 | " values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
102 | _, e := db.Exec(sql, this.Subscribe, this.Openid, this.Nickname, this.Sex, this.City,
103 | this.Country, this.Province, this.Language, this.Headimgurl,
104 | this.Subscribe_time, this.Unionid)
105 | if e != nil {
106 | sql := "update tb_wx_user_info set subscribe=? , nickname=?, " +
107 | "sex=?, city=?, country=?, province=?, language=?, headimgurl=?, " +
108 | "subscribe_time=?, unionid=? where openid=? "
109 | r, e2 := db.Exec(sql, this.Subscribe, this.Nickname, this.Sex, this.City,
110 | this.Country, this.Province, this.Language, this.Headimgurl,
111 | this.Subscribe_time, this.Unionid, this.Openid)
112 | if e2 != nil {
113 | log.Println(e2)
114 | return false
115 | } else {
116 | log.Println(r.LastInsertId())
117 | // log.Println(r.RowsAffected())
118 | }
119 | } else {
120 | // log.Println(r.LastInsertId())
121 | // log.Println(r.RowsAffected())
122 |
123 | }
124 | }
125 | return true
126 | }
127 |
128 | // 链接mysql数据库
129 | func connectDB() (db *sql.DB, err error) {
130 | connStr := beego.AppConfig.String("wx_mysql_connstr")
131 | db, err = sql.Open("mysql", connStr)
132 | if err != nil {
133 | log.Fatal("database initialize error : ", err.Error())
134 | // db = db
135 | }
136 | return
137 | }
138 |
139 | /// 获取用户信息列表
140 | func GetUserListInfo() {
141 | var redcli redis.Client
142 | redcli.Addr = beego.AppConfig.String("redis_addr")
143 | key := "wx_UserList"
144 | b, _ := redcli.Lrange(key, 0, -1)
145 | for _, v := range b {
146 | GetUserInfo(fmt.Sprintf("%s", v))
147 | }
148 | }
149 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 2, June 1991
3 |
4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6 | Everyone is permitted to copy and distribute verbatim copies
7 | of this license document, but changing it is not allowed.
8 |
9 | Preamble
10 |
11 | The licenses for most software are designed to take away your
12 | freedom to share and change it. By contrast, the GNU General Public
13 | License is intended to guarantee your freedom to share and change free
14 | software--to make sure the software is free for all its users. This
15 | General Public License applies to most of the Free Software
16 | Foundation's software and to any other program whose authors commit to
17 | using it. (Some other Free Software Foundation software is covered by
18 | the GNU Lesser General Public License instead.) You can apply it to
19 | your programs, too.
20 |
21 | When we speak of free software, we are referring to freedom, not
22 | price. Our General Public Licenses are designed to make sure that you
23 | have the freedom to distribute copies of free software (and charge for
24 | this service if you wish), that you receive source code or can get it
25 | if you want it, that you can change the software or use pieces of it
26 | in new free programs; and that you know you can do these things.
27 |
28 | To protect your rights, we need to make restrictions that forbid
29 | anyone to deny you these rights or to ask you to surrender the rights.
30 | These restrictions translate to certain responsibilities for you if you
31 | distribute copies of the software, or if you modify it.
32 |
33 | For example, if you distribute copies of such a program, whether
34 | gratis or for a fee, you must give the recipients all the rights that
35 | you have. You must make sure that they, too, receive or can get the
36 | source code. And you must show them these terms so they know their
37 | rights.
38 |
39 | We protect your rights with two steps: (1) copyright the software, and
40 | (2) offer you this license which gives you legal permission to copy,
41 | distribute and/or modify the software.
42 |
43 | Also, for each author's protection and ours, we want to make certain
44 | that everyone understands that there is no warranty for this free
45 | software. If the software is modified by someone else and passed on, we
46 | want its recipients to know that what they have is not the original, so
47 | that any problems introduced by others will not reflect on the original
48 | authors' reputations.
49 |
50 | Finally, any free program is threatened constantly by software
51 | patents. We wish to avoid the danger that redistributors of a free
52 | program will individually obtain patent licenses, in effect making the
53 | program proprietary. To prevent this, we have made it clear that any
54 | patent must be licensed for everyone's free use or not licensed at all.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | GNU GENERAL PUBLIC LICENSE
60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61 |
62 | 0. This License applies to any program or other work which contains
63 | a notice placed by the copyright holder saying it may be distributed
64 | under the terms of this General Public License. The "Program", below,
65 | refers to any such program or work, and a "work based on the Program"
66 | means either the Program or any derivative work under copyright law:
67 | that is to say, a work containing the Program or a portion of it,
68 | either verbatim or with modifications and/or translated into another
69 | language. (Hereinafter, translation is included without limitation in
70 | the term "modification".) Each licensee is addressed as "you".
71 |
72 | Activities other than copying, distribution and modification are not
73 | covered by this License; they are outside its scope. The act of
74 | running the Program is not restricted, and the output from the Program
75 | is covered only if its contents constitute a work based on the
76 | Program (independent of having been made by running the Program).
77 | Whether that is true depends on what the Program does.
78 |
79 | 1. You may copy and distribute verbatim copies of the Program's
80 | source code as you receive it, in any medium, provided that you
81 | conspicuously and appropriately publish on each copy an appropriate
82 | copyright notice and disclaimer of warranty; keep intact all the
83 | notices that refer to this License and to the absence of any warranty;
84 | and give any other recipients of the Program a copy of this License
85 | along with the Program.
86 |
87 | You may charge a fee for the physical act of transferring a copy, and
88 | you may at your option offer warranty protection in exchange for a fee.
89 |
90 | 2. You may modify your copy or copies of the Program or any portion
91 | of it, thus forming a work based on the Program, and copy and
92 | distribute such modifications or work under the terms of Section 1
93 | above, provided that you also meet all of these conditions:
94 |
95 | a) You must cause the modified files to carry prominent notices
96 | stating that you changed the files and the date of any change.
97 |
98 | b) You must cause any work that you distribute or publish, that in
99 | whole or in part contains or is derived from the Program or any
100 | part thereof, to be licensed as a whole at no charge to all third
101 | parties under the terms of this License.
102 |
103 | c) If the modified program normally reads commands interactively
104 | when run, you must cause it, when started running for such
105 | interactive use in the most ordinary way, to print or display an
106 | announcement including an appropriate copyright notice and a
107 | notice that there is no warranty (or else, saying that you provide
108 | a warranty) and that users may redistribute the program under
109 | these conditions, and telling the user how to view a copy of this
110 | License. (Exception: if the Program itself is interactive but
111 | does not normally print such an announcement, your work based on
112 | the Program is not required to print an announcement.)
113 |
114 | These requirements apply to the modified work as a whole. If
115 | identifiable sections of that work are not derived from the Program,
116 | and can be reasonably considered independent and separate works in
117 | themselves, then this License, and its terms, do not apply to those
118 | sections when you distribute them as separate works. But when you
119 | distribute the same sections as part of a whole which is a work based
120 | on the Program, the distribution of the whole must be on the terms of
121 | this License, whose permissions for other licensees extend to the
122 | entire whole, and thus to each and every part regardless of who wrote it.
123 |
124 | Thus, it is not the intent of this section to claim rights or contest
125 | your rights to work written entirely by you; rather, the intent is to
126 | exercise the right to control the distribution of derivative or
127 | collective works based on the Program.
128 |
129 | In addition, mere aggregation of another work not based on the Program
130 | with the Program (or with a work based on the Program) on a volume of
131 | a storage or distribution medium does not bring the other work under
132 | the scope of this License.
133 |
134 | 3. You may copy and distribute the Program (or a work based on it,
135 | under Section 2) in object code or executable form under the terms of
136 | Sections 1 and 2 above provided that you also do one of the following:
137 |
138 | a) Accompany it with the complete corresponding machine-readable
139 | source code, which must be distributed under the terms of Sections
140 | 1 and 2 above on a medium customarily used for software interchange; or,
141 |
142 | b) Accompany it with a written offer, valid for at least three
143 | years, to give any third party, for a charge no more than your
144 | cost of physically performing source distribution, a complete
145 | machine-readable copy of the corresponding source code, to be
146 | distributed under the terms of Sections 1 and 2 above on a medium
147 | customarily used for software interchange; or,
148 |
149 | c) Accompany it with the information you received as to the offer
150 | to distribute corresponding source code. (This alternative is
151 | allowed only for noncommercial distribution and only if you
152 | received the program in object code or executable form with such
153 | an offer, in accord with Subsection b above.)
154 |
155 | The source code for a work means the preferred form of the work for
156 | making modifications to it. For an executable work, complete source
157 | code means all the source code for all modules it contains, plus any
158 | associated interface definition files, plus the scripts used to
159 | control compilation and installation of the executable. However, as a
160 | special exception, the source code distributed need not include
161 | anything that is normally distributed (in either source or binary
162 | form) with the major components (compiler, kernel, and so on) of the
163 | operating system on which the executable runs, unless that component
164 | itself accompanies the executable.
165 |
166 | If distribution of executable or object code is made by offering
167 | access to copy from a designated place, then offering equivalent
168 | access to copy the source code from the same place counts as
169 | distribution of the source code, even though third parties are not
170 | compelled to copy the source along with the object code.
171 |
172 | 4. You may not copy, modify, sublicense, or distribute the Program
173 | except as expressly provided under this License. Any attempt
174 | otherwise to copy, modify, sublicense or distribute the Program is
175 | void, and will automatically terminate your rights under this License.
176 | However, parties who have received copies, or rights, from you under
177 | this License will not have their licenses terminated so long as such
178 | parties remain in full compliance.
179 |
180 | 5. You are not required to accept this License, since you have not
181 | signed it. However, nothing else grants you permission to modify or
182 | distribute the Program or its derivative works. These actions are
183 | prohibited by law if you do not accept this License. Therefore, by
184 | modifying or distributing the Program (or any work based on the
185 | Program), you indicate your acceptance of this License to do so, and
186 | all its terms and conditions for copying, distributing or modifying
187 | the Program or works based on it.
188 |
189 | 6. Each time you redistribute the Program (or any work based on the
190 | Program), the recipient automatically receives a license from the
191 | original licensor to copy, distribute or modify the Program subject to
192 | these terms and conditions. You may not impose any further
193 | restrictions on the recipients' exercise of the rights granted herein.
194 | You are not responsible for enforcing compliance by third parties to
195 | this License.
196 |
197 | 7. If, as a consequence of a court judgment or allegation of patent
198 | infringement or for any other reason (not limited to patent issues),
199 | conditions are imposed on you (whether by court order, agreement or
200 | otherwise) that contradict the conditions of this License, they do not
201 | excuse you from the conditions of this License. If you cannot
202 | distribute so as to satisfy simultaneously your obligations under this
203 | License and any other pertinent obligations, then as a consequence you
204 | may not distribute the Program at all. For example, if a patent
205 | license would not permit royalty-free redistribution of the Program by
206 | all those who receive copies directly or indirectly through you, then
207 | the only way you could satisfy both it and this License would be to
208 | refrain entirely from distribution of the Program.
209 |
210 | If any portion of this section is held invalid or unenforceable under
211 | any particular circumstance, the balance of the section is intended to
212 | apply and the section as a whole is intended to apply in other
213 | circumstances.
214 |
215 | It is not the purpose of this section to induce you to infringe any
216 | patents or other property right claims or to contest validity of any
217 | such claims; this section has the sole purpose of protecting the
218 | integrity of the free software distribution system, which is
219 | implemented by public license practices. Many people have made
220 | generous contributions to the wide range of software distributed
221 | through that system in reliance on consistent application of that
222 | system; it is up to the author/donor to decide if he or she is willing
223 | to distribute software through any other system and a licensee cannot
224 | impose that choice.
225 |
226 | This section is intended to make thoroughly clear what is believed to
227 | be a consequence of the rest of this License.
228 |
229 | 8. If the distribution and/or use of the Program is restricted in
230 | certain countries either by patents or by copyrighted interfaces, the
231 | original copyright holder who places the Program under this License
232 | may add an explicit geographical distribution limitation excluding
233 | those countries, so that distribution is permitted only in or among
234 | countries not thus excluded. In such case, this License incorporates
235 | the limitation as if written in the body of this License.
236 |
237 | 9. The Free Software Foundation may publish revised and/or new versions
238 | of the General Public License from time to time. Such new versions will
239 | be similar in spirit to the present version, but may differ in detail to
240 | address new problems or concerns.
241 |
242 | Each version is given a distinguishing version number. If the Program
243 | specifies a version number of this License which applies to it and "any
244 | later version", you have the option of following the terms and conditions
245 | either of that version or of any later version published by the Free
246 | Software Foundation. If the Program does not specify a version number of
247 | this License, you may choose any version ever published by the Free Software
248 | Foundation.
249 |
250 | 10. If you wish to incorporate parts of the Program into other free
251 | programs whose distribution conditions are different, write to the author
252 | to ask for permission. For software which is copyrighted by the Free
253 | Software Foundation, write to the Free Software Foundation; we sometimes
254 | make exceptions for this. Our decision will be guided by the two goals
255 | of preserving the free status of all derivatives of our free software and
256 | of promoting the sharing and reuse of software generally.
257 |
258 | NO WARRANTY
259 |
260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268 | REPAIR OR CORRECTION.
269 |
270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278 | POSSIBILITY OF SUCH DAMAGES.
279 |
280 | END OF TERMS AND CONDITIONS
281 |
282 | How to Apply These Terms to Your New Programs
283 |
284 | If you develop a new program, and you want it to be of the greatest
285 | possible use to the public, the best way to achieve this is to make it
286 | free software which everyone can redistribute and change under these terms.
287 |
288 | To do so, attach the following notices to the program. It is safest
289 | to attach them to the start of each source file to most effectively
290 | convey the exclusion of warranty; and each file should have at least
291 | the "copyright" line and a pointer to where the full notice is found.
292 |
293 | {description}
294 | Copyright (C) {year} {fullname}
295 |
296 | This program is free software; you can redistribute it and/or modify
297 | it under the terms of the GNU General Public License as published by
298 | the Free Software Foundation; either version 2 of the License, or
299 | (at your option) any later version.
300 |
301 | This program is distributed in the hope that it will be useful,
302 | but WITHOUT ANY WARRANTY; without even the implied warranty of
303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304 | GNU General Public License for more details.
305 |
306 | You should have received a copy of the GNU General Public License along
307 | with this program; if not, write to the Free Software Foundation, Inc.,
308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
309 |
310 | Also add information on how to contact you by electronic and paper mail.
311 |
312 | If the program is interactive, make it output a short notice like this
313 | when it starts in an interactive mode:
314 |
315 | Gnomovision version 69, Copyright (C) year name of author
316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
317 | This is free software, and you are welcome to redistribute it
318 | under certain conditions; type `show c' for details.
319 |
320 | The hypothetical commands `show w' and `show c' should show the appropriate
321 | parts of the General Public License. Of course, the commands you use may
322 | be called something other than `show w' and `show c'; they could even be
323 | mouse-clicks or menu items--whatever suits your program.
324 |
325 | You should also get your employer (if you work as a programmer) or your
326 | school, if any, to sign a "copyright disclaimer" for the program, if
327 | necessary. Here is a sample; alter the names:
328 |
329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program
330 | `Gnomovision' (which makes passes at compilers) written by James Hacker.
331 |
332 | {signature of Ty Coon}, 1 April 1989
333 | Ty Coon, President of Vice
334 |
335 | This General Public License does not permit incorporating your program into
336 | proprietary programs. If your program is a subroutine library, you may
337 | consider it more useful to permit linking proprietary applications with the
338 | library. If this is what you want to do, use the GNU Lesser General
339 | Public License instead of this License.
340 |
341 |
--------------------------------------------------------------------------------