首页 > 其他分享 >微信每日天气推送

微信每日天气推送

时间:2022-08-25 15:48:33浏览次数:65  
标签:templateMessage String 微信 天气 new import 推送 com public

一、注册微信测试账号,编辑推送模板

 

 

 

 

二、spring boot 后台

目录结构:

 

1.依赖

 1     <properties>
 2         <java.version>1.8</java.version>
 3         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 4         <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
 5         <spring-boot.version>2.3.7.RELEASE</spring-boot.version>
 6     </properties>
 7 
 8     <dependencies>
 9         <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
10         <dependency>
11             <groupId>org.projectlombok</groupId>
12             <artifactId>lombok</artifactId>
13             <version>1.18.20</version>
14             <scope>provided</scope>
15         </dependency>
16 
17         <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
18         <dependency>
19             <groupId>com.alibaba</groupId>
20             <artifactId>fastjson</artifactId>
21             <version>2.0.7</version>
22         </dependency>
23 
24         <dependency>
25             <groupId>org.springframework.boot</groupId>
26             <artifactId>spring-boot-starter-web</artifactId>
27         </dependency>
28 
29         <dependency>
30             <groupId>org.springframework.boot</groupId>
31             <artifactId>spring-boot-starter-test</artifactId>
32             <scope>test</scope>
33             <exclusions>
34                 <exclusion>
35                     <groupId>org.junit.vintage</groupId>
36                     <artifactId>junit-vintage-engine</artifactId>
37                 </exclusion>
38             </exclusions>
39         </dependency>
40         <!-- https://mvnrepository.com/artifact/com.github.binarywang/weixin-java-mp -->
41         <dependency>
42             <groupId>com.github.binarywang</groupId>
43             <artifactId>weixin-java-mp</artifactId>
44             <version>3.3.0</version>
45         </dependency>
46     </dependencies>

 

2.实体类

 1 package com.ang.wxpushdaily.entity;
 2 
 3 import lombok.AllArgsConstructor;
 4 import lombok.Data;
 5 import lombok.NoArgsConstructor;
 6 
 7 /**
 8  * @author ncwuDA
 9  * @createtime 2022-08-25
10  */
11 @Data
12 @AllArgsConstructor
13 @NoArgsConstructor
14 public class Weather {
15     String area;
16     String date;
17     String week;
18     // 当前天气
19     String weather;
20     // 当前温度
21     String real;
22     // 最低温度
23     String lowest;
24     // 最高温度
25     String highest;
26     // 风级大小
27     String windsc;
28     // 风向
29     String wind;
30     //提示
31     String tips;
32 
33 }

 

3.工具类

 1)发送请求工具类

 1 package com.ang.wxpushdaily.utils;
 2 
 3 import org.apache.http.HttpEntity;
 4 import org.apache.http.client.methods.CloseableHttpResponse;
 5 import org.apache.http.client.methods.HttpGet;
 6 import org.apache.http.impl.client.CloseableHttpClient;
 7 import org.apache.http.impl.client.HttpClients;
 8 import org.apache.http.util.EntityUtils;
 9 
10 import java.io.IOException;
11 
12 /**
13  * @author ncwuDA
14  * @createtime 2022-08-25
15  */
16 public class HttpsClientUtils {
17 
18     /**
19      * 发送get请求
20      *
21      * @param url 发送链接 拼接参数
22      */
23     public static String sendGet(String url) throws IOException {
24         CloseableHttpClient httpClient = HttpClients.createDefault();
25         HttpGet httpGet = new HttpGet(url);
26         CloseableHttpResponse response = httpClient.execute(httpGet);
27         String resp;
28         try {
29             HttpEntity entity = response.getEntity();
30             resp = EntityUtils.toString(entity, "utf-8");
31             EntityUtils.consume(entity);
32         } finally {
33             response.close();
34         }
35         return resp;
36     }
37 }

 

2)获取天气工具类

 1 package com.ang.wxpushdaily.utils;
 2 
 3 import com.alibaba.fastjson.JSONArray;
 4 import com.alibaba.fastjson.JSONObject;
 5 import com.ang.wxpushdaily.entity.Weather;
 6 import org.springframework.web.client.RestTemplate;
 7 
 8 import java.io.IOException;
 9 import java.util.HashMap;
10 import java.util.List;
11 import java.util.Map;
12 
13 /**
14  * @author ncwuDA
15  * @createtime 2022-08-25
16  */
17 public class WeatherUtils {
18     public static void main(String[] args) throws IOException {
19         System.out.println(getWeather());
20     }
21     public static Weather getWeather() throws IOException {
22         String city = "XXX"; // 地区
23         String key = "********************"; //APIKEY
24         String res = HttpsClientUtils.sendGet("http://api.tianapi.com/tianqi/index?key=" + key + "&&city=" + city);
25         JSONObject json = JSONObject.parseObject(res);
26         assert json != null;
27         JSONArray newsList = json.getJSONArray("newslist");
28         List<Weather> weathers = newsList.toJavaList(Weather.class);
29 
30         return weathers.get(0);
31     }
32 }

 

3)计算生日工具类

 1 package com.ang.wxpushdaily.utils;
 2 
 3 
 4 import java.text.DateFormat;
 5 import java.text.ParseException;
 6 import java.text.SimpleDateFormat;
 7 import java.util.Calendar;
 8 
 9 /**
10  * @author ncwuDA
11  * @createtime 2022-08-25
12  */
13 public class MemorialDayUtils {
14 
15     public static int getLianAi(){
16         return calculationLianAi("2022-12-11");
17     }
18     public static int getBirthday_Jo(){
19         try {
20             return calculationBirthday("2009-03-09");
21         } catch (ParseException e) {
22             e.printStackTrace();
23         }
24         return 0;
25     }
26     public static int getBirthday_Hui(){
27         try {
28             return calculationBirthday("2020-01-11");
29         } catch (ParseException e) {
30             e.printStackTrace();
31         }
32         return 0;
33     }
34 
35     // 计算生日天数
36     public static int calculationBirthday(String clidate) throws ParseException {
37         SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
38         Calendar cToday = Calendar.getInstance(); // 存今天
39         Calendar cBirth = Calendar.getInstance(); // 存生日
40         cBirth.setTime(myFormatter.parse(clidate)); // 设置生日
41         cBirth.set(Calendar.YEAR, cToday.get(Calendar.YEAR)); // 修改为本年
42         int days;
43         if (cBirth.get(Calendar.DAY_OF_YEAR) < cToday.get(Calendar.DAY_OF_YEAR)) {
44             // 生日已经过了,要算明年的了
45             days = cToday.getActualMaximum(Calendar.DAY_OF_YEAR) - cToday.get(Calendar.DAY_OF_YEAR);
46             days += cBirth.get(Calendar.DAY_OF_YEAR);
47         } else {
48             // 生日还没过
49             days = cBirth.get(Calendar.DAY_OF_YEAR) - cToday.get(Calendar.DAY_OF_YEAR);
50         }
51         // 输出结果
52         return days;
53     }
54 
55     // 计算天数
56     public static int calculationLianAi(String date) {
57         DateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
58         int day = 0;
59         try {
60             long time = System.currentTimeMillis() - simpleDateFormat.parse(date).getTime();
61             day = (int) (time / 86400000L);
62         } catch (ParseException e) {
63             e.printStackTrace();
64         }
65         return day;
66     }
67 }

 

4.推送配置

 1 package com.ang.wxpushdaily.main;
 2 
 3 import com.ang.wxpushdaily.entity.Weather;
 4 import com.ang.wxpushdaily.utils.MemorialDayUtils;
 5 import com.ang.wxpushdaily.utils.WeatherUtils;
 6 import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
 7 import me.chanjar.weixin.mp.api.WxMpService;
 8 import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
 9 import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
10 import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
11 
12 import java.io.IOException;
13 import java.util.Map;
14 
15 /**
16  * @author ncwuDA
17  * @createtime 2022-08-25
18  */
19 public class Pusher {
20 
21     public static void main(String[] args) throws IOException {
22         push();
23     }
24 
25     private static final String appId = "wxa1c394a*********";
26     private static final String secret = "84c32ce8cd02379bf*************";
27 
28     public static void push() throws IOException {
29         //配置测试号信息
30         WxMpInMemoryConfigStorage wxStorage = new WxMpInMemoryConfigStorage();
31         wxStorage.setAppId(appId);
32         wxStorage.setSecret(secret);
33         WxMpService wxMpService = new WxMpServiceImpl();
34         wxMpService.setWxMpConfigStorage(wxStorage);
35         //配置模板信息
36         WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
37                 .toUser("ofnf15lpR422OhB3********") // 用户id
38                 .templateId("fh7fPySUnc_J2bZu9Mi78CXvSI8***********")  //模板id
39                 .build();
40         //配置模版推送消息
41         Weather weather = WeatherUtils.getWeather();
42         templateMessage.addData(new WxMpTemplateData("date", weather.getDate() + "  " + weather.getWeek() + "\n", "#9932CD"));
43         templateMessage.addData(new WxMpTemplateData("weather", weather.getArea() + "  " + weather.getWeather() + "\n", "#9932CD"));
44         templateMessage.addData(new WxMpTemplateData("real", weather.getReal() + "\n", "#EE212D"));
45         templateMessage.addData(new WxMpTemplateData("lowest", weather.getLowest() + "  ", "#EE212D"));
46         templateMessage.addData(new WxMpTemplateData("highest", weather.getHighest() + "\n", "#EE212D"));
47         templateMessage.addData(new WxMpTemplateData("wind", weather.getWind() + "  ", "#B95EA3"));
48         templateMessage.addData(new WxMpTemplateData("windsc", weather.getWindsc() + "\n\n", "#B95EA3"));
49         templateMessage.addData(new WxMpTemplateData("tips", weather.getTips() + "", "#8E2323"));
50         templateMessage.addData(new WxMpTemplateData("lianai", MemorialDayUtils.getLianAi() + "", "#FF1493"));
51         templateMessage.addData(new WxMpTemplateData("shengri1", MemorialDayUtils.getBirthday_Jo() + "", "#FFA500"));
52         templateMessage.addData(new WxMpTemplateData("shengri2", MemorialDayUtils.getBirthday_Hui() + "", "#FFA500"));
53         String beizhu = "❤";
54         if (MemorialDayUtils.getLianAi() % 365 == 0) {
55             beizhu = "今天是恋爱" + (MemorialDayUtils.getLianAi() / 365) + "周年纪念日!";
56         }
57         if (MemorialDayUtils.getBirthday_Jo() == 0) {
58             beizhu = "今天是生日,生日快乐呀!";
59         }
60         if (MemorialDayUtils.getBirthday_Hui() == 0) {
61             beizhu = "今天是生日,生日快乐呀!";
62         }
63         templateMessage.addData(new WxMpTemplateData("beizhu", beizhu, "#FF0000"));
64 
65         try {
66             System.out.println(templateMessage.toJson());
67             System.out.println(wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage));
68         } catch (Exception e) {
69             System.out.println("推送失败:" + e.getMessage());
70             e.printStackTrace();
71         }
72     }
73 }

 

5.启动定时

package com.ang.wxpushdaily;

import com.ang.wxpushdaily.main.Pusher;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.io.IOException;

@SpringBootApplication
@EnableScheduling // 开启定时任务
public class WxPushDailyApplication {

    public static void main(String[] args) {
        SpringApplication.run(WxPushDailyApplication.class, args);
    }

    // 定时
    @Scheduled(cron = "0 0 6 * * ?")
    public void goodMorning() throws IOException {
        Pusher.push();
    }

}

 

标签:templateMessage,String,微信,天气,new,import,推送,com,public
From: https://www.cnblogs.com/ikunn/p/16624462.html

相关文章

  • 微信公众平台开发 - 接入公众号(.NetCore+WebApi)
    1.使用WebApi来配置公众号服务器地址,get用于签名,post用于接口,需要注意路由的定义  namespaceTzj.WeiXinSite.Controllers.Api{[Route("api/[controller]")]......
  • 创建企业微信教程
    企业微信应用消息配置说明优点:一次配置,持续使用配置好以后,只需要微信就能收消息,不再需要安装企业微信客户端PS:消息接口无需认证即可使用,个人用微信就可以注册具体操......
  • 微信小程序---自定义组件和传参
    1.自定义组件1.在项目根目录中新建components文件夹2.在components文件夹下新建组件的文件夹,如zujian3.鼠标右键点击zujian文件夹,选择新建component,就会生成wxml,wxss,js......
  • uni-app微信小程序保存照片(照片是两张照片合并成canvas的另一张图片)到相册
    背景:1、若是使用了 uni.downloadFile(),那么使用的url必须是http或者https开头的图片,这是官方的,实际使用你会发现模拟器确实是http开头的图片,但是开发版、体验版、真机测试......
  • 微信上怎么设置每周二汽车限行限号提醒
    对于很多人来说,每天手机不离手主要是为了接收各种各样的微信消息,无论是我们和孩子老师的交流还是和家人、同事们之间的交流都要用到微信。既然大多数人的都比较重视微信消......
  • 最新微信小程序抓包方法
    一、安装fiddler官网下载:https://www.telerik.com/download/fiddler二、配置打开fiddlertools->options,genneral:全选https:connections:配置代理地址gateway:三......
  • 微信公众号天气推送(快写给你的对象)
    下载项目https://gitee.com/toyan/wechat-official-account-push/tree/master/下载那个压缩包就好https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showin......
  • 微信小程序实现城市列表
    效果图与文件目录wxml<!--pages/citylist/citylist.wxml--><viewclass="city-body"><!--搜索城市--><viewclass="search-bar"><viewclass="search-ro......
  • Prometheus企业微信告警
    自己注册一个企业微信,进入管理控制台。在应用管理中点击创建应用创建机器人发送消息测试发送消息测试,我这里可以正常收到消息找到企业ID找到机器人的AgentId......
  • 微信小程序点击结算获取用户信息
    //countPrice代表事件名字countPrice(){//获取用户登录信息用同步的方法获取用户信息userinfo代表键letuserinfo=wx.getStorageSync('......