MCPcopy Create free account
hub / github.com/027xiguapi/code-box / WechatSender

Class WechatSender

server/WechatSender.js:3–81  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1import fetch from "node-fetch"
2
3class WechatSender {
4 constructor() {
5 this.appid = process.env.WECHAT_APPID
6 this.secret = process.env.WECHAT_SECRET
7
8 if (!this.appid || !this.secret) {
9 const errorMessage =
10 "Error: WECHAT_APPID or WECHAT_SECRET is not set in the environment variables"
11 console.error(errorMessage)
12 throw new Error(errorMessage)
13 }
14 }
15
16 async getAccessToken() {
17 const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${this.appid}&secret=${this.secret}`
18 const response = await fetch(url)
19 const data = await response.json()
20 if (data.errcode) {
21 throw new Error(`Failed to get access token: ${data.errmsg}`)
22 }
23 return data.access_token
24 }
25
26 async addDraft(accessToken, event) {
27 const url = `https://api.weixin.qq.com/cgi-bin/draft/add?access_token=${accessToken}`
28 const response = await fetch(url, {
29 method: "POST",
30 body: JSON.stringify({
31 articles: [
32 {
33 title: event.title, // 标题
34 author: event.author, // 作者
35 digest: event.digest, // 图文消息的摘要,仅有单图文消息才有摘要,多图文此处为空。如果本字段为没有填写,则默认抓取正文前54个字。
36 content: event.content, // 图文消息的具体内容,支持HTML标签,必须少于2万字符,小于1M,且此处会去除JS,涉及图片url必须来源 "上传图文消息内的图片获取URL"接口获取。外部图片url将被过滤。
37 content_source_url: event.content_source_url, //图文消息的原文地址,即点击“阅读原文”后的URL
38 thumb_media_id: event.thumb_media_id, // 图文消息的封面图片素材id(必须是永久MediaID)
39 need_open_comment: event.need_open_comment, // Uint32 是否打开评论,0不打开(默认),1打开
40 only_fans_can_comment: event.only_fans_can_comment, // Uint32 是否粉丝才可评论,0所有人可评论(默认),1粉丝才可评论
41 pic_crop_235_1: event.pic_crop_235_1, // 封面裁剪为2.35:1规格的坐标字段。
42 pic_crop_1_1: event.pic_crop_1_1 // 封面裁剪为1:1规格的坐标字段,裁剪原理同pic_crop_235_1,裁剪后的图片必须符合规格要求。
43 }
44 ]
45 })
46 })
47 const data = await response.json()
48 if (data.errcode) {
49 throw new Error(`Failed to add draft: ${data.errmsg}`)
50 }
51 return data.media_id
52 }
53
54 async publishArticle(accessToken, mediaId) {
55 const url = `https://api.weixin.qq.com/cgi-bin/freepublish/submit?access_token=${accessToken}`
56 const response = await fetch(url, {
57 method: "POST",
58 body: JSON.stringify({
59 media_id: mediaId
60 })

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected