银豹商品上传图片

This commit is contained in:
苏尹岚
2020-04-01 16:57:22 +08:00
parent 0ffbb59cce
commit 061801f96d
3 changed files with 109 additions and 4 deletions

View File

@@ -1,9 +1,13 @@
package yinbaoapi
import (
"bytes"
"encoding/json"
"fmt"
"math/rand"
"mime/multipart"
"net/http"
"net/textproto"
"regexp"
"strings"
@@ -13,9 +17,9 @@ import (
)
const (
pageUrl = "https://beta27.pospal.cn"
pageUrl = "https://beta27.pospal.cn"
MainStoreVendorOrgCode = "3933189"
letterBytes = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
)
var (
@@ -57,6 +61,71 @@ func (a *API) AccessStorePage(action string, bizParams map[string]interface{}) (
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) AccessStorePage2(action string, userID, productID string, data []byte, fileName string) (retVal map[string]interface{}, err error) {
// 实例化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"`,
"file", fileName))
h.Set("Content-Type", "image/jpeg")
part, _ := writer.CreatePart(h)
// part, _ := writer.CreateFormFile("file", "4ff17b24fdccfc37fd0847469a8039e9.jpg")
// 写入文件数据到multipart和读取本地文件方法的唯一区别
_, err = part.Write(data)
//将额外参数也写入到multipart
_ = writer.WriteField("name", fileName)
err = writer.Close()
fullURL := utils.GenerateGetURL(pageUrl, action, nil)
err = platformapi.AccessPlatformAPIWithRetry(a.client,
func() *http.Request {
request, _ := http.NewRequest(http.MethodPost, fullURL+"?userId="+userID+"&productId="+productID, body)
request.Header.Set("Content-Type", writer.FormDataContentType())
a.FillRequestCookies(request)
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")
}
if err == nil {
if jsonResult1["successed"] != nil {
if !jsonResult1["successed"].(bool) {
errLevel = platformapi.ErrLevelGeneralFail
err = utils.NewErrorCode(jsonResult1["msg"].(string), "-1", 0)
baseapi.SugarLogger.Debugf("yinbao AccessStorePageAPI failed, jsonResult1:%s", utils.Format4Output(jsonResult1, true))
}
} else {
errLevel = platformapi.ErrLevelGeneralFail
if strings.Contains(jsonResult1["fakeData"].(string), "登录") {
err = utils.NewErrorCode("银豹Cookie可能失效了", "-1", 0)
}
}
retVal = jsonResult1
}
return errLevel, err
})
return retVal, err
}
func IsErrCookie(err error) (isExist bool) {
return utils.IsErrMatch(err, "-1", []string{"银豹Cookie可能失效了"})
}
@@ -300,7 +369,7 @@ func (a *API) FindProduct(productId string) (findProductResult *FindProductResul
return findProductResult, err
}
//更新单个商品信息(称编码)
//更新单个商品信息(称编码和图片
//Request URL: https://beta27.pospal.cn/Product/SaveProduct
func (a *API) SaveProduct(userId, keyword string) (err error) {
productId, err := a.LoadProductsByPage(userId, keyword)
@@ -356,6 +425,13 @@ func (a *API) SaveProduct(userId, keyword string) (err error) {
return err
}
//上传图片
//https://beta27.pospal.cn/Product/UploadProductImage?userId=3933189&productId=8788044
func (a *API) UploadProductImage(userID, productId string, data []byte, fileName string) (err error) {
_, err = a.AccessStorePage2("Product/UploadProductImage", userID, productId, data, fileName)
return err
}
//登录?
//https://beta27.pospal.cn/account/SignIn?noLog=
//userName: 18048531223

View File

@@ -1,8 +1,13 @@
package yinbaoapi
import (
"crypto/md5"
"fmt"
"io/ioutil"
"net/http"
"testing"
"git.rosy.net.cn/baseapi/platformapi"
"git.rosy.net.cn/baseapi/utils"
)
@@ -84,3 +89,27 @@ func TestTryGetCookie(t *testing.T) {
}
t.Log(utils.Format4Output(result, false))
}
func TestUploadProductImage(t *testing.T) {
url := "http://image.jxc4.com/image/243ec2100060c15a1eb009fd2ee99450.jpg"
data, _, _ := DownloadFileByURL(url)
err := api.UploadProductImage(MainStoreVendorOrgCode, "8788044", data, "243ec2100060c15a1eb009fd2ee99450.jpg")
if err != nil {
t.Fatal(err)
}
}
func DownloadFileByURL(fileURL string) (bodyData []byte, fileMD5 string, err error) {
response, err := http.Get(fileURL)
if err == nil {
defer response.Body.Close()
if response.StatusCode == http.StatusOK {
if bodyData, err = ioutil.ReadAll(response.Body); err == nil {
fileMD5 = fmt.Sprintf("%X", md5.Sum(bodyData))
}
} else {
err = platformapi.ErrHTTPCodeIsNot200
}
}
return bodyData, fileMD5, err
}

View File

@@ -18,7 +18,7 @@ func init() {
sugarLogger = logger.Sugar()
baseapi.Init(sugarLogger)
api = New("682628966212343269", "18C0E0867E467DBC26EFF5E957B02EC4") //总店
api.SetCookie(".POSPALAUTH30220", "010214EB504F27D2D708FE145315B12FD2D708000833003900330033003100380039003A0000012F00FFAFFECF157DB55356D2DA4F6E2B3CDB5BCD9B47C2")
api.SetCookie(".POSPALAUTH30220", "010285F62D8F18D6D708FE855EF2F020D6D708000833003900330033003100380039003A0000012F00FF2492A4FB8757535AA993086F60564361E0F54C49")
}
func TestAddProductInfo(t *testing.T) {