forked from silenceper/wechat
-
Notifications
You must be signed in to change notification settings - Fork 1
/
media.go
110 lines (95 loc) · 2.67 KB
/
media.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package material
import (
"encoding/json"
"fmt"
"github.com/blueswn/wechat/util"
)
//MediaType 媒体文件类型
type MediaType string
const (
//MediaTypeImage 媒体文件:图片
MediaTypeImage MediaType = "image"
//MediaTypeVoice 媒体文件:声音
MediaTypeVoice = "voice"
//MediaTypeVideo 媒体文件:视频
MediaTypeVideo = "video"
//MediaTypeThumb 媒体文件:缩略图
MediaTypeThumb = "thumb"
)
const (
mediaUploadURL = "https://api.weixin.qq.com/cgi-bin/media/upload"
mediaUploadImageURL = "https://api.weixin.qq.com/cgi-bin/media/uploadimg"
mediaGetURL = "https://api.weixin.qq.com/cgi-bin/media/get"
)
//Media 临时素材上传返回信息
type Media struct {
util.CommonError
Type MediaType `json:"type"`
MediaID string `json:"media_id"`
ThumbMediaID string `json:"thumb_media_id"`
CreatedAt int64 `json:"created_at"`
}
//MediaUpload 临时素材上传
func (material *Material) MediaUpload(mediaType MediaType, filename string) (media Media, err error) {
var accessToken string
accessToken, err = material.GetAccessToken()
if err != nil {
return
}
uri := fmt.Sprintf("%s?access_token=%s&type=%s", mediaUploadURL, accessToken, mediaType)
var response []byte
response, err = util.PostFile("media", filename, uri)
if err != nil {
return
}
err = json.Unmarshal(response, &media)
if err != nil {
return
}
if media.ErrCode != 0 {
err = fmt.Errorf("MediaUpload error : errcode=%v , errmsg=%v", media.ErrCode, media.ErrMsg)
return
}
return
}
//GetMediaURL 返回临时素材的下载地址供用户自己处理
//NOTICE: URL 不可公开,因为含access_token 需要立即另存文件
func (material *Material) GetMediaURL(mediaID string) (mediaURL string, err error) {
var accessToken string
accessToken, err = material.GetAccessToken()
if err != nil {
return
}
mediaURL = fmt.Sprintf("%s?access_token=%s&media_id=%s", mediaGetURL, accessToken, mediaID)
return
}
//resMediaImage 图片上传返回结果
type resMediaImage struct {
util.CommonError
URL string `json:"url"`
}
//ImageUpload 图片上传
func (material *Material) ImageUpload(filename string) (url string, err error) {
var accessToken string
accessToken, err = material.GetAccessToken()
if err != nil {
return
}
uri := fmt.Sprintf("%s?access_token=%s", mediaUploadImageURL, accessToken)
var response []byte
response, err = util.PostFile("media", filename, uri)
if err != nil {
return
}
var image resMediaImage
err = json.Unmarshal(response, &image)
if err != nil {
return
}
if image.ErrCode != 0 {
err = fmt.Errorf("UploadImage error : errcode=%v , errmsg=%v", image.ErrCode, image.ErrMsg)
return
}
url = image.URL
return
}