package com.csjs.coreapp.prove.utils.wechat;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
/**
* 企业微信工具类
*
* @author hury
*/
@Component
public class WechatUtil {
// public String corpid = "xxxxx";
// public String corpsecret = "xxxxx";
// public String agentid = "xxxxx";
@Value("${wechat.corpId}")
private String corpid;
@Value("${wechat.corpsecret}")
private String corpsecret;
@Value("${wechat.agentid}")
private String agentid;
/**
* 获取access_token
*
*/
public String getAccessToken() {
String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken" + "?corpid=" + corpid + "&corpsecret=" + corpsecret;
String result = HttpUtil.get(url);
cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj(result);
String access_token = jsonObject.get("access_token").toString();
return access_token;
}
/**
* 根据手机号获取企业微信用户UserId
*
* @param mobile
* @return
*/
public String getUserIdByMobile(String mobile) {
String url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserid?access_token=" + getAccessToken();
HashMap<String, Object> map = new HashMap<>();
map.put("mobile", mobile);
String result = HttpUtil.post(url, JSONUtil.toJsonStr(map));
String userid = JSONUtil.parseObj(result).get("userid").toString();
return userid;
}
/**
* 发送文本消息
*
* @param content 发送内容
* @param touser 接收人
* @return
*/
public void sendMsgText(String touser, String content) {
Map<String, Object> data = new HashMap<String, Object>();
Map<String, Object> text = new HashMap<String, Object>();
data.put("touser", touser);
data.put("msgtype", "text");
data.put("agentid", agentid);
text.put("content", content);
data.put("text", text);
String param = JSONUtil.toJsonStr(data);
String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + getAccessToken();
HttpUtil.post(url, param);
}
@Test
public void test(){
String userId = getUserIdByMobile("1111111");
sendMsgText(userId,"我是一条测试消息");
}
}
企业微信发送文本消息工具类,基于hutool工具类,超简洁
最新推荐文章于 2023-10-22 10:52:03 发布