package client import ( "fmt" "hudongzhuanjia/controllers" "hudongzhuanjia/libs/wx" "hudongzhuanjia/utils" "hudongzhuanjia/utils/define" "time" ) type WxCtl struct { controllers.BaseCtl } const SignUrl = "jsapi_ticket=%s&noncestr=%s×tamp=%d&url=%s" type TicketCache struct { Url string `json:"url"` Token string `json:"token"` TokenExpired int64 `json:"ticket_expired"` Ticket string `json:"ticket"` TicketExpired int64 `json:"ticket_expired"` } var cache TicketCache // 检测token是否过期 // 检测ticket是否过期 func (t *WxCtl) Ticket() { url := t.MustGet("url") nonceStr := utils.RandomStr(32) timestamp := time.Now().Unix() if cache.TokenExpired <= time.Now().Unix() { token, err := wx.GetTicketToken() t.CheckErr(err) if token.ErrCode != 0 { t.ERROR(token.ErrMsg, token.ErrCode) } cache.Token = token.AccessToken cache.TokenExpired = token.ExpiresIn + 7200 } if cache.TicketExpired <= time.Now().Unix() { ticket, err := wx.GetTicket(cache.Token) t.CheckErr(err) if ticket.ErrCode != 0 { t.ERROR(ticket.ErrMsg, ticket.ErrCode) } cache.TicketExpired = ticket.ExpiresIn + 7200 cache.Ticket = ticket.Ticket } query := fmt.Sprintf(SignUrl, cache.Ticket, nonceStr, timestamp, url) signature := utils.Sha1(query) t.JSON(map[string]interface{}{ "signature": signature, "noncestr": nonceStr, "timestamp": timestamp, "ticket": cache.Ticket, "appid": define.AppId, }) }