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