1.Controller层代码
package com.example.tuisong.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
@RestController
@RequestMapping("/api")
public class WeChatConller {
@Value("${wechat.appId}")
private String appId;
@Value("${wechat.appSecret}")
private String appSecret;
@Value("${wechat.templateMessageUrl}")
private String templateMessageUrl;
@PostMapping("/template-message")
public String sendTemplateMessage(@RequestBody String data) {
// 1. 获取access_token
String accessToken = getAccessToken();
// 2. 构造模板消息
String templateMessage = buildTemplateMessage(data);
// 3. 发送模板消息
String url = templateMessageUrl + "?access_token=" + accessToken;
RestTemplate restTemplate = new RestTemplate();
String response = restTemplate.postForObject(url, templateMessage, String.class);
return response;
}
private String getAccessToken() {
String url = templateMessageUrl + "&appid=" + appId + "&secret=" + appSecret;
RestTemplate restTemplate = new RestTemplate();
String response = restTemplate.getForObject(url, String.class);
return response;
}
private String buildTemplateMessage(String data) {
// 根据传入的数据构造模板消息
// 可以使用JSON转换工具,如Jackson或Gson
return data;
}
}
2.配置文件application.properties
3.获取access-token
GET:https请求方式: GET https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
发送模板消息http请求方式: POST https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN
touser:是openID
template_id是模板id