微信-公众号/订阅号推送消息(js版本)

1.登录或注册微信测试号

(测试号的名称由官方自动生成,不能更改)

微信测试号入口:微信公众平台

2.登录进去后会看到自己的appId和appsecret

(这两个参数都需填入代码中)

3.检查是否安装nodeJs,使用node -v可检查是否安装;

node -v

没有就去官网下载进行安装

Node.js — Run JavaScript Everywhere

4.扫码关注测试二维码

(微信号需要拿到,后期填入代码中)

6.编辑测试号需要发送的信息模版,得到一个模版ID

(模板ID后期需放在代码中)

今天是:{{date.DATA}} 
土味情话:{{QingHua.DATA}} 
距离生日还有:{{Birthday.DATA}} 天 
今天是我们在一起第:{{jiNianDay.DATA}} 天 
【网易云时间】:{{wangyiyun.DATA}}

6.直接copy代码,然后将上面的4个参数填进去

(代码提供了单条发送和多条发送的,按需切换)

// 需要填写的地方已经标出
// 一共4个地方 appID、appsecret、模板ID、微信用户的openid
const axios = require("axios");
const moment = require("moment");
let openId = ""; // 关注者ID
let params = {}; // 装参用的

// 设置跨域请求头
axios.defaults.headers.post["Content-Type"] = "application/json; charset=utf-8";

// 定义post请求方法
const axiosPost = function (url, params) {
  return new Promise((resolve, reject) => {
    axios
      .post(url, params)
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        reject(err);
      });
  });
};

// 定义get请求方法
const axiosGet = function (url, params) {
  return new Promise((resolve, reject) => {
    axios
      .get(url, {
        params,
      })
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        reject(err);
      });
  });
};

//  定义获取token方法
async function getToken() {
  const params = {
    grant_type: "client_credential",
    appid: "", // 你的appid  1
    secret: "", // 你的secret 2
  };
  let res = await axiosGet("https://api.weixin.qq.com/cgi-bin/token", params);
  return res.data.access_token;
}

// 1、随机一句土味情话
async function getQingHua() {
  let res = await axiosGet("https://api.uomg.com/api/rand.qinghua?format=json");
  return res.data.content;
}

// 2、舔狗日记
// async function getTianGou() {
//     let res = await axiosGet('http://api.weijieyue.cn/api/tgrj/api.php')
//     return res.data;
// }

// 3、网易云热评
async function getWangYiYun() {
  let res = await axiosGet("https://keai.icu/apiwyy/api");
  return res.data;
}

// 天气 暂时不可用
// async function getWeather() {
//     let res = await axiosGet('https://api.vvhan.com/api/weather?city=长沙');
//     console.log(res,'4')
//     return res.data.info;
// }

// 4、计算还有多少天过生日(公历)
function getDaysToBirthday(month, day) {
  let now = new Date();
  let thisYear = now.getFullYear();
  //今年的生日
  let birthday = new Date(thisYear, month - 1, day);
  if (birthday < now) {
    birthday.setFullYear(now.getFullYear() + 1);
  }
  let timeDec = birthday - now;
  let days = timeDec / (24 * 60 * 60 * 1000);
  return Math.ceil(days);
}
// 5、纪念日
function getJiNianDays(time) {
  let startTime = new Date(time).getTime(); // 开始时间
  let nowTime = new Date().getTime(); // 今天
  let duration = -moment(startTime).diff(nowTime) / (1000 * 3600 * 24); // 时间戳转化为天数
  return Math.ceil(duration); // 取整数
}
// 6、当前时间
function getDays() {
  let date = new Date();
  // 获取时间:时分秒
  const hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
  const minute =
    date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
  const secound =
    date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
  // this.datetime = hour + ':' + minute + ':' + secound

  // 获取日期:年月日
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  // this.nowDate = month + "月" + day + "日"
  // this.nowYear = year + "年"

  // 获取星期几
  const weeks = new Array(
    "星期日",
    "星期一",
    "星期二",
    "星期三",
    "星期四",
    "星期五",
    "星期六"
  );
  // weeks[new Date().getDay()];
  return (
    year +
    "年" +
    month +
    "月" +
    day +
    "日 " +
    hour +
    ":" +
    minute +
    ":" +
    secound +
    " " +
    weeks[new Date().getDay()]
  );
}

async function getParams() {
  const token = await getToken();
  const QingHua = await getQingHua();
  // const tiangou = await getTianGou();
  const wangyyun = await getWangYiYun();
  const birthday = getDaysToBirthday(7, 28); // 填入生日(公历)
  const nowTime = getDays();
  const jiNianDay = getJiNianDays("2020-08-25"); // 按照格式填入 年-月-日

  params = {
    // touser: '', // 用户openid 3 就是扫码关注的那个微信号
    template_id: "", // 模板id 4 就是那个测试模板的ID
    // url: 'http://www.baidu.com',
    topcolor: "#FF0000",
    data: {
      date: {
        value: nowTime,
        color: "#FCA60B",
      },
      QingHua: {
        value: QingHua,
        color: "#ff1a75",
      },
      Birthday: {
        value: birthday,
        color: "#1E90FF",
      },
      jiNianDay: {
        value: jiNianDay,
        color: "#3399cc",
      },
      qinghua: {
        value: QingHua,
        color: "#33FF33",
      },
      // tiangou: {
      //     "value": tiangou,
      //     "color": "#007f80"
      // },
      wangyiyun: {
        value: wangyyun.content + "-- by " + wangyyun.user,
        color: "#2B9D4A",
      },
    },
  };
  // console.log('------------------------------------------')
  // console.log('打印消息: ',QingHua, '--', tiangou, '--', wangyyun, '--', birthday, '---', jiNianDay)
  // console.log('------------------------------------------')

  if (token) {
    // 单个openid,直接发送
    openId = ''; // 用户openid 3 就是扫码关注的那个微信号
    templateMessageSend(openId, token);

    // 获取批量openId,批量发送
    // axiosGet(
    //   `https://api.weixin.qq.com/cgi-bin/user/get?access_token=${token}&next_openid=${openId}`
    // ).then((res) => {
    //   const opemIdArr = res.data.data.openid;
    //   opemIdArr.forEach((element) => {
    //     openId = element;
    //     templateMessageSend(openId, token);
    //     // return openId;
    //   });
    // });
  }
}

// end定义发送消息模板
async function templateMessageSend(openId, token) {
  params = {
    ...params,
    touser: openId, // 用户openid 3 就是扫码关注的那个微信号
  };

  const url =
    "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" +
    token;

  let res = await axiosPost(url, params);
  console.log("res: ", res.data);
}
//  执行发送订阅消息
// templateMessageSend();

// 先装参再执行发送订阅消息
getParams();

7.运行;

npm install axios

npm install moment

node ./文件名

8.结果查看

如果有问题,多检查那4个参数;

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值