- change all request to NewRequest, don't use bare Request{}.
- MessageTemplateSend added. - refactor weixin api.
This commit is contained in:
@@ -2,7 +2,7 @@ package weixinapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"git.rosy.net.cn/baseapi"
|
||||
@@ -11,7 +11,11 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
prodURL = "https://api.weixin.qq.com"
|
||||
prodURL = "https://api.weixin.qq.com/cgi-bin"
|
||||
)
|
||||
|
||||
const (
|
||||
actionGetToken = "token"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -59,7 +63,6 @@ func (a *API) SetToken(newToken string) bool {
|
||||
a.token = newToken
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -69,29 +72,37 @@ func (a *API) GetToken() string {
|
||||
return a.token
|
||||
}
|
||||
|
||||
func (a *API) AccessAPI(action string, params map[string]interface{}) (retVal interface{}, err error) {
|
||||
if params == nil {
|
||||
panic("params is nil!")
|
||||
func (a *API) AccessAPI(action string, params map[string]interface{}, body string) (retVal map[string]interface{}, err error) {
|
||||
if params != nil && body != "" {
|
||||
panic("params and body can not all non-empty")
|
||||
}
|
||||
|
||||
params2 := make(map[string]interface{})
|
||||
for k, v := range params {
|
||||
params2[k] = v
|
||||
}
|
||||
params2["appid"] = a.appID
|
||||
params2["secret"] = a.secret
|
||||
fullURL, _ := url.Parse(utils.GenerateGetURL(prodURL, action, params2))
|
||||
// baseapi.SugarLogger.Debug(url.String())
|
||||
request := &http.Request{
|
||||
Method: "GET",
|
||||
URL: fullURL,
|
||||
if action == actionGetToken {
|
||||
params2["appid"] = a.appID
|
||||
params2["secret"] = a.secret
|
||||
} else {
|
||||
accessToken := a.GetToken()
|
||||
if accessToken == "" {
|
||||
panic("token is empty!")
|
||||
}
|
||||
params2["access_token"] = accessToken
|
||||
}
|
||||
fullURL := utils.GenerateGetURL(prodURL, action, params2)
|
||||
// baseapi.SugarLogger.Debug(fullURL)
|
||||
var request *http.Request
|
||||
if body == "" {
|
||||
request, _ = http.NewRequest(http.MethodGet, fullURL, nil)
|
||||
} else {
|
||||
request, _ = http.NewRequest(http.MethodPost, fullURL, strings.NewReader(body))
|
||||
}
|
||||
err = platformapi.AccessPlatformAPIWithRetry(a.client, request, a.config, func(response *http.Response) (result string, err error) {
|
||||
jsonResult1, err := utils.HTTPResponse2Json(response)
|
||||
if err != nil {
|
||||
return platformapi.ErrLevelGeneralFail, platformapi.ErrResponseDataFormatWrong
|
||||
}
|
||||
|
||||
var errInfo *ErrorInfo
|
||||
// 微信的返回值,在错误与正常情况下,结构是完全不一样的
|
||||
if errCode, ok := jsonResult1["errcode"]; ok {
|
||||
@@ -99,13 +110,12 @@ func (a *API) AccessAPI(action string, params map[string]interface{}) (retVal in
|
||||
ErrCode: int(utils.MustInterface2Int64(errCode)),
|
||||
ErrMsg: jsonResult1["errmsg"].(string),
|
||||
}
|
||||
} else {
|
||||
retVal = &TokenInfo{
|
||||
AccessToken: jsonResult1["access_token"].(string),
|
||||
ExpiresIn: int(utils.MustInterface2Int64(jsonResult1["expires_in"])),
|
||||
if errInfo.ErrCode == 0 {
|
||||
retVal = jsonResult1
|
||||
}
|
||||
} else {
|
||||
retVal = jsonResult1
|
||||
}
|
||||
|
||||
if retVal != nil {
|
||||
return platformapi.ErrLevelSuccess, nil
|
||||
}
|
||||
@@ -116,18 +126,33 @@ func (a *API) AccessAPI(action string, params map[string]interface{}) (retVal in
|
||||
}
|
||||
return platformapi.ErrLevelCodeIsNotOK, newErr
|
||||
})
|
||||
|
||||
return retVal, err
|
||||
}
|
||||
|
||||
func (a *API) RefreshToken() (tokenInfo *TokenInfo, err error) {
|
||||
result, err := a.AccessAPI("cgi-bin/token", utils.Params2Map("grant_type", "client_credential"))
|
||||
result, err := a.AccessAPI(actionGetToken, utils.Params2Map("grant_type", "client_credential"), "")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tokenInfo = result.(*TokenInfo)
|
||||
|
||||
tokenInfo = &TokenInfo{
|
||||
AccessToken: utils.Interface2String(result["access_token"]),
|
||||
ExpiresIn: int(utils.MustInterface2Int64(result["expires_in"])),
|
||||
}
|
||||
// update my token too.
|
||||
a.SetToken(tokenInfo.AccessToken)
|
||||
return tokenInfo, nil
|
||||
}
|
||||
|
||||
func (a *API) MessageTemplateSend(userOpneID, templateID, downloadURL string, miniProgram, data interface{}) (err error) {
|
||||
bodyJson := map[string]interface{}{
|
||||
"touser": userOpneID,
|
||||
"template_id": templateID,
|
||||
"url": downloadURL,
|
||||
"data": data,
|
||||
}
|
||||
if miniProgram != nil {
|
||||
bodyJson["miniprogram"] = miniProgram
|
||||
}
|
||||
_, err = a.AccessAPI("message/template/send", nil, string(utils.MustMarshal(bodyJson)))
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -33,8 +33,23 @@ func TestTest(t *testing.T) {
|
||||
|
||||
func TestRefreshToken(t *testing.T) {
|
||||
result, err := weixinapi.RefreshToken()
|
||||
if err != nil {
|
||||
if err != nil || result.ExpiresIn != 7200 {
|
||||
t.Fatal(err.Error())
|
||||
}
|
||||
sugarLogger.Debug(result)
|
||||
}
|
||||
|
||||
func TestMessageTemplateSend(t *testing.T) {
|
||||
weixinapi.SetToken("11_Gio44UhE5jgP_TNuAwrV9IjSX2QuVwKDyAsVYSWl94RXOJCjcxHcLjzJ81tr-e8cxithGxSlh3accjrdxoo8viWMG9MppZV6IftFPS8WNkFI8ToEbnhMz79UU-d84hLYbVLfecGavVN3HkIvZJYiAFAMWL")
|
||||
err := weixinapi.MessageTemplateSend("oYN_usvnObzrPweIgHTad9-uMf78", "_DtNGwmOeR6TkkTVUblxLIlkV2MAPOX57TkvfdqG6nY", "http://www.163.com", nil, map[string]interface{}{
|
||||
"first": "first",
|
||||
"Day": "Day",
|
||||
"orderId": "orderId",
|
||||
"orderType": "orderType",
|
||||
"customerName": "customerName",
|
||||
"customerPhone": "customerPhone",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user