-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
mp.js
77 lines (64 loc) · 2.31 KB
/
mp.js
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
const axios = require('axios')
const fs = require('fs')
const path = require('path')
const FormData = require('form-data')
module.exports.getAccessToken = async () => {
return axios.post('https://api.weixin.qq.com/cgi-bin/stable_token', {
grant_type: 'client_credential',
appid: '1234',
secret: '5678',
force_refresh: false
})
}
module.exports.addTempImage = async (access_token) => {
if (!access_token) {
const token = await module.exports.getAccessToken();
access_token = token.data.access_token;
}
const formData = new FormData();
formData.append('media', fs.createReadStream(path.join(__dirname, './test.png')));
console.log('uploading with token ', access_token);
return axios.post(
`https://api.weixin.qq.com/cgi-bin/media/upload?access_token=${access_token}&type=image`,
formData,
{
headers: {
...formData.getHeaders()
}
}
)
}
module.exports.addPersistedImage = async (access_token) => {
if (!access_token) {
const token = await module.exports.getAccessToken();
access_token = token.data.access_token;
}
const formData = new FormData();
formData.append('media', fs.createReadStream(path.join(__dirname, './test.png')));
console.log('uploading persisted image with token ', access_token);
return axios.post(
`https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=${access_token}&type=image`,
formData,
{
headers: {
...formData.getHeaders()
}
}
)
}
module.exports.addDraft = async ({ title, content, content_source_url }) => {
const token = await module.exports.getAccessToken();
const mediaRes = await module.exports.addPersistedImage(token.data.access_token);
console.log('mediaRes= ', mediaRes.data.media_id);
return axios.post(`https://api.weixin.qq.com/cgi-bin/draft/add?access_token=${token.data.access_token}`, {
articles: [
{
title,
content,
content_source_url,
need_open_comment: 1,
thumb_media_id: mediaRes.data.media_id
}
]
});
}