最新消息: 新版网站上线了!!!

SpringBoot微信消息接口配置详解

1.申请测试号,并记录appID和appsecret

2.关注测试号

3.添加消息模板

{{topic.DATA}} 
用户名: {{user.DATA}} 
单车编号:{{car.DATA}} 
锁定时间:{{date.DATA}} 
{{remark.DATA}}

微信接口配置和代码

1.添加微信配置文件

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties(prefix = "wechat")
public class WechatConf {
  // 获取accessToken的接口
  public static final String GET_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
  // 发送消息的接口
  public static final String PUSH_MESSAGE_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s";
  private String appId;
  private String appsecret;
  // 发送消息的接口的访问凭证
  private String accessToken;
  public String getAppId() {
    return appId;
  }
  public void setAppId(String appId) {
    this.appId = appId;
  }
  public String getAppsecret() {
    return appsecret;
  }
  public void setAppsecret(String appsecret) {
    this.appsecret = appsecret;
  }
  public String getAccessToken() {
    return accessToken;
  }

  public void setAccessToken(String accessToken) {
    this.accessToken = accessToken;
  }
}

这里@ConfigurationProperties(prefix = "wechat")注解会报黄,需要导入依赖

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>

2.填写配置文件application.yml

以下两个值会被注入到WechatConf 中

wechat:
app-id: wxc67a533f22dc2f9c
appsecret: <your appsecret>

3.注入发送Http请求的对象

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestConf {
@Bean
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}

4.后台调用微信接口凭证AccessToken的封装类

import com.fasterxml.jackson.annotation.JsonProperty;
public class AccessToken {
@JsonProperty("access_token")
private String accessToken;
@JsonProperty("expires_in")
private Long expiresIn;
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public Long getExpiresIn() {
return expiresIn;
}
public void setExpiresIn(Long expiresIn) {
this.expiresIn = expiresIn;
}
}

5.使用定时任务获取后台访问微信接口的凭证AccessToken

注意:需在启动类上添加开启定时任务的注解@EnableScheduling

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import com.thy.common.AccessToken;
import com.thy.config.WechatConf;
@Component
public class MessageTask {
@Autowired
private RestTemplate restTemplate;
@Autowired
private WechatConf wechatConf;
/**
* initialDelay: 初始化2s后执行第一次
* fixedDelay:微信默认Token过期时间为7200s,这里定时7100s执行一次定时任务
*/
@Scheduled(initialDelay = 2000, fixedDelay = 7100 * 1000)
public void refreshToken() {
// 请求方式: GET
// URL:https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
// 发起一个get请求,返回的数据json文本,使用json工具将json文本直接转化为Class<?>
AccessToken accessToken = restTemplate.getForObject(
String.format(WechatConf.GET_TOKEN_URL, wechatConf.getAppId(), wechatConf.getAppsecret()),
AccessToken.class);
// 将获取的accessToken注入wechatConf
wechatConf.setAccessToken(accessToken.getAccessToken());
}
}

6.发送消息接口的请求参数的封装类

import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonProperty;
public class MessageTemplate {
@JsonProperty("touser")
private String toUser;
@JsonProperty("template_id")
private String templateId;
private String url;
private Map<String,String> miniprogram;
private Map<String, Map<String, String>> data = new HashMap<>();
public static Map<String, String> initData(String value, String color) {
HashMap<String, String> data = new HashMap<String, String>();
data.put("value", value);
data.put("color", color);
return data;
}
public String getToUser() {
return toUser;
}
public void setToUser(String toUser) {
this.toUser = toUser;
}
public String getTemplateId() {
return templateId;
}
public void setTemplateId(String templateId) {
this.templateId = templateId;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Map<String, String> getMiniprogram() {
return miniprogram;
}
public void setMiniprogram(Map<String, String> miniprogram) {
this.miniprogram = miniprogram;
}
public Map<String, Map<String, String>> getData() {
return data;
}
public void setData(Map<String, Map<String, String>> data) {
this.data = data;
}
}

7.发送消息接口的返回值的封装类

public class Result {
private Integer errcode;
private String errmsg;
private Long msgid;
public Integer getErrcode() {
return errcode;
}
public void setErrcode(Integer errcode) {
this.errcode = errcode;
}
public String getErrmsg() {
return errmsg;
}
public void setErrmsg(String errmsg) {
this.errmsg = errmsg;
}
public Long getMsgid() {
return msgid;
}
public void setMsgid(Long msgid) {
this.msgid = msgid;
}
}

8.消息发送接口

import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.thy.common.MessageTemplate;
import com.thy.common.Result;
import com.thy.config.WechatConf;
import com.thy.pojo.UserCarInfo;
@RestController
public class MessageController {
@Autowired
private RestTemplate restTemplate;
@Autowired
private WechatConf wechatConf;
@RequestMapping("/sendMessage")
public Object sendMessage(@RequestBody UserCarInfo userCarInfo) {
MessageTemplate messageTemplate = new MessageTemplate();
// 设置模板id
messageTemplate.setTemplateId("othsG1ZD5w9ywTGyV6XCECnY1Q1oAIY5e-NvF94fzAI");
// 设置接收用户openId
messageTemplate.setToUser("oUbk_1bVlUGqhMzQHMC_jbkysMgY");
//点击详情跳转的地址
messageTemplate.setUrl("http://www.baidu.com");
//设置模板dada参数
messageTemplate.getData().put("topic", MessageTemplate.initData("您的单车已经锁定成功,骑行请注意安全!\n", ""));
messageTemplate.getData().put("user", MessageTemplate.initData(userCarInfo.getUserName(), "#0000EE"));
messageTemplate.getData().put("car", MessageTemplate.initData(userCarInfo.getCarSn(), "#00CD00"));
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
messageTemplate.getData().put("date", MessageTemplate.initData(simpleDateFormat.format(new Date())+"\n", ""));
messageTemplate.getData().put("remark", MessageTemplate.initData("点击详情可查看您的租车信息", ""));
//调用微信接口,发送模板消息
Result result = restTemplate.postForObject(String.format(WechatConf.PUSH_MESSAGE_URL, wechatConf.getAccessToken()),
messageTemplate, Result.class);
return result;
}
}

测试

1.运行项目,发送请求

2.接收到微信提醒消息

码云地址

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持谷谷点程序。

转载请注明:谷谷点程序 » SpringBoot微信消息接口配置详解