This commit is contained in:
suyl
2021-06-17 14:32:39 +08:00
parent 3ed374e74a
commit f746cd1023
13 changed files with 191 additions and 18 deletions

View File

@@ -1,8 +1,12 @@
package weixinapi
import (
"bytes"
"fmt"
"math/rand"
"mime/multipart"
"net/http"
"net/textproto"
"strings"
"sync"
@@ -17,6 +21,8 @@ const (
const (
ResponseCodeBusy = -1
ResponseCodeSuccess = 0
letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
)
type TokenInfo struct {
@@ -129,3 +135,78 @@ func (a *API) AccessAPI(action string, params map[string]interface{}, body strin
})
return retVal, err
}
func RandStringBytes(n int) string {
b := make([]byte, n)
for i := range b {
b[i] = letterBytes[rand.Intn(len(letterBytes))]
}
return string(b)
}
func getBoundary() (boundary string) {
boundary = "----WebKitFormBoundary"
boundary += RandStringBytes(16)
return boundary
}
func (a *API) AccessAPIUpload(data []byte, fileName, contentType string) (retVal map[string]interface{}, err error) {
params2 := make(map[string]interface{})
accessToken := a.CBGetToken()
if accessToken == "" {
panic("token is empty!")
}
params2["access_token"] = accessToken
fullURL := utils.GenerateGetURL(prodURL, "cgi-bin/media/uploadimg", params2)
// baseapi.SugarLogger.Debug(fullURL)
// 实例化multipart
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
writer.SetBoundary(getBoundary())
// 创建multipart 文件字段
h := make(textproto.MIMEHeader)
h.Set("Content-Disposition",
fmt.Sprintf(`form-data; name="%s"; filename="%s"`,
"media", fileName))
h.Set("Content-Type", contentType)
part, err := writer.CreatePart(h)
// 写入文件数据到multipart和读取本地文件方法的唯一区别
_, err = part.Write(data)
//将额外参数也写入到multipart
//_ = writer.WriteField("media", fileName)
err = writer.Close()
err = platformapi.AccessPlatformAPIWithRetry(a.client,
func() *http.Request {
request, _ := http.NewRequest(http.MethodPost, fullURL, body)
request.Header.Set("Content-Type", writer.FormDataContentType())
return request
},
a.config,
func(response *http.Response, bodyStr string, jsonResult1 map[string]interface{}) (errLevel string, err error) {
if jsonResult1 == nil {
return platformapi.ErrLevelRecoverableErr, fmt.Errorf("mapData is nil")
}
var errInfo *ErrorInfo
// 微信的返回值,在错误与正常情况下,结构是完全不一样的
if errCode, ok := jsonResult1["errcode"]; ok {
errInfo = &ErrorInfo{
ErrCode: int(utils.MustInterface2Int64(errCode)),
ErrMsg: jsonResult1["errmsg"].(string),
}
if errInfo.ErrCode == 0 {
retVal = jsonResult1
}
} else {
retVal = jsonResult1
}
if retVal != nil {
return platformapi.ErrLevelSuccess, nil
}
newErr := utils.NewErrorIntCode(errInfo.ErrMsg, errInfo.ErrCode)
if errInfo.ErrCode == ResponseCodeBusy {
return platformapi.ErrLevelRecoverableErr, newErr
}
return platformapi.ErrLevelCodeIsNotOK, newErr
})
return retVal, err
}