key 来自:
一、发送消息
function sendText(key = '', text = '', mentioned = []) {
try {
axios({
method: 'post',
url: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key='+ key,
data: {
msgtype: 'text',
text: {
content: text,
mentioned_list: mentioned
}
}
})
} catch (error) {
console.log(error)
}
}
二、发送文件
要先上传到企业微信的服务器里,获得 id 后,再发送 id
上传文件
import FormData from 'form-data'
import fs from 'fs'
import axios from 'axios'
uploadFile = (key = '', filePath = '') => {
try {
const readStream = fs.createReadStream(filePath)
const formData = new FormData()
formData.append('media', readStream)
return axios
.post('https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?type=file&&key=' + key, formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then(({ data }) => {
return data.media_id || ''
})
} catch (error) {
console.log(error)
}
}
通过得到的 id,发送文件到企业微信:
sendFile = (key ='', id = '') => {
try {
axios({
method: 'post',
url: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=' + key,
data: {
msgtype: 'file',
file: {
media_id: id // 从 uploadFile 处获得
}
}
})
} catch (error) {
console.log(error)
}
}
和发送文本不同的是,里面的 data 不同