使用springboot每日推送早安问候语到用户微信

Posted stevezhao6

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用springboot每日推送早安问候语到用户微信相关的知识,希望对你有一定的参考价值。

本文主要实现给不同的用户推动不同的问候模板

准备工作

申请微信公众平台的测试号

申请微信测试公众号
创建成功后,可以看到appid和appsecret,这个后面认证时需要

申请模板

可自行修改

今天是:now.DATA 不管那一天,每一天都是想你的一天 
当前城市:city.DATA 
今天的天气:text.DATA
最低气温:low.DATA 度
最高气温:high.DATA 度 
今天是我们想恋的第:scq_day.DATA 天 
距你的生日还有:bir_day.DATA 天 
daily_english_cn.DATA 
daily_english_en.DATA

新建成功后,记得保存模板Id后续有用

扫描关注该测试公众号

扫码关注后,记录微信号,后续推送通知用

申请百度天气

申请百度天气

完成认证后,创建一个应用,保存ak

申请天行数据的接口

申请天行数据

  • 申请彩虹屁
  • 申请每日一句

记得保存申请接口的key

开发工作

技术栈

  • springboot 2.7.5
  • swagger 3.0
  • mysql 8.x
  • spring data jpa
  • openfeign

依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.zhao</groupId>
    <artifactId>daily-weather</artifactId>
    <version>1.0.0</version>
    <name>daily-weather</name>
    <description>微信用户推送消息</description>

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-boot.version>2.7.5</spring-boot.version>
        <swagger.version>3.0.0</swagger.version>
        <knife4j.version>3.0.3</knife4j.version>
        <fastjson.version>2.0.15</fastjson.version>
        <openfeign.version>3.1.3</openfeign.version>
        <hutools.version>5.7.5</hutools.version>
    </properties>
    <dependencies>
        <!--hutools-->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-core</artifactId>
            <version>$hutools.version</version>
        </dependency>
        <!--fastjson-->
        <dependency>
            <groupId>com.alibaba.fastjson2</groupId>
            <artifactId>fastjson2</artifactId>
            <version>$fastjson.version</version>
        </dependency>
        <!--open feign-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
            <version>$openfeign.version</version>
        </dependency>
        <!--weixin-java-mp-->
        <dependency>
            <groupId>com.github.binarywang</groupId>
            <artifactId>weixin-java-mp</artifactId>
            <version>3.3.0</version>
        </dependency>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <!--swagger-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>$swagger.version</version>
        </dependency>
        <!--换掉默认皮肤-->
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>knife4j-spring-boot-starter</artifactId>
            <version>$knife4j.version</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </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>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>$spring-boot.version</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.3.7.RELEASE</version>
                <configuration>
                    <mainClass>com.zhao.wechat.DailyWeatherApplication</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

配置文件

server:
  port: 43310
# 微信配置
tencent:
  wechat:
    appId: 微信appid
    appSecret: 微信appSecret
  # 模板消息集合
  templatelist:
    - type: 1
      templateId: 微信模板id
    - type: 2
      templateId: 微信模板id
    - type: 3
      templateId: 微信模板id
# 百度天气配置
baidu:
  server: https://api.map.baidu.com
  ak: 百度数据的ak
# 天行数据
tianxin:
  server: http://api.tianapi.com
  key: 天行数据的key
spring:
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher
  datasource:
    type: com.zaxxer.hikari.HikariDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://ip:3306/库名?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
    username: root
    password: 564929
    hikari:
      minimum-idle: 5
      # 空闲连接存活最大时间,默认600000(10分钟)
      idle-timeout: 180000
      # 连接池最大连接数,默认是10
      maximum-pool-size: 10
      # 此属性控制从池返回的连接的默认自动提交行为,默认值:true
      auto-commit: true
      # 连接池名称
      pool-name: MyHikariCP
      # 此属性控制池中连接的最长生命周期,值0表示无限生命周期,默认1800000即30分钟
      max-lifetime: 1800000
      # 数据库连接超时时间,默认30秒,即30000
      connection-timeout: 30000
      connection-test-query: SELECT 1
  jpa:
    show-sql: true # 默认false,在日志里显示执行的sql语句
    database: mysql
    database-platform: org.hibernate.dialect.MySQL5Dialect
    hibernate:
      ddl-auto: update #指定为update,每次启动项目检测表结构有变化的时候会新增字段,表不存在时会 新建,如果指定create,则每次启动项目都会清空数据并删除表,再新建
      naming:
        #指定jpa的自动表生成策略,驼峰自动映射为下划线格式7
        implicit-strategy: org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
        #physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
# 日志
#logging:
#  config: classpath:logback-spring-dev.xml

统一数据封装

package com.zhao.wechat.advice;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhao.wechat.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 对前端响应结果统一封装
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.zhao.wechat.rest")
public class ApiResponseAdvice implements ResponseBodyAdvice<Object> 


	/**
	 * 打印统一请求响应规范
	 */
	ApiResponseAdvice()
		log.info("启动请求统一响应规范... ...");
	


	/**
	 * 判断是否需要对返回值进行封装
	 * @param returnType the return type
	 * @param converterType the selected converter type
	 * @return
	 */
	@Override
	public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) 
		// 如果返回的结果是Result.class类型就不用封装
		if (returnType.getParameterType().equals(Result.class))
			return false;
		
		return true;
	

	/**
	 * 对返回前端的值统一封装
	 * @param body the body to be written
	 * @param returnType the return type of the controller method
	 * @param selectedContentType the content type selected through content negotiation
	 * @param selectedConverterType the converter type selected to write to the response
	 * @param request the current request
	 * @param response the current response
	 * @return
	 */
	@Override
	public Object beforeBodyWrite(Object body,
								  MethodParameter returnType,
								  MediaType selectedContentType,
								  Class<? extends HttpMessageConverter<?>> selectedConverterType,
								  ServerHttpRequest request,
								  ServerHttpResponse response) 
	 if (returnType.getParameterType().equals(String.class))
		 // 如果是String类需要特殊处理
		 ObjectMapper objectMapper = new ObjectMapper();
		 try 
			 // 设置响应数据格式为json
			 response.getHeaders().add("content-type","application/json;charset=UTF-8");
			 return objectMapper.writeValueAsString(Result.success(body));
		  catch (JsonProcessingException e) 
			 throw new RuntimeException(e);
		 
	 
	 return Result.success(body);
	



工程结构

用户controller

package com.zhao.wechat.rest;

import com.zhao.wechat.domain.UserInfo;
import com.zhao.wechat.service.UserInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户信息管理视图层
 */
@RestController
@RequestMapping("/userInfo")
@Api(tags = "用户信息管理")
public class UserInfoRest 

	@Autowired
	private UserInfoService userInfoService;

	/**
	 * 分页获取所有的用户
	 * @return
	 */
	@ApiOperation(value = "分页获取所有的用户")
	@PostMapping("/queryPage")
	public Page<UserInfo> queryUserPage(@PageableDefault Pageable pageable)
		Page<UserInfo> userInfos = userInfoService.queryUserPage(pageable.getPageNumber(), pageable.getPageSize());
		return userInfos;
	

	/**
	 * 添加或者修改用户
	 */
	@ApiOperation(value = "添加或者修改用户")
	@PostMapping("/saveOrUpdate")
    public	void saveOrUpdate(@RequestBody UserInfo userInfo)
		userInfoService.saveOrUpdate(userInfo);
	

	/**
	 * 删除用户
	 */
	@ApiOperation(value = "删除用户")
	@DeleteMapping("/delete")
	public void deleteUserById(@RequestParam("id") Long id)
		userInfoService.deleteUserById(id);
	


调用第三方接口

package com.zhao.wechat.remote;

import com.zhao.wechat.remote.param.TianXinParam;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.cloud.openfeign.SpringQueryMap;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;

/**
 * 第三方接口天行数据
 */
@FeignClient(value = "TianDataRemoteClient",url = "$tianxin.server")
public interface TianDataRemoteClient 

	/**
	 * 获取彩虹屁
	 */
	@GetMapping(value = "/caihongpi/index",
			consumes = MediaType.APPLICATION_JSON_VALUE,
			produces = MediaType.APPLICATION_JSON_VALUE
	)
	String 以上是关于使用springboot每日推送早安问候语到用户微信的主要内容,如果未能解决你的问题,请参考以下文章

微信每日早安推送

java实现每日给女友微信发送早安等微信信息

还在手动发早安吗?教你用java实现每日给女友微信发送早安

小红书 程序员七夕礼物 - 微信每日早安推送 简单部署一键启动

最能打动人心的早安问候「温馨甜蜜」

网易邮箱问候语