1.微信推送方法
/**
* @ClassName:PushController
* @Description:微信推送
* @Author:chenyb
* @Date:2020/11/27 10:33 上午
* @Versiion:1.0
*/
@RestController
@RequestMapping("/wx")
public class PushController {
@Autowired
private WeChatConfig weChatConfig;
/*
* 微信测试账号推送
* */
@GetMapping("/push")
@Scheduled(cron = "0 43 17 ? * *")
public String push() {
//1,配置
WxMpInMemoryConfigStorage wxStorage = new WxMpInMemoryConfigStorage();
wxStorage.setAppId(weChatConfig.getAppId());
wxStorage.setSecret(weChatConfig.getAppsecret());
WxMpService wxMpService = new WxMpServiceImpl();
wxMpService.setWxMpConfigStorage(wxStorage);
//2,推送消息
WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
.toUser("o9lMz54rJwdYrtCYyhg3K7GTwBro")//要推送的用户openid
.templateId(weChatConfig.getTemplateId())//模版id
.url(weChatConfig.getForwardUrl())//点击模版消息要访问的网址
.build();
//3,如果是正式版发送模版消息,这里需要配置你的信息,替换微信公众号上创建的模板内容
//设置模板dada参数
LocalDate date = LocalDate.now();
String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
templateMessage.addData(new WxMpTemplateData("date", date.getMonthValue() "月" date.getDayOfMonth() "日" "\n", "#CCCCFF"));
templateMessage.addData(new WxMpTemplateData("topic", "店长您好,有一笔新的让利单,需要您的确认。" "\n", "#FF00FF"));
templateMessage.addData(new WxMpTemplateData("time", time, "#CCFF99"));
try {
wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
return "推送成功";
} catch (Exception e) {
System.out.println("推送失败:" e.getMessage());
e.printStackTrace();
return "推送失败";
}
}
}
2.pom文件
<!--微信模版消息推送三方sdk-->
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-mp</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>4.1.0</version>
</dependency>
3.获取token
package com.itheima.reggie.utils;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastJSON.jsonObject;
import com.itheima.reggie.config.WeChatConfig;
import com.itheima.reggie.entity.AccessToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Component
public class WeChatCommonUtil {
Logger logger = LoggerFactory.getLogger(WeChatCommonUtil.class);
// 获取access_token的接口地址(GET) 限2000(次/天)
private static String url = WeChatConfig.GET_TOKEN_URL;
public AccessToken getToken(String appid, String appsecret){
AccessToken token;
//访问微信服务器的地址
String requestUrl=url.replace("APPID", appid).replace("APPSECRET", appsecret);
//HttpRequestUtil httpRequestUtil=new HttpRequestUtil();
//创建一个json对象
String responseStr = HttpUtil.get(requestUrl);
System.out.println("获取到的String格式的Response为:" responseStr);
//判断返回字符串是否为空
if (responseStr != null) {
token = JSONObject.parseObject(responseStr, AccessToken.class);
} else {
token = null;
// 获取token失败
logger.error("获取token失败 errcode:{} errmsg:{}");
}
return token;
}
}