Skip to content

Commit

Permalink
更新weixin公众号API
Browse files Browse the repository at this point in the history
  • Loading branch information
tiechui1994 committed Feb 25, 2023
1 parent 2b784ca commit 981ffbe
Show file tree
Hide file tree
Showing 4 changed files with 83 additions and 81 deletions.
15 changes: 10 additions & 5 deletions util/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"io/ioutil"
"net"
"net/http"
"strconv"
"strings"
"time"

Expand All @@ -24,7 +25,7 @@ func (err CodeError) Error() string {
if err.Message == "" {
return fmt.Sprintf("%v %q : status: %v", err.Method, err.URL,
http.StatusText(err.Code))
} else {
} else {
return fmt.Sprintf("%v %q : (status:%v, message:%v)", err.Method, err.URL,
http.StatusText(err.Code), err.Message)
}
Expand All @@ -39,11 +40,15 @@ func Request(method, u string, opts ...Option) (json.RawMessage, http.Header, er
try := 0
try:
request, _ := http.NewRequestWithContext(options.ctx, method, u, options.body)
request.Header.Set("user-agent", UserAgent())
for k, v := range options.header {
request.Header.Set(k, v)
}

request.Header.Set("user-agent", UserAgent())
val := request.Header.Get("Content-Length")
if val != "" {
request.ContentLength, _ = strconv.ParseInt(val, 10, 64)
}

response, err := client.Do(request)
if err != nil && try < options.retry {
Expand All @@ -69,7 +74,7 @@ try:
}

if response.StatusCode >= 400 {
return raw, response.Header, CodeError{method,u, response.StatusCode, string(raw)}
return raw, response.Header, CodeError{method, u, response.StatusCode, string(raw)}
}

return raw, response.Header, err
Expand Down Expand Up @@ -126,7 +131,7 @@ func SOCKET(u string, header map[string]string) (conn *websocket.Conn, raw json.
}

if response.StatusCode >= 400 {
return conn, raw, CodeError{http.MethodGet,u, response.StatusCode,""}
return conn, raw, CodeError{http.MethodGet, u, response.StatusCode, ""}
}

return conn, raw, nil
Expand Down Expand Up @@ -157,7 +162,7 @@ try:
}

if response.StatusCode != 200 {
return io, CodeError{method,u, response.StatusCode,""}
return io, CodeError{method, u, response.StatusCode, ""}
}

return response.Body, err
Expand Down
14 changes: 5 additions & 9 deletions weixin/upload.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,16 @@ import (
"fmt"
"io"
"io/fs"
"mime"
"path/filepath"
"strings"
)

func randomBoundary() string {
var buf [4]byte
var buf [8]byte
_, err := io.ReadFull(rand.Reader, buf[:])
if err != nil {
panic(err)
}
return hex.EncodeToString(buf[:])
return "------------------------" + hex.EncodeToString(buf[:])
}

var quoteEscaper = strings.NewReplacer("\\", "\\\\", `"`, "\\\"")
Expand Down Expand Up @@ -48,7 +46,7 @@ func uploadFile(fields map[string]interface{}) (reader io.Reader, contentType st
parts := make([]io.Reader, 0)
CRLF := "\r\n"

fieldBoundary := "------------------------" + boundary + CRLF
fieldBoundary := "--" + boundary + CRLF

for k, v := range fields {
parts = append(parts, strings.NewReader(fieldBoundary))
Expand All @@ -69,11 +67,9 @@ func uploadFile(fields map[string]interface{}) (reader io.Reader, contentType st
continue
case fs.File:
stat, _ := val.Stat()
contentType := mime.TypeByExtension(filepath.Ext(stat.Name()))
header := strings.Join([]string{
fmt.Sprintf(`Content-Disposition: form-data; name="%s"; filename="%s"`, escapeQuotes(k), escapeQuotes(stat.Name())),
fmt.Sprintf(`Content-Type: %s`, contentType),
fmt.Sprintf(`Content-Length: %d`, stat.Size()),
fmt.Sprintf(`Content-Type: %s`, "application/octet-stream"),
}, CRLF)
parts = append(
parts,
Expand All @@ -86,7 +82,7 @@ func uploadFile(fields map[string]interface{}) (reader io.Reader, contentType st
}
}

finishBoundary := "------------------------" + boundary + "------------------------" + CRLF
finishBoundary := "--" + boundary + "--" + CRLF
parts = append(parts, strings.NewReader(finishBoundary))
totalSize += len(finishBoundary)

Expand Down
77 changes: 31 additions & 46 deletions weixin/weixin.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
package weixin

import (
"bytes"
"encoding/json"
"fmt"
"io"
"mime/multipart"
"os"
"strings"

Expand All @@ -18,6 +15,7 @@ const (
MediaImage = "image"
MediaVideo = "video"
MediaVoice = "voice"
MediaThumb = "thumb"
MediaNews = "news"
)

Expand Down Expand Up @@ -65,7 +63,7 @@ func (e wxerror) isError() bool {
return e.Code != 0
}

func PersitMaterialList(token, mtype string, offset, count int) (list interface{}, err error) {
func PersistMaterialList(token, mtype string, offset, count int) (list interface{}, err error) {
value := []string{
"access_token=" + token,
}
Expand Down Expand Up @@ -122,8 +120,8 @@ func PersitMaterialList(token, mtype string, offset, count int) (list interface{
}
}

func UploadNewsImage(token, filename string) (url string, err error) {
info, err := os.Stat(filename)
func UploadImage(token, filename string) (url string, err error) {
fd, err := os.Open(filename)
if err != nil {
return url, err
}
Expand All @@ -132,26 +130,19 @@ func UploadNewsImage(token, filename string) (url string, err error) {
"access_token=" + token,
}
u := weixin + "/cgi-bin/media/uploadimg?" + strings.Join(value, "&")
var body bytes.Buffer
w := multipart.NewWriter(&body)
writer, err := w.CreateFormFile("media", info.Name())
if err != nil {
return url, err
}
reader, err := os.Open(filename)
if err != nil {
return url, err
}
_, err = io.Copy(writer, reader)

reader, contentType, contentLen, err := uploadFile(map[string]interface{}{
"media": fd,
})
if err != nil {
return url, err
}

w.Close()
header := map[string]string{
"content-type": w.FormDataContentType(),
"Content-Type": contentType,
"Content-Length": fmt.Sprintf("%v", contentLen),
}
raw, err := util.POST(u, util.WithBody(body), util.WithHeader(header))
raw, err := util.POST(u, util.WithBody(reader), util.WithHeader(header))
if err != nil {
return url, err
}
Expand All @@ -173,44 +164,38 @@ func UploadNewsImage(token, filename string) (url string, err error) {
return result.URL, nil
}

func AddPersitMaterial(token, mtype, filename string, args ...map[string]string) (url string, err error) {
info, err := os.Stat(filename)
func AddPersistMaterial(token, mtype, filename string, args ...map[string]string) (url, id string, err error) {
fd, err := os.Open(filename)
if err != nil {
return url, err
return url, id, err
}

value := []string{
"access_token=" + token,
"type=" + mtype,
}
u := weixin + "/cgi-bin/material/add_material?" + strings.Join(value, "&")
var body bytes.Buffer
w := multipart.NewWriter(&body)
writer, err := w.CreateFormFile("media", info.Name())
if err != nil {
return url, err
}
reader, err := os.Open(filename)
if err != nil {
return url, err
}
_, err = io.Copy(writer, reader)
if err != nil {
return url, err
}

fields := map[string]interface{}{
"media": fd,
}
if mtype == MediaVideo {
bin, _ := json.Marshal(args[0])
w.WriteField("description", string(bin))
fields["description"] = string(bin)
}

reader, contentType, contentLen, err := uploadFile(fields)
if err != nil {
return url, id, err
}

w.Close()
header := map[string]string{
"content-type": w.FormDataContentType(),
"Content-Type": contentType,
"Content-Length": fmt.Sprintf("%v", contentLen),
}
raw, err := util.POST(u, util.WithBody(body), util.WithHeader(header))
raw, err := util.POST(u, util.WithBody(reader), util.WithHeader(header))
if err != nil {
return url, err
return url, id, err
}

var result struct {
Expand All @@ -220,15 +205,15 @@ func AddPersitMaterial(token, mtype, filename string, args ...map[string]string)
}
err = json.Unmarshal(raw, &result)
if err != nil {
return url, err
return url, id, err
}

if result.isError() {
err = result.wxerror
return
}

return result.URL, nil
return result.URL, result.MediaID, nil
}

type TokenInfo struct {
Expand Down Expand Up @@ -326,13 +311,13 @@ func GetDraft(token, mediaid string) (artice []Article, err error) {
return result.NewsItem, nil
}

func UpdateDraft(token, mdediaid string, index int, article Article) (err error) {
func UpdateDraft(token, mediaid string, index int, article Article) (err error) {
value := []string{
"access_token=" + token,
}
u := weixin + "/cgi-bin/draft/update?" + strings.Join(value, "&")
body := map[string]interface{}{
"media_id": mdediaid,
"media_id": mediaid,
"index": index,
"articles": article,
}
Expand Down
58 changes: 37 additions & 21 deletions weixin/weixin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,39 +5,51 @@ import (
"testing"
)

var token = "65__urjOi5kgsVuLWxndRheHLtoWqT8UWo9dzBTxUFNMXpdX6L5mm-ok7MnyDQWulpl7m-eu4ACdRDOMooC5ZJw25Q58tzuvVCQayBh49rNdmC-AT_q9-o1X_I_tMJPZgACAYEO"
var token = "65_WN79odGQ3E-mjZfZaTKfyl"

func TestUploadNewsImage(t *testing.T) {
id, err := UploadNewsImage(token, "/home/quinn/Downloads/v.jpeg")
t.Log("id", id)
t.Log("err", err)
url, err := UploadImage(token, "/home/user/Downloads/flower.jpg")
if err != nil {
t.Fatalf("UploadImage: %v", err)
}
t.Log("url", url)
}

func TestAddPersitMaterial(t *testing.T) {
id, err := AddPersitMaterial(token, MediaImage, "/home/quinn/Downloads/vietnamese-woman.jpg")
func TestAddPersistMaterial(t *testing.T) {
url, id, err := AddPersistMaterial(token, MediaThumb, "/home/user/Downloads/superb.jpg")
if err != nil {
t.Fatalf("AddPersistMaterial: %v", err)
}
t.Log("url", url)
t.Log("id", id)
t.Log("err", err)
}

func TestMediaList(t *testing.T) {
list, err := PersitMaterialList(token, MediaImage, 0, 1)
t.Log("id", list)
t.Log("err", err)
func TestPersistMaterialList(t *testing.T) {
list, err := PersistMaterialList(token, MediaImage, 0, 10)
if err != nil {
t.Fatalf("PersistMaterialList: %v", err)
}

for _, v := range list.([]Media) {
t.Logf("name:%v, mediaid:%v, url:%v", v.Name, v.MediaID, v.Url)
}
}

// crAgK-cmXMbGEq9kZymbzf_ZnZjo4XV7HHYef7yF_ZI
// crAgK-cmXMbGEq9kZymbzTLmVnS0qOcgZ0WY9r-EMYlUBa-0hUzLV8CHUT3Nknbr
func TestAddDraft(t *testing.T) {
data, _ := ioutil.ReadFile("/home/quinn/Desktop/www.html")
data, _ := ioutil.ReadFile("/home/user/Desktop/xyz.html")
news := Article{
Title: "测试case",
Author: "tiechui1994",
ThumbMediaID: "crAgK-cmXMbGEq9kZymbzbQ2SZK08yL2dASCbsNrKRf3UH5s3yDc9ReYrv0IyNbd",
ThumbMediaID: "crAgK-cmXMbGEq9kZymbzTLmVnS0qOcgZ0WY9r-EMYlUBa-0hUzLV8CHUT3Nknbr",
ContentSourceUrl: "https://www.baidu.com",
Content: string(data),
Content: string(data),
}
id, err := AddDraft(token, news)
if err != nil {
t.Fatalf("AddDraft: %v", err)
}
t.Log("id", id)
t.Log("err", err)
}

func TestUpdateDraft(t *testing.T) {
Expand All @@ -47,14 +59,18 @@ func TestUpdateDraft(t *testing.T) {
Author: "tiechui1994",
ThumbMediaID: "crAgK-cmXMbGEq9kZymbzWP0k6ziJ5W_OayqgGzT2Go",
ContentSourceUrl: "https://www.baidu.com",
Content: string(data),
Content: string(data),
}
err := UpdateDraft(token, "crAgK-cmXMbGEq9kZymbzf_ZnZjo4XV7HHYef7yF_ZI", 0, news)
t.Log("err", err)
if err != nil {
t.Fatalf("UpdateDraft: %v", err)
}
}

func TestGetDraft(t *testing.T) {
news, err := GetDraft(token, "crAgK-cmXMbGEq9kZymbzfRNQraVlfgjkPuDLTrU2yY")
t.Log("news", news)
t.Log("err", err)
news, err := GetDraft(token, "crAgK-cmXMbGEq9kZymbzX38HXl7Wr8_f1Bifz9Tc5pOT5c_i2b8L-UJschJbmL0")
if err != nil {
t.Fatalf("GetDraft: %v", err)
}
t.Logf("url:%v", news[0].Url)
}

0 comments on commit 981ffbe

Please sign in to comment.