1 新建应用
登陆微信管理(如果没有请先注册)
https://work.weixin.qq.com/wework_admin/loginpage_wx?etype=otherLogin#apps/modApiApp/5629501376549416
第二步,点击应用管理--> 创建应用。
第三步,上传logo,输入应用名称,点击创建应用按钮。
2 找到corpid和secret
第一步,打开我的企业->企业信息->企业ID。企业ID就是corpid。
第二步,打开应用管理->具体应用名->secret。
3 获取token
调用https://qyapi.weixin.qq.com/cgi-bin/gettoken后面加上自己corpid和corpsecret。
application.properties配置
#企业微信相关信息
#企业Id
wechat.corpid=wwe19918a2a
#应用私钥
wechat.corpsecret=DXfkT9ijmT83iknrj
#获取token地址
wechat.ACCESS_TOKEN_URL=https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wwe19918a2a&corpsecret=DXfkT9ijmT83iknrj
#发送消息地址
wechat.CREATE_SESSION_URL=https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=
#获取用户id地址
wechat.GET_USER_ID=https://qyapi.weixin.qq.com/cgi-bin/user/getuserid?access_token=
#应用ID
wechat.agentId=1000
-------------------工具类开始-------------------
package com.medicine.pharmaceutical_factory.utils;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import javax.net.ssl.HttpsURLConnection;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
@Data
@Component
public class SendWeChatMessage {
//企业Id
@Value("${wechat.corpid}")
private String corpid;
//应用私钥
@Value("${wechat.corpsecret}")
private String corpsecret;
// 获取访问权限码(access_token)URL GET请求
@Value("${wechat.ACCESS_TOKEN_URL}")
private String ACCESS_TOKEN_URL;
// 发送消息URL POST请求
@Value("${wechat.CREATE_SESSION_URL}")
private String CREATE_SESSION_URL;
// 获取企业微信用户userid POST请求
@Value("${wechat.GET_USER_ID}")
private String GET_USER_ID;
//应用ID
@Value("${wechat.agentId}")
private String agentId;
@Autowired
private RedisUtil redisUtil;
public String getToken() {
//没有token就初始化
// 查询验证码
String token = (String) redisUtil.get("wxtoken");
if (StringUtils.isBlank(token)) {
token=initToken();
}
return token;
}
/**
* 初始化token
*
* @return
*/
public String initToken() {
//获取token
RestTemplate restTemplate = new RestTemplate();
String url = ACCESS_TOKEN_URL.replaceAll("CORPID", corpid).replaceAll("CORPSECRET", corpsecret);
JSONObject jsonObject = restTemplate.getForObject(url, JSONObject.class);
String access_token = jsonObject.getString("access_token");
//把token放入session时间7000秒
redisUtil.set("wxtoken",access_token,7000);
return access_token;
}
/**
* 根据电话号码得到userId
*
* @param token
* @param employeePhone
* @return
*/
public String getUserId(String token, String employeePhone) {
StringBuffer sb = new StringBuffer();
sb.append("{");
sb.append("\"mobile\":" + "\"" + employeePhone + "\",");
sb.append("}");
String json = sb.toString();
String result = "";
String url = GET_USER_ID + token;
try {
HttpsURLConnection http = getHttp(url);
OutputStream os = http.getOutputStream();
os.write(json.getBytes("UTF-8"));
InputStream is = http.getInputStream();
int size = is.available();
byte[] jsonBytes = new byte[size];
is.read(jsonBytes);
result = new String(jsonBytes, "UTF-8");
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
JSONObject jsonObject = JSONObject.parseObject(result);
return jsonObject.getString("userid");
}
public HttpsURLConnection getHttp(String action) throws Exception {
URL url = null;
HttpsURLConnection http = null;
try {
url = new URL(action);
http = (HttpsURLConnection) url.openConnection();
http.setRequestMethod("POST");
http.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
http.setDoOutput(true);
http.setDoInput(true);
//连接超时30秒
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");
//读取超时30秒
System.setProperty("sun.net.client.defaultReadTimeout", "30000");
http.connect();
} catch (Exception e) {
e.printStackTrace();
}
return http;
}
public String sendMessage(String token, String json) {
//请求链接
String action = CREATE_SESSION_URL + token;
String result="";
try {
HttpsURLConnection http = getHttp(action);
OutputStream os = http.getOutputStream();
os.write(json.getBytes("UTF-8"));
InputStream is = http.getInputStream();
int size = is.available();
byte[] jsonBytes = new byte[size];
is.read(jsonBytes);
result = new String(jsonBytes, "UTF-8");
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
return result;
}
return result;
}
}
-------------------工具类结束-------------------
/**方法调用
*
* @param phoneList 目标人企业微信绑定的手机号
* @param message 消息内容
*/
public void sendMessage(List<String> phoneList,String message){
//初始化token
String token=sendWeChatMessage.getToken();
for(String phone : phoneList){
//得到userId
String userId=sendWeChatMessage.getUserId(token,phone);
//构造消息体
StringBuffer sb = new StringBuffer();
String content=userId+","+message;
sb.append("{");
sb.append("\"touser\":" + "\"" + userId + "\",");
sb.append("\"msgtype\":" + "\"" + "text" + "\",");
sb.append("\"agentid\":" + "\"" + sendWeChatMessage.getAgentId() + "\",");
sb.append("\"text\":" + "{");
sb.append("\"content\":" + "\"" + content + "\"},");
sb.append("\"safe\":\"0\"");
sb.append("}");
//发送消息
boolean b= sendWeChatMessage.sendMessage(token,sb.toString());
System.out.println(phone+"======================="+b);
}
}
ps:token生成后要放到redis中否则7200秒后会失效
参考原文:https://blog.csdn.net/qq_38974638/article/details/113246970
Java 实现企业微信消息推送
最新推荐文章于 2024-06-06 18:50:06 发布