先在微信公众平台设置好模板和测试号:
地址:微信公众平台


下面是我的模板:
{{riqi.DATA}} {{beizhu.DATA}}
地区:{{districtName.DATA}}
天气:{{tianqi.DATA}}
风级:{{windclass.DATA}}
风向:{{winddir.DATA}}
最低气温: {{low.DATA}}度
最高气温: {{high.DATA}}度
今天是我们恋爱的第{{lianai.DATA}}天
距离{{you.DATA}}生日还有{{shengri1.DATA}}天
距离{{me.DATA}}生日还有{{shengri2.DATA}}天
{{lubarmonth.DATA}} {{lunarday.DATA}}
宜:{{fitness.DATA}}
不宜:{{taboo.DATA}}
星座指数:{{zhishu.DATA}}
{{content.DATA}}
{{caihongpi.DATA}}
{{qingshi.DATA}}
{{en.DATA}}
{{zh.DATA}}
然后我们来到项目代码部分,项目使用springboot框架,使用前先导入依赖:
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.7</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- https://mvnrepository.com/artifact/com.github.binarywang/weixin-java-mp -->
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-mp</artifactId>
<version>3.3.0</version>
</dependency>
1、天行数据接口,第三方接口用于接入彩虹屁、黄历、情诗等,
public class CaiHongPiUtils {
public static String getCaiHongPi(String key) {
String httpUrl = "http://api.tianapi.com/caihongpi/index?key="+key;
BufferedReader reader = null;
String result = null;
StringBuffer sbf = new StringBuffer();
try {
URL url = new URL(httpUrl);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setRequestMethod("GET");
InputStream is = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sbf.append(strRead);
sbf.append("\r\n");
}
reader.close();
result = sbf.toString();
} catch (Exception e) {
e.printStackTrace();
}
JSONObject jsonObject = JSONObject.parseObject(result);
JSONArray newslist = jsonObject.getJSONArray("newslist");
String content = newslist.getJSONObject(0).getString("content");
return content;
}
public static Map<String,String> getEveryday(String key) {
String httpUrl = "http://api.tianapi.com/everyday/index?key="+key;
BufferedReader reader = null;
String result = null;
StringBuffer sbf = new StringBuffer();
try {
URL url = new URL(httpUrl);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setRequestMethod("GET");
InputStream is = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sbf.append(strRead);
sbf.append("\r\n");
}
reader.close();
result = sbf.toString();
} catch (Exception e) {
e.printStackTrace();
}
JSONObject jsonObject = JSONObject.parseObject(result);
JSONArray newslist = jsonObject.getJSONArray("newslist");
String en = newslist.getJSONObject(0).getString("content");
String zh = newslist.getJSONObject(0).getString("note");
Map<String, String> map = new HashMap<>();
map.put("zh",zh);
map.put("en",en);
return map;
}
public static Map<String,String> getQingshi(String key) {
String httpUrl = "http://api.tianapi.com/qingshi/index?key="+key;
BufferedReader reader = null;
String result = null;
StringBuffer sbf = new StringBuffer();
try {
URL url = new URL(httpUrl);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setRequestMethod("GET");
InputStream is = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sbf.append(strRead);
sbf.append("\r\n");
}
reader.close();
result = sbf.toString();
} catch (Exception e) {
e.printStackTrace();
}
JSONObject jsonObject = JSONObject.parseObject(result);
JSONArray newslist = jsonObject.getJSONArray("newslist");
String content = newslist.getJSONObject(0).getString("content");
String source = newslist.getJSONObject(0).getString("source");
String author = newslist.getJSONObject(0).getString("author");
Map<String, String> map = new HashMap<>();
map.put("content",content);
map.put("source",source);
map.put("author",author);
return map;
}
public static Map<String,String> gethuangli(String key) {
SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
String httpUrl = "http://api.tianapi.com/lunar/index?key="+key+"&date="+myFormatter.format(new Date());
BufferedReader reader = null;
String result = null;
StringBuffer sbf = new StringBuffer();
try {
URL url = new URL(httpUrl);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setRequestMethod("GET");
InputStream is = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sbf.append(strRead);
sbf.append("\r\n");
}
reader.close();
result = sbf.toString();
} catch (Exception e) {
e.printStackTrace();
}
JSONObject jsonObject = JSONObject.parseObject(result);
JSONArray newslist = jsonObject.getJSONArray("newslist");
String lubarmonth = newslist.getJSONObject(0).getString("lubarmonth");
String lunarday = newslist.getJSONObject(0).getString("lunarday");
String fitness = newslist.getJSONObject(0).getString("fitness");
String taboo = newslist.getJSONObject(0).getString("taboo");
Map<String, String> map = new HashMap<>();
map.put("lubarmonth",lubarmonth);
map.put("lunarday",lunarday);
map.put("fitness",fitness);
map.put("taboo",taboo);
return map;
}
public static Map<String,String> getxingzuo(String key, String astro) {
String httpUrl = "http://api.tianapi.com/star/index?key="+key+"&astro="+astro;
BufferedReader reader = null;
String result = null;
StringBuffer sbf = new StringBuffer();
try {
URL url = new URL(httpUrl);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setRequestMethod("GET");
InputStream is = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sbf.append(strRead);
sbf.append("\r\n");
}
reader.close();
result = sbf.toString();
} catch (Exception e) {
e.printStackTrace();
}
JSONObject jsonObject = JSONObject.parseObject(result);
JSONArray newslist = jsonObject.getJSONArray("newslist");
String zhishu = newslist.getJSONObject(0).getString("content");
String content = newslist.getJSONObject(8).getString("content");
Map<String, String> map = new HashMap<>();
map.put("zhishu",zhishu);
map.put("content",content);
return map;
}
}
2、计算纪念日工具类,用来计算周年、生日、在一起多少天等等
public class JiNianRiUtils {
public static int getLianAi(String dateStr){
return calculationLianAi(dateStr);
}
public static int getLianAiYear(String dateStr){
return calculationLianAiYear(dateStr);
}
public static int getBirthday_me(String dateStr){
try {
return calculationBirthday(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
return 0;
}
public static int getBirthday_you(String dateStr){
try {
return calculationBirthday(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
return 0;
}
// 计算生日天数
public static int calculationBirthday(String clidate) throws ParseException {
SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
Calendar cToday = Calendar.getInstance(); // 存今天
Calendar cBirth = Calendar.getInstance(); // 存生日
cBirth.setTime(myFormatter.parse(clidate)); // 设置生日
cBirth.set(Calendar.YEAR, cToday.get(Calendar.YEAR)); // 修改为本年
int days;
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);
days += cBirth.get(Calendar.DAY_OF_YEAR);
} else {
// 生日还没过
days = cBirth.get(Calendar.DAY_OF_YEAR) - cToday.get(Calendar.DAY_OF_YEAR);
}
// 输出结果
if (days == 0) {
return 0;
} else {
return days;
}
}
// 计算天数
public static int calculationLianAi(String date) {
DateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
int day = 0;
try {
long time = System.currentTimeMillis() - simpleDateFormat.parse(date).getTime();
day = (int) (time / 86400000L);
} catch (ParseException e) {
e.printStackTrace();
}
return day;
}
// 计算恋爱周年
public static int calculationLianAiYear(String date) {
DateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
int year = 0;
try {
Calendar cToday = Calendar.getInstance();
Calendar cBirth = Calendar.getInstance();
cBirth.setTime(simpleDateFormat.parse(date));
if(cToday.get(Calendar.MONTH)==cBirth.get(Calendar.MONTH)&&cToday.get(Calendar.DAY_OF_MONTH)==cBirth.get(Calendar.DAY_OF_MONTH)) {
year = cToday.get(Calendar.YEAR) - cBirth.get(Calendar.YEAR);
}
} catch (ParseException e) {
e.printStackTrace();
}
return year;
}
// 区分周末和工作日,当天是否发送
public static Boolean calculationSend(String date) {
String[] strArr = date.split(":");
int hour = Integer.valueOf(strArr[0]);
int minute = Integer.valueOf(strArr[1]);
Calendar now = Calendar.getInstance();
Calendar tar = (Calendar) now.clone();
Calendar before = (Calendar) now.clone();
tar.set(Calendar.HOUR_OF_DAY, hour);
tar.set(Calendar.MINUTE, minute);
tar.set(Calendar.SECOND, 0);
tar.set(Calendar.MILLISECOND, 0);
before.add(Calendar.MINUTE, -30);
if(now.getTime().getTime()>=tar.getTime().getTime()&&tar.getTime().getTime()>before.getTime().getTime()) {
return true;
}
return false;
}
}
3、天气,使用的是百度天气第三方接口。
dto代码:
public class Weather {
String wd_night;
String date;
String high;
String week;
String text_night;
String wd_day;
String low;
String wc_night;
String text_day;
String wc_day;
// 当前天气
String text_now;
// 当前温度
String temp;
// 风级大小
String wind_class;
// 风向
String wind_dir;
}
天气接口工具类:
public class WeatherUtils {
public static Weather getWeather(String district_id, String ak){
RestTemplate restTemplate = new RestTemplate();
Map<String,String> map = new HashMap<String,String>();
map.put("district_id",district_id); // 地方行政代码
map.put("data_type","all");//这个是数据类型
map.put("ak",ak);
String res = restTemplate.getForObject(
"https://api.map.baidu.com/weather/v1/?district_id={district_id}&data_type={data_type}&ak={ak}",
String.class,
map);
JSONObject json = JSONObject.parseObject(res);
JSONArray forecasts = json.getJSONObject("result").getJSONArray("forecasts");
List<Weather> weathers = forecasts.toJavaList(Weather.class);
JSONObject now = json.getJSONObject("result").getJSONObject("now");
Weather weather = weathers.get(0);
weather.setText_now(now.getString("text"));
weather.setTemp(now.getString("temp"));
weather.setWind_class(now.getString("wind_class"));
weather.setWind_dir(now.getString("wind_dir"));
return weather;
}
}
然后用定时任务推送:
@Slf4j
@DisallowConcurrentExecution
@Component("WXWeatherJob")
public class WXWeatherJob{
@Resource
private WxpushService wxpushService;
@Scheduled(cron = "0,30 * * * * ?")
// @Scheduled(cron = "0 0,30 * * * ?")
@Transactional
public void executeWork(){
log.info("WXPushJob#######################start");
List<Wxpush> wxpushList = wxpushService.findAll();
Calendar cal = Calendar.getInstance();
if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
for (Wxpush wxpush : wxpushList) {
if(JiNianRiUtils.calculationSend(wxpush.getPushTimeWeek())) {
push(wxpush);
}
}
}else {
for (Wxpush wxpush : wxpushList) {
if(JiNianRiUtils.calculationSend(wxpush.getPushTimeWork())) {
push(wxpush);
}
}
}
log.info("WXPushJob#######################end");
}
public void push(Wxpush wxpush){
//1,配置
WxMpInMemoryConfigStorage wxStorage = new WxMpInMemoryConfigStorage();
wxStorage.setAppId(wxpush.getAppId());
wxStorage.setSecret(wxpush.getSecret());
WxMpService wxMpService = new WxMpServiceImpl();
wxMpService.setWxMpConfigStorage(wxStorage);
//2,推送消息
WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
.toUser(wxpush.getToUser())
.templateId(wxpush.getTemplateId())
.build();
//3,配置信息
Weather weather = WeatherUtils.getWeather(wxpush.getDistrictId(), wxpush.getAk());
Map<String, String> qingshiMap = CaiHongPiUtils.getQingshi(wxpush.getTianxingKey());
String caihongpiStr = CaiHongPiUtils.getCaiHongPi(wxpush.getTianxingKey());
if(caihongpiStr.contains("XXX")) {
caihongpiStr = caihongpiStr.replaceAll("XXX", wxpush.getNameYou());
}
Map<String, String> huangli = CaiHongPiUtils.gethuangli(wxpush.getTianxingKey());
Map<String, String> xingzuo = CaiHongPiUtils.getxingzuo(wxpush.getTianxingKey(),wxpush.getAstro());
Map<String, String> map = CaiHongPiUtils.getEveryday(wxpush.getTianxingKey());
templateMessage.addData(new WxMpTemplateData("riqi",weather.getDate() + " "+ weather.getWeek(),"#00BFFF"));
templateMessage.addData(new WxMpTemplateData("districtName",wxpush.getDistrictName() + "","#173177"));
templateMessage.addData(new WxMpTemplateData("tianqi",weather.getText_now(),"#42B857"));
templateMessage.addData(new WxMpTemplateData("low",weather.getLow() + "","#173177"));
templateMessage.addData(new WxMpTemplateData("temp",weather.getTemp() + "","#EE212D"));
templateMessage.addData(new WxMpTemplateData("high",weather.getHigh()+ "","#FF6347" ));
templateMessage.addData(new WxMpTemplateData("windclass",weather.getWind_class()+ "","#00FFFF" ));
templateMessage.addData(new WxMpTemplateData("winddir",weather.getWind_dir()+ "","#B95EA3" ));
templateMessage.addData(new WxMpTemplateData("caihongpi",caihongpiStr+ "","#FF69B4"));
templateMessage.addData(new WxMpTemplateData("qingshi",qingshiMap.get("content")+"--《"+qingshiMap.get("source")+"》"+ "","#B95EA3"));
templateMessage.addData(new WxMpTemplateData("lianai",JiNianRiUtils.getLianAi(wxpush.getDateLove())+"","#FF1493"));
templateMessage.addData(new WxMpTemplateData("shengri1",JiNianRiUtils.getBirthday_you(wxpush.getDateBirYou())+"","#FFA500"));
templateMessage.addData(new WxMpTemplateData("shengri2",JiNianRiUtils.getBirthday_me(wxpush.getDateBirMe())+"","#00BFFF"));
templateMessage.addData(new WxMpTemplateData("you", wxpush.getNameYou(),"#000000"));
templateMessage.addData(new WxMpTemplateData("me", wxpush.getNameMe(),"#000000"));
templateMessage.addData(new WxMpTemplateData("en",map.get("en") +"","#C71585"));
templateMessage.addData(new WxMpTemplateData("zh",map.get("zh") +"","#C71585"));
templateMessage.addData(new WxMpTemplateData("lubarmonth",huangli.get("lubarmonth") +"","#FFD700"));
templateMessage.addData(new WxMpTemplateData("lunarday",huangli.get("lunarday") +"","#FFD700"));
templateMessage.addData(new WxMpTemplateData("fitness",huangli.get("fitness") +"","#00BFFF"));
templateMessage.addData(new WxMpTemplateData("taboo",huangli.get("taboo") +"","#DC143C"));
templateMessage.addData(new WxMpTemplateData("zhishu",xingzuo.get("zhishu") +"","#ADFF2F"));
templateMessage.addData(new WxMpTemplateData("content",xingzuo.get("content") +"","#00BFFF"));
String beizhu = "❤";
if(JiNianRiUtils.getLianAiYear(wxpush.getDateLove()) != 0){
beizhu = "今天是我们在一起" + JiNianRiUtils.getLianAiYear(wxpush.getDateLove()) + "周年纪念日!";
}
if(JiNianRiUtils.getBirthday_you(wxpush.getDateBirYou()) == 0){
beizhu = "今天是"+wxpush.getNameYou()+"生日,生日快乐!";
}
if(JiNianRiUtils.getBirthday_me(wxpush.getDateBirMe()) == 0){
beizhu = "今天是"+wxpush.getNameMe()+"生日,快来祝"+wxpush.getNameMe()+"生日快乐!";
}
templateMessage.addData(new WxMpTemplateData("beizhu",beizhu,"#FF0000"));
try {
System.out.println(templateMessage.toJson());
System.out.println(wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage));
} catch (Exception e) {
System.out.println("推送失败:" + e.getMessage());
e.printStackTrace();
}
}
}
最后,那个wxpushService就是查询存需要发送数据的表的服务,表结构如下:
CREATE TABLE `t_wxpush` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
`app_id` varchar(255) DEFAULT NULL COMMENT '微信appId',
`secret` varchar(255) DEFAULT NULL COMMENT '微信secret',
`to_user` varchar(255) DEFAULT NULL COMMENT '微信用户openid',
`template_id` varchar(255) DEFAULT NULL COMMENT '模板id',
`tianxing_key` varchar(255) DEFAULT NULL COMMENT '数据key',
`name_you` varchar(255) DEFAULT NULL COMMENT '你的称呼',
`name_me` varchar(255) DEFAULT NULL COMMENT '我的称呼',
`date_love` varchar(255) DEFAULT NULL COMMENT '恋爱纪念日',
`date_bir_you` varchar(255) DEFAULT NULL COMMENT '你的生日',
`date_bir_me` varchar(255) DEFAULT NULL COMMENT '我的生日',
`district_id` varchar(255) DEFAULT NULL COMMENT '百度天气地区id',
`ak` varchar(255) DEFAULT NULL COMMENT '百度天气ak',
`district_name` varchar(255) DEFAULT NULL COMMENT '所在地区名称',
`push_time_work` varchar(255) DEFAULT NULL COMMENT '工作日推送时间',
`push_time_week` varchar(255) DEFAULT NULL COMMENT '周末推送时间',
`astro` varchar(255) DEFAULT NULL COMMENT '星座',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COMMENT='微信推送表';
另外,对于那些第三方接口(比如天气,彩虹屁英文情诗等)的秘钥就需要到第三方网站去配置。

被折叠的 条评论
为什么被折叠?



