通过微信公众号给女朋友推送消息

先看下效果图
在这里插入图片描述

准备工作
1、首先去微信公众平台注册成为测试号,点这里
在这里插入图片描述

然后再添加一个模板
在这里插入图片描述

![在这里插入图片描述](https://img-blog.csdnimg.cn/875c3ac58c014834b33e268cf239eda2.png
模板里的json字符串示例如下

{{date.DATA}} {{remark.DATA}} 所在城市:{{city.DATA}} 今日天气:{{weather.DATA}} 气温变化:{{min_temperature.DATA}}~{{max_temperature.DATA}} 今日建议:{{tips.DATA}} 今天是我们恋爱的第{{love_days.DATA}}天 距离婷宝贝生日还有{{girl_birthday.DATA}}天 距离你家康先生生日还有{{boy_birthday.DATA}}{{rainbow.DATA}}

天气情话我调用的是天行数据管理系统的,他们有免费的额度,够用。
最后就再新建一个springboot项目就好了。

代码实现部分
微信配置代码

package cc.mrbird.febs.system.until;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class WeChatConfigure {

    public static String Access_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}";
    public static String Send_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={0}";

    public static String App_ID;
    @Value("${WeChat.AppID}")
    public void setAppID(String AppID) {
        App_ID = AppID;
    }

    public static String App_Secret;
    @Value("${WeChat.AppSecret}")
    public void setAppSecret(String AppSecret) {
        App_Secret = AppSecret;
    }

    public static String Open_ID;
    @Value("${WeChat.OpenID}")
    public void setOpenID(String OpenID) {
        Open_ID = OpenID;
    }

    public static String Template_ID;
    @Value("${WeChat.TemplateID}")
    public void setTemplateID(String TemplateID) {
        Template_ID = TemplateID;
    }

    public static String Top_Color;
    @Value("${WeChat.TopColor}")
    public void setTopColor(String TopColor) {
        Top_Color = TopColor;
    }

    public static String Weather_API;
    @Value("${WeChat.WeatherAPI}")
    public void setWeatherAPI(String WeatherAPI) {
        Weather_API = WeatherAPI;
    }

    public static String Rainbow_API;
    @Value("${WeChat.RainbowAPI}")
    public void setRainbowAPI(String RainbowAPI) {
        Rainbow_API = RainbowAPI;
    }

    public static String Boy_Birthday;
    @Value("${WeChat.BoyBirthday}")
    public void setBoyBirthday(String BoyBirthday) {
        Boy_Birthday = BoyBirthday;
    }

    public static String Girl_Birthday;
    @Value("${WeChat.GirlBirthday}")
    public void setGirlBirthday(String GirlBirthday) {
        Girl_Birthday = GirlBirthday;
    }

    public static String Love_Day;
    @Value("${WeChat.LoveDay}")
    public void setLoveDay(String LoveDay) {
        Love_Day = LoveDay;
    }
}

具体的值写在yml配置文件里的,示例如下

在这里插入图片描述

工具类

package cc.mrbird.febs.system.until;

import cc.mrbird.febs.system.domain.Weather;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.client.RestTemplate;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class DataUtils {

    /**
     * 获取 Weather 信息
     * @param restTemplate
     * @return
     */
    public static Weather getWeather(RestTemplate restTemplate){
        String responseJson = restTemplate.getForObject(WeChatConfigure.Weather_API, String.class);
        JSONObject responseResult = JSONObject.parseObject(responseJson);
        JSONObject jsonObject = responseResult.getJSONArray("newslist").getJSONObject(0);
        return jsonObject.toJavaObject(Weather.class);
    }

    /**
     * 获取 RainbowPi 信息
     * @param restTemplate
     * @return
     */
    public static String getRainbow(RestTemplate restTemplate){
        String responseJson = restTemplate.getForObject(WeChatConfigure.Rainbow_API, String.class);
        JSONObject responseResult = JSONObject.parseObject(responseJson);
        JSONObject jsonObject = responseResult.getJSONArray("newslist").getJSONObject(0);
        return jsonObject.getString("content");
    }
    /**
     * 计算生日天数 days
     * @return
     */
    public static int getBirthDays(String birthday) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cToday = Calendar.getInstance(); // 存今天
        Calendar cBirth = Calendar.getInstance(); // 存生日
        int days = 0;
        try {
            cBirth.setTime(dateFormat.parse(birthday)); // 设置生日
            cBirth.set(Calendar.YEAR, cToday.get(Calendar.YEAR)); // 修改为本年
            if (cBirth.get(Calendar.DAY_OF_YEAR) < cToday.get(Calendar.DAY_OF_YEAR)) {
                // 生日已经过了,要算明年的了
                days = (cToday.getActualMaximum(Calendar.DAY_OF_YEAR) - cToday.get(Calendar.DAY_OF_YEAR)) + cBirth.get(Calendar.DAY_OF_YEAR);
            } else {
                // 生日还没过
                days = cBirth.get(Calendar.DAY_OF_YEAR) - cToday.get(Calendar.DAY_OF_YEAR);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return days;
    }

    /**
     * 计算恋爱天数 days
     * @return
     */
    public static int getLoveDays(String loveday) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        int days = 0;
        try {
            long time = System.currentTimeMillis() - dateFormat.parse(loveday).getTime();
            days = (int) (time / (24 * 60 * 60 * 1000));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return days;
    }
    /**
     * 获取token,默认7200秒过期,所以存redis7200秒取一次
     * @return 获取用户详情
     */
    public static String getAccessToken(RestTemplate restTemplate) {
        String responseJson = restTemplate.getForObject("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxb23f8f7f1f2ed5a6&secret=5bf40a38641e5bc5e3d11ab4c1cadc4f", String.class);
        JSONObject responseResult = JSONObject.parseObject(responseJson);
        return responseResult.getString("access_token");
    }
}

具体的实现代码

package cc.mrbird.febs.system.controller;

import cc.mrbird.febs.system.domain.DataItem;
import cc.mrbird.febs.system.domain.ResultVo;
import cc.mrbird.febs.system.domain.Weather;
import cc.mrbird.febs.system.until.DataUtils;
import cc.mrbird.febs.system.until.WeChatConfigure;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
@Validated
@RestController
@RequestMapping("ztt")
public class ZttControlle {
    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder){
        return builder.build();
    }
   @Autowired
   private RestTemplate restTemplate;

    /**
     * {{date.DATA}}
     * {{remark.DATA}}
     * 所在城市:{{city.DATA}}
     * 今日天气:{{weather.DATA}}
     * 气温变化:{{min_temperature.DATA}} ~ {{max_temperature.DATA}}
     * 今日建议:{{tips.DATA}}
     * 今天是我们恋爱的第 {{love_days.DATA}} 天
     * 距离xx生日还有 {{girl_birthday.DATA}} 天
     * 距离xx生日还有 {{boy_birthday.DATA}} 天
     * {{rainbow.DATA}}
     */
    @Scheduled(cron = "0 0 8 * * ?")
    public void push(){
        ResultVo resultVo = ResultVo.initializeResultVo(WeChatConfigure.Open_ID,WeChatConfigure.Template_ID,WeChatConfigure.Top_Color);
        //1.设置城市与天气信息
        Weather weather = DataUtils.getWeather(restTemplate);
        resultVo.setAttribute("date",new DataItem(weather.getDate() + " " + weather.getWeek(),"#00BFFF"));
        resultVo.setAttribute("city",new DataItem(weather.getArea(),null));
        resultVo.setAttribute("weather",new DataItem(weather.getWeather(),"#1f95c5"));
        resultVo.setAttribute("min_temperature",new DataItem(weather.getLowest(),"#0ace3c"));
        resultVo.setAttribute("max_temperature",new DataItem(weather.getHighest(),"#dc1010"));
        resultVo.setAttribute("tips",new DataItem(weather.getTips(),null));
        //2.设置日期相关
        int love_days = DataUtils.getLoveDays(WeChatConfigure.Love_Day);
        int girl_birthday = DataUtils.getBirthDays(WeChatConfigure.Girl_Birthday);
        int boy_birthday = DataUtils.getBirthDays(WeChatConfigure.Boy_Birthday);
        resultVo.setAttribute("love_days",new DataItem(love_days+"","#FFA500"));
        resultVo.setAttribute("girl_birthday",new DataItem(girl_birthday+"","#FFA500"));
        resultVo.setAttribute("boy_birthday",new DataItem(boy_birthday+"","#FFA500"));
        //3.设置彩虹屁
        String rainbow =  DataUtils.getRainbow(restTemplate);
        resultVo.setAttribute("rainbow",new DataItem(rainbow,"#FF69B4"));
        //4.其他
        String remark = "❤";
        if(DataUtils.getBirthDays(WeChatConfigure.Love_Day) == 0){
            remark = "今天是恋爱周年纪念日!永远爱你~";
        }else if(girl_birthday == 0){
            remark = "今天是婷宝贝的生日!生日快乐哟~";
        }else if(boy_birthday == 0){
            remark = "今天是康先生的生日!别忘了好好爱他~";
        }
        resultVo.setAttribute("remark",new DataItem(remark,"#FF1493"));
        //5.发送请求,推送消息
        String responseStr = restTemplate.postForObject(WeChatConfigure.Send_URL, resultVo, String.class, DataUtils.getAccessToken(restTemplate));
        printPushLog(responseStr);
    }

    /**
     * 打印 response log
     * @param responseStr
     */
    private void printPushLog(String responseStr){
        JSONObject jsonObject = JSONObject.parseObject(responseStr);
        String msgCode = jsonObject.getString("errcode");
        String msgContent = jsonObject.getString("errmsg");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("[ " + dateFormat.format(new Date()) + " ] : messageCode=" + msgCode + ",messageContent=" + msgContent);
    }
}

还一个Weather的实体类,我就不贴出来了,你们可以参考着天行的接口写下就好。
如需源码可私聊我

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值