nodejs推送微信消息

使用 Node.js 推送微信消息的几种方法

以下是几种使用 Node.js 向微信推送消息的方法,包括微信公众号模板消息、企业微信应用消息和微信小程序消息推送。

方法一:通过微信公众号模板消息推送(需服务号)

const axios = require('axios');
const crypto = require('crypto');

// 配置信息
const config = {
  appId: '你的微信公众号appId',
  appSecret: '你的微信公众号appSecret',
  templateId: '模板消息ID',
  openId: '接收用户的openid'
};

// 获取access_token
async function getAccessToken() {
  const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${config.appId}&secret=${config.appSecret}`;
  const response = await axios.get(url);
  return response.data.access_token;
}

// 发送模板消息
async function sendTemplateMessage() {
  try {
    const accessToken = await getAccessToken();
    const url = `https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=${accessToken}`;
    
    const data = {
      touser: config.openId,
      template_id: config.templateId,
      url: 'https://example.com', // 可选,点击跳转链接
      data: {
        first: {
          value: '您好,您有一条新消息',
          color: '#173177'
        },
        keyword1: {
          value: 'Node.js推送',
          color: '#173177'
        },
        keyword2: {
          value: new Date().toLocaleString(),
          color: '#173177'
        },
        remark: {
          value: '感谢您的使用!',
          color: '#173177'
        }
      }
    };

    const response = await axios.post(url, data);
    console.log('消息发送结果:', response.data);
  } catch (error) {
    console.error('发送消息失败:', error);
  }
}

sendTemplateMessage();

方法二:通过企业微信应用消息推送

const axios = require('axios');

// 企业微信配置
const qyWechatConfig = {
  corpId: '你的企业ID',
  corpSecret: '应用的Secret',
  agentId: '应用ID',
  toUser: '接收成员ID,多个用|分隔'
};

// 获取企业微信access_token
async function getQYAccessToken() {
  const url = `https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=${qyWechatConfig.corpId}&corpsecret=${qyWechatConfig.corpSecret}`;
  const response = await axios.get(url);
  return response.data.access_token;
}

// 发送企业微信应用消息
async function sendQYMessage() {
  try {
    const accessToken = await getQYAccessToken();
    const url = `https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=${accessToken}`;
    
    const data = {
      touser: qyWechatConfig.toUser,
      msgtype: 'text',
      agentid: qyWechatConfig.agentId,
      text: {
        content: '这是一条来自Node.js的企业微信消息\n时间:' + new Date().toLocaleString()
      },
      safe: 0
    };

    const response = await axios.post(url, data);
    console.log('企业微信消息发送结果:', response.data);
  } catch (error) {
    console.error('发送企业微信消息失败:', error);
  }
}

sendQYMessage();

方法三:通过Server酱等第三方服务推送(到微信)

const axios = require('axios');

// Server酱配置(Turbo版需要填写自己的SendKey)
const serverChanConfig = {
  sendKey: '你的SendKey',
  title: 'Node.js消息推送',
  desp: '这是一条通过Server酱从Node.js发送的微信消息\n\n' +
       '时间:' + new Date().toLocaleString() + '\n\n' +
       '[点击查看详情](https://example.com)'
};

// 通过Server酱发送微信消息
async function sendServerChanMessage() {
  try {
    const url = `https://sctapi.ftqq.com/${serverChanConfig.sendKey}.send`;
    const response = await axios.post(url, {
      title: serverChanConfig.title,
      desp: serverChanConfig.desp
    });
    console.log('Server酱消息发送结果:', response.data);
  } catch (error) {
    console.error('通过Server酱发送消息失败:', error);
  }
}

sendServerChanMessage();

方法四:通过微信小程序订阅消息推送

const axios = require('axios');

// 小程序配置
const miniProgramConfig = {
  appId: '小程序appId',
  appSecret: '小程序appSecret',
  templateId: '订阅消息模板ID',
  openId: '用户openid'
};

// 获取小程序access_token
async function getMiniProgramToken() {
  const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${miniProgramConfig.appId}&secret=${miniProgramConfig.appSecret}`;
  const response = await axios.get(url);
  return response.data.access_token;
}

// 发送小程序订阅消息
async function sendMiniProgramMessage() {
  try {
    const accessToken = await getMiniProgramToken();
    const url = `https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=${accessToken}`;
    
    const data = {
      touser: miniProgramConfig.openId,
      template_id: miniProgramConfig.templateId,
      page: 'pages/index/index', // 点击消息跳转的小程序页面
      data: {
        thing1: { value: 'Node.js推送测试' },
        time2: { value: new Date().toLocaleString() },
        thing3: { value: '这是一条测试消息' }
      }
    };

    const response = await axios.post(url, data);
    console.log('小程序订阅消息发送结果:', response.data);
  } catch (error) {
    console.error('发送小程序订阅消息失败:', error);
  }
}

sendMiniProgramMessage();

注意事项

  1. 微信公众号模板消息:需要服务号且用户已关注,模板消息需要事先申请

  2. 企业微信消息:需要企业微信账号和应用权限

  3. Server酱:免费版有发送限制,适合个人使用

  4. 小程序订阅消息:需要用户事先授权订阅

根据你的具体需求选择合适的推送方式,并确保已获取所有必要的API权限和密钥。

要使用 Node.js 实现微信推送功能,你可以使用微信公众平台提供的开发接口来实现。下面是一个基本的实现步骤: 1. 注册微信公众号:前往微信公众平台注册一个公众号,并获取到对应的 AppID 和 AppSecret。 2. 配置服务器地址:在微信公众平台中,配置服务器地址,将接收微信消息和事件的 URL 地址指向你的 Node.js 服务器。 3. 搭建 Node.js 服务器:使用 Express、Koa 或其他 Node.js 框架搭建一个服务器。 4. 实现消息处理逻辑:在服务器中编写处理微信消息和事件的逻辑,根据接收到的消息类型进行相应的处理,例如关注事件、文本消息等。 5. 验证服务器有效性:在服务器中实现微信服务器验证逻辑,验证服务器的有效性,确保可以接收微信发送的消息和事件。 6. 实现消息回复逻辑:根据接收到的消息类型,编写相应的回复逻辑,生成对应的 XML 格式的回复消息,并返回给微信服务器。 7. 调用微信接口:使用 Node.js 的 HTTP 请求库(如 axios、request)调用微信公众平台提供的接口,例如获取 access_token、发送模板消息等。 8. 启动服务器:运行你的 Node.js 服务器,确保服务器可以接收和处理来自微信服务器的请求。 这只是一个简单的示例,具体的实现方式和逻辑根据你的需求和业务场景可能会有所不同。请参考微信公众平台的开发文档和示例代码,以便更好地理解和使用 Node.js 实现微信推送功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值