package com.panzhihua.sangeshenbian.utils;
|
|
import cn.hutool.http.HttpUtil;
|
import com.alibaba.fastjson.JSONObject;
|
import lombok.extern.slf4j.Slf4j;
|
import org.springframework.stereotype.Component;
|
|
import java.util.Map;
|
|
@Component
|
@Slf4j
|
public class WechatMsgUtil {
|
|
private String appId;
|
|
private String appSecret;
|
|
// 获取access_token
|
private String getAccessToken() {
|
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret="+appSecret;
|
String result = HttpUtil.get(url);
|
return JSONObject.parseObject(result).getString("access_token");
|
}
|
|
// 发送模板消息
|
public void sendTemplateMsg(String openId, String templateId,
|
Map<String, String> content) {
|
try {
|
String accessToken = getAccessToken();
|
String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+accessToken;
|
|
JSONObject json = new JSONObject();
|
json.put("touser", openId);
|
json.put("template_id", templateId);
|
|
JSONObject data = new JSONObject();
|
content.forEach((key, value) -> {
|
JSONObject item = new JSONObject();
|
item.put("value", value);
|
data.put(key, item);
|
});
|
json.put("data", data);
|
|
String result = HttpUtil.post(url, json.toJSONString());
|
log.info("微信消息发送结果:{}", result);
|
} catch (Exception e) {
|
log.error("微信消息发送失败", e);
|
}
|
}
|
}
|