123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229 |
- package wechat
- import (
- "encoding/json"
- "fmt"
- "net/url"
- "time"
- "git.chuangxin1.com/cx/myth"
- "git.chuangxin1.com/cx/myth/cache"
- )
- func keyMini(appid string) string {
- return "wechat:mini:client:" + appid
- }
- func keyMiniToken(appid string) string {
- return "wechat:mini:client:token:" + appid
- }
- // NewMiniClient new mini client
- func NewMiniClient(appID, appSecret string) *MiniClient {
- key := keyMini(appID)
- if v, ok := memcache.Load(key); ok {
- return v.(*MiniClient)
- }
- c := &MiniClient{AppID: appID, AppSecret: appSecret, UseCacheToken: true}
- memcache.Store(key, c)
- return c
- }
- // TokenKey token key in cache
- func (mc *MiniClient) TokenKey() string {
- return keyMiniToken(mc.AppID)
- }
- // GetMiniOpenID get openid by code
- func (mc *MiniClient) GetMiniOpenID(frm FormCode) (s MiniSession, err error) {
- uri := BaseURL + "/sns/jscode2session?"
- args := url.Values{}
- args.Add("grant_type", "authorization_code")
- args.Add("appid", mc.AppID)
- args.Add("secret", mc.AppSecret)
- args.Add("js_code", frm.Code)
- uri += args.Encode()
- var jq *myth.JSONQuery
- if jq, err = getJSON(uri); err == nil {
- s.OpenID, err = jq.String(`openid`)
- s.SessionKey, _ = jq.String(`session_key`)
- s.UnionID, _ = jq.String(`unionid`)
- }
- return
- }
- // getToken get token
- func (mc *MiniClient) getToken() (token string, err error) {
- if mc.UseCacheToken {
- key := keyMiniToken(mc.AppID)
- var ct ClientToken
- s := ``
- //now := time.Now().Unix()
- s, err = cache.Get(key)
- if err != nil {
- return
- }
- err = json.Unmarshal([]byte(s), &ct)
- if err != nil {
- return
- }
- token = ct.AccessToken
- return
- }
- now := time.Now().Unix()
- if mc.LastTokenTime > 0 {
- if now-mc.LastTokenTime < TokenExpires {
- token = mc.AccessToken
- return
- }
- }
- token, err = mc.UpdateToken()
- return
- }
- func (mc *MiniClient) UpdateToken() (token string, err error) {
- now := time.Now().Unix()
- uri := BaseURL + "/cgi-bin/token?"
- args := url.Values{}
- args.Add("grant_type", "client_credential")
- args.Add("appid", mc.AppID)
- args.Add("secret", mc.AppSecret)
- uri += args.Encode()
- var jq *myth.JSONQuery
- jq, err = getJSON(uri)
- if err != nil {
- return
- }
- key := keyMiniToken(mc.AppID)
- mc.LastTokenTime = now
- mc.AccessToken, err = jq.String(`access_token`)
- token = mc.AccessToken
- k := keyMini(mc.AppID)
- memcache.Store(k, mc)
- ct := ClientToken{AppID: mc.AppID, AccessToken: mc.AccessToken, LastTokenTime: now}
- bs, _ := json.Marshal(ct)
- cache.Set(key, string(bs), 0)
- return
- }
- // TemplateList /cgi-bin/wxopen/template/list
- func (mc *MiniClient) TemplateList(offset, count int) (body []byte, err error) {
- uri := BaseURL + "/cgi-bin/wxopen/template/list?"
- if mc.AccessToken, err = mc.getToken(); err != nil {
- return
- }
- args := url.Values{}
- args.Add("access_token", mc.AccessToken)
- uri += args.Encode()
- params := make(map[string]interface{})
- params["offset"] = offset
- params["count"] = count
- var msg myth.HTTPMessage
- msg, err = postJSON(uri, params)
- if err == nil {
- body = msg.Body
- }
- /*
- data, err := json.Marshal(params)
- if err != nil {
- return
- }
- body, err = postJSONBody(uri, data)
- // */
- return
- }
- // MiniPhoneInfo 手机信息
- type MiniPhoneInfo struct {
- ResponseMsg
- PhoneInfo struct {
- PhoneNumber string `json:"phoneNumber"`
- PurePhoneNumber string `json:"purePhoneNumber"`
- CountryCode string `json:"countryCode"`
- Watermark struct {
- Timestamp int64 `json:"timestamp"`
- AppID string `json:"appid"`
- } `json:"watermark"`
- } `json:"phone_info"`
- }
- // GetPhoneInfo 获取手机信息 /wxa/business/getuserphonenumber
- func (mc *MiniClient) GetPhoneInfo(frm FormCode) (res MiniPhoneInfo, err error) {
- uri := BaseURL + "/wxa/business/getuserphonenumber?"
- if mc.AccessToken, err = mc.getToken(); err != nil {
- return
- }
- args := url.Values{}
- args.Add("access_token", mc.AccessToken)
- uri += args.Encode()
- var msg myth.HTTPMessage
- msg, err = postJSON(uri, frm)
- if err != nil {
- return
- }
- err = msg.JSON(&res)
- if err != nil {
- return
- }
- if res.ErrCode != 0 {
- err = fmt.Errorf("%s uri: %s", res.ErrMsg, uri)
- }
- return
- }
- // TemplateSend /cgi-bin/message/wxopen/template/send
- func (mc *MiniClient) TemplateSend(template MiniTemplateMessage) (jq *myth.JSONQuery, err error) {
- uri := BaseURL + "/cgi-bin/message/wxopen/template/send?"
- if mc.AccessToken, err = mc.getToken(); err != nil {
- return
- }
- args := url.Values{}
- args.Add("access_token", mc.AccessToken)
- uri += args.Encode()
- var msg myth.HTTPMessage
- msg, err = postJSON(uri, template)
- if err == nil {
- jq, err = msg.JSONQuery()
- }
- return
- }
- // UniformSend /cgi-bin/message/wxopen/template/uniform_send
- func (mc *MiniClient) UniformSend(template MiniUniformMessage) (jq *myth.JSONQuery, err error) {
- uri := BaseURL + "/cgi-bin/message/wxopen/template/uniform_send?"
- if mc.AccessToken, err = mc.getToken(); err != nil {
- return
- }
- args := url.Values{}
- args.Add("access_token", mc.AccessToken)
- uri += args.Encode()
- var msg myth.HTTPMessage
- msg, err = postJSON(uri, template)
- if err == nil {
- jq, err = msg.JSONQuery()
- }
- return
- }
|