Files
stock/wxgzh/wxgzh.go
2021-12-20 19:17:24 +08:00

111 lines
2.5 KiB
Go

/**
* @Author: jager
* @Email: lhj168os@gmail.com
* @File: wxgzh
* @Date: 2021/12/20 6:53 下午
* @package: wxgzh
* @Version: v1.0.0
*
* @Description:
*
*/
package wxgzh
import (
"fmt"
"github.com/jageros/hawox/errcode"
"github.com/jageros/hawox/httpc"
"stock/stock"
"time"
)
var (
appid = "wxba88e64e7342b027"
secret = "ab8130a7bf55b78992e3d17f59909e0a"
accessTokenUrl = fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", appid, secret)
sendUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s"
accessToken = ""
expiresIn int64
)
type Resp struct {
Errcode int `json:"errcode"`
Errmsg string `json:"errmsg"`
Msgid int `json:"msgid"`
}
type AccessToken struct {
AccessToken string `json:"access_token"`
ExpiresIn int64 `json:"expires_in"`
Errcode int `json:"errcode"`
Errmsg string `json:"errmsg"`
}
type RData struct {
ToUserName string `xml:"ToUserName"`
FromUserName string `xml:"FromUserName"`
CreateTime int `xml:"CreateTime"`
MsgType string `xml:"MsgType"`
Content string `xml:"Content"`
MsgID int64 `xml:"MsgId"`
}
type xml struct {
ToUserName string `xml:"ToUserName"`
FromUserName string `xml:"FromUserName"`
CreateTime int `xml:"CreateTime"`
MsgType string `xml:"MsgType"`
Content string `xml:"Content"`
}
func getAccessToken(update bool) (string, error) {
if !update && time.Now().Unix() < expiresIn {
return accessToken, nil
}
resp := &AccessToken{}
err := httpc.RequestWithInterface(httpc.GET, accessTokenUrl, httpc.FORM, nil, nil, resp)
if err != nil {
return "", err
}
if resp.Errcode != 0 {
return "", errcode.New(int32(resp.Errcode), resp.Errmsg)
}
accessToken = resp.AccessToken
expiresIn = time.Now().Unix() + resp.ExpiresIn
return resp.AccessToken, nil
}
func send(openID string, stk stock.IArg, recall bool) error {
token, err := getAccessToken(false)
if err != nil {
return err
}
url := fmt.Sprintf(sendUrl, token)
arg := stk.Arg(openID)
resp := &Resp{}
err = httpc.RequestWithInterface(httpc.POST, url, httpc.JSON, arg, nil, resp)
if err != nil {
return err
}
if resp.Errcode != 0 {
if resp.Errcode == 40014 {
_, err = getAccessToken(true)
if err != nil {
return err
}
if recall {
return send(openID, stk, false)
}
}
return errcode.New(int32(resp.Errcode), resp.Errmsg)
}
return nil
}
func Send(openId string, stk stock.IArg) error {
return send(openId, stk, true)
}