123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341 |
- package wechat
- import (
- "encoding/json"
- "errors"
- "fmt"
- "net/url"
- "time"
- "git.chuangxin1.com/cx/myth/cache"
- "git.chuangxin1.com/cx/myth"
- )
- func key(appid string) string {
- return "wechat:client:" + appid
- }
- func keyToken(appid string) string {
- return "wechat:client:token:" + appid
- }
- // NewClient new client
- func NewClient(appID, appSecret, token, encodingAESKey string) *Client {
- key := key(appID)
- if v, ok := memcache.Load(key); ok {
- return v.(*Client)
- }
- c := &Client{AppID: appID, AppSecret: appSecret, Token: token, EncodingAESKey: encodingAESKey}
- memcache.Store(key, c)
- return c
- }
- // getToken get token
- func (wc *Client) getToken() (token string, err error) {
- key := keyToken(wc.AppID)
- if wc.UseCacheToken {
- var ct ClientToken
- s := ``
- s, err = cache.Get(key)
- if err != nil {
- return
- }
- err = json.Unmarshal([]byte(s), &ct)
- if err != nil {
- return
- }
- token = ct.AccessToken
- return
- }
- //wc.ReadLock.Lock()
- //defer wc.ReadLock.Unlock()
- now := time.Now().Unix()
- if wc.LastTokenTime > 0 {
- if now-wc.LastTokenTime < TokenExpires {
- token = wc.AccessToken
- return
- }
- }
- uri := BaseURL + "/cgi-bin/token?"
- args := url.Values{}
- args.Add("grant_type", "client_credential")
- args.Add("appid", wc.AppID)
- args.Add("secret", wc.AppSecret)
- uri += args.Encode()
- var jq *myth.JSONQuery
- if jq, err = getJSON(uri); err == nil {
- wc.LastTokenTime = now
- var accessToken string
- accessToken, err = jq.String(`access_token`)
- wc.AccessToken = accessToken
- token = wc.AccessToken
- key1 := key(wc.AppID)
- memcache.Store(key1, wc)
- ct := ClientToken{AppID: wc.AppID, AccessToken: wc.AccessToken, LastTokenTime: now}
- bs, _ := json.Marshal(ct)
- cache.Set(key, string(bs), 0)
- //cache.Store(key, accessToken)
- }
- return
- }
- func (wc *Client) getTicket(now int64) (ticket string, err error) {
- var jq *myth.JSONQuery
- if wc.LastTicketTime > 0 {
- if now-wc.LastTicketTime < TicketExpires {
- ticket = wc.Ticket
- return
- }
- }
- args := url.Values{}
- args.Add("access_token", wc.AccessToken)
- args.Add("type", "jsapi")
- uri := BaseURL + "/cgi-bin/ticket/getticket?"
- uri += args.Encode()
- if jq, err = getJSON(uri); err == nil {
- ticket, err = jq.String(`ticket`)
- wc.LastTicketTime = now
- wc.Ticket = ticket
- key := key(wc.AppID)
- memcache.Store(key, wc)
- }
- return
- }
- // GetCodeURL get code 授权获取 OpenID URL
- // /connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
- // 转向到
- // redirect_uri/?code=CODE&state=STATE
- func (wc Client) GetCodeURL(redirectURL, state string) (uri string) {
- uri = OpenURL + "/connect/oauth2/authorize?"
- args := url.Values{}
- args.Add("appid", wc.AppID)
- args.Add("redirect_uri", redirectURL)
- args.Add("response_type", "code")
- args.Add("scope", "snsapi_base")
- args.Add("state", state)
- uri += args.Encode()
- uri += "#wechat_redirect"
- return
- }
- // GetOpenID 获取 OpenID
- // /sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
- func (wc Client) GetOpenID(code string) (jq *myth.JSONQuery, err error) {
- uri := BaseURL + "/sns/oauth2/access_token?"
- if wc.AccessToken, err = wc.getToken(); err != nil {
- return
- }
- args := url.Values{}
- args.Add("access_token", wc.AccessToken)
- args.Add("appid", wc.AppID)
- args.Add("secret", wc.AppSecret)
- args.Add("code", code)
- args.Add("grant_type", "authorization_code")
- uri += args.Encode()
- jq, err = getJSON(uri)
- return
- }
- // GetUserInfo user info
- func (wc Client) GetUserInfo(openid string) (info UserInfo, err error) {
- uri := BaseURL + "/cgi-bin/user/info?"
- if wc.AccessToken, err = wc.getToken(); err != nil {
- return
- }
- args := url.Values{}
- args.Add("access_token", wc.AccessToken)
- args.Add("openid", openid)
- args.Add("lang", "zh_CN")
- uri += args.Encode()
- var msg myth.HTTPMessage
- msg, err = getBody(uri)
- if err == nil {
- err = msg.JSON(&info)
- }
- return
- }
- // GetUserList user list
- func (wc Client) GetUserList(nextOpenID string) (list UserList, err error) {
- uri := BaseURL + "/cgi-bin/user/get?"
- if wc.AccessToken, err = wc.getToken(); err != nil {
- return
- }
- args := url.Values{}
- args.Add("access_token", wc.AccessToken)
- args.Add("next_openid", nextOpenID)
- uri += args.Encode()
- var msg myth.HTTPMessage
- msg, err = getBody(uri)
- if err == nil {
- err = msg.JSON(&list)
- }
- return
- }
- // GetMaterial 永久资料
- func (wc Client) GetMaterial(mtype string, offset, count int) (material Material, err error) {
- uri := BaseURL + "/cgi-bin/material/batchget_material?"
- if wc.AccessToken, err = wc.getToken(); err != nil {
- return
- }
- args := url.Values{}
- data := make(map[string]interface{})
- args.Add("access_token", wc.AccessToken)
- data["type"] = mtype
- data["offset"] = offset
- data["count"] = count
- uri += args.Encode()
- var msg myth.HTTPMessage
- msg, err = postJSON(uri, data)
- if err == nil {
- err = msg.JSON(&material)
- }
- return
- }
- // GetMenu 查询自定义菜单
- func (wc Client) GetMenu() (menu Menu, err error) {
- uri := BaseURL + "/cgi-bin/get_current_selfmenu_info?"
- if wc.AccessToken, err = wc.getToken(); err != nil {
- return
- }
- args := url.Values{}
- data := make(map[string]interface{})
- args.Add("access_token", wc.AccessToken)
- uri += args.Encode()
- var msg myth.HTTPMessage
- msg, err = postJSON(uri, data)
- if err == nil {
- err = msg.JSON(&menu)
- }
- return
- }
- // CreateMenu 创建自定义菜单
- func (wc Client) CreateMenu(menu FormMenu) (err error) {
- uri := BaseURL + "/cgi-bin/menu/create?"
- if wc.AccessToken, err = wc.getToken(); err != nil {
- return
- }
- args := url.Values{}
- args.Add("access_token", wc.AccessToken)
- uri += args.Encode()
- var msg myth.HTTPMessage
- msg, err = postJSON(uri, menu)
- if err != nil {
- return
- }
- jq, e := msg.JSONQuery()
- if e != nil {
- err = e
- return
- }
- code, _ := jq.Int(`errcode`)
- errmsg, _ := jq.String(`errmsg`)
- if code != ErrReqOk {
- err = errors.New(errmsg)
- }
- return
- }
- // GetSignPackage JS 签名
- // uri 当前 URL
- // nonceStr 随机字符串
- func (wc Client) GetSignPackage(uri, nonceStr string) (sign SignPackage, err error) {
- if wc.AccessToken, err = wc.getToken(); err != nil {
- return
- }
- var (
- s string
- unix int64
- )
- unix = time.Now().Unix()
- if wc.Ticket, err = wc.getTicket(unix); err != nil {
- return
- }
- s = `jsapi_ticket=` + wc.Ticket
- s += `&noncestr=` + nonceStr
- s += `×tamp=` + fmt.Sprintf("%d", unix)
- s += `&url=` + uri
- sign.AppID = wc.AppID
- sign.NonceStr = nonceStr
- sign.Signature = myth.SHA1(s)
- sign.Timestamp = unix
- sign.Ticket = wc.Ticket
- sign.URL = uri
- return
- }
- // SendTemplateMessage send template message
- // POST /cgi-bin/message/template/send?access_token=ACCESS_TOKEN
- func (wc Client) SendTemplateMessage(template TemplateMessage) (res TemplateResponse, err error) {
- uri := BaseURL + "/cgi-bin/message/template/send?"
- if wc.AccessToken, err = wc.getToken(); err != nil {
- return
- }
- args := url.Values{}
- args.Add("access_token", wc.AccessToken)
- uri += args.Encode()
- var msg myth.HTTPMessage
- msg, err = postJSON(uri, template)
- if err == nil {
- err = json.Unmarshal(msg.Body, &res)
- }
- return
- }
- // TemplateMessageReslut template message reslut
- func (wc Client) TemplateMessageReslut(jq *myth.JSONQuery) (code int, id int64, err error) {
- code, _ = jq.Int(`errcode`)
- errmsg, _ := jq.String(`errmsg`)
- id, _ = jq.Int64(`msgid`)
- if code != ErrReqOk {
- err = errors.New(errmsg)
- }
- return
- }
|