企业微信开发第一步获取AccessToken,企业微信的AccessToken和公众号的不一样,企业微信所有接口调用只需要一个AccessToken,而公众号授权和jssdk是分开的
一、获取企业微信AccessToken
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bootdo.common.cache.RedisService;
import com.bootdo.common.utils.Errors;
import com.bootdo.wx.entity.WxAgent;
import com.bootdo.wx.mapper.WxAgentMapper;
import com.hyd.weixin.utils.HttpSender;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
/**
* 处理企业微信AccessToken
* @author laowang
* @email [email protected]
*/
@Slf4j
@Service
public class WeixinAccessTokenService {
//企业微信
public static final String URL_PATTERN2 = "https://qyapi.weixin.qq.com/cgi-bin/gettoken" +
"?corpid={{APPID}}&corpsecret={{SECRET}}";
@Autowired
WxAgentMapper wxAgentMapper;
@Autowired
RedisService redisService;
public String getEnterpriseAccessToken(String account) throws IOException {
String accessToken = "";
WxAgent wxAgent = selectAgent(account);
if (wxAgent == null) {
throw Errors.Account_MissingAccount.ex(account);
}
String url = URL_PATTERN2
.replace("{{APPID}}", wxAgent.getCorpid())
.replace("{{SECRET}}", wxAgent.getAgentSecret());
if(redisService.keyExists("enterprise_"+wxAgent.getAgentId())){
accessToken = redisService.get("enterprise_"+wxAgent.getAgentId());
}else{
HttpSender httpSender = new HttpSender(url);
String json = httpSender.sendAndGetResponse();
JSONObject jsonObject = JSON.parseObject(json);
if (jsonObject.getInteger("errcode")==0) {
accessToken = jsonObject.getString("access_token");
redisService.set("enterprise_"+wxAgent.getAgentId(),accessToken,7200, TimeUnit.SECONDS);
}else{
log.error("企业号获取AccessToken错误 原因{}",jsonObject.getString("errmsg"));
}
}
return accessToken;
}
public WxAgent selectAgent(String account) {
return wxAgentMapper.selectWxAgent(account);
}
}
注:这里获取AccessToken根据自己业务来,做好AccessToken缓存
二、对所有消息类型的枚举
public interface WxTempConstant {
public final String TEMP_TEXT = "text";
public final String TEMP_IMAGE = "image";
public final String TEMP_VOICE = "voice";
public final String TEMP_VIDEO = "video";
public final String TEMP_FILE = "file";
public final String TEMP_TEXT_CARD = "textcard";
public final String TEMP_NEWS = "news";
public final String TEMP_MPNEWS = "mpnews";
public final String TEMP_MARKDOWN = "markdown";
public final String TEMP_MINIPROGEAM_NOTICE = "miniprogram_notice";
public final String TEMP_TASK_CARD = "taskcard";
}
三、封装消息节点结构接口
import java.util.List;
import java.util.Map;
/**
* (description)
* created at 2017/9/30
*
* @author laowang
*/
public interface MapInitializer {
void init(Map m);
void initListMap(List
四、封装消息发送类
package com.bootdo.wx.service.wechat;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bootdo.common.utils.MapInitializer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 处理企业微信消息推送操作
*
* @author laowang
* @email [email protected]
*/
@Slf4j
@Service
public class WeixinMessageService {
//企业微信
public static final String URL_PATTERN = "https://qyapi.weixin.qq.com/cgi-bin/message/send" +
"?access_token={{ACCESS_TOKEN}}";
@Autowired
WeixinAccessTokenService weixinAccessTokenService;
/**
* 推送企业消息给用户
*
* @param agentId 应用ID
* @param touser 成员ID列表(消息接收者,多个接收者用‘|’分隔,最多支持1000个)。特殊情况:指定为@all,则向关注该企业应用的全部成员发送
* @param toparty 部门ID列表,多个接收者用‘|’分隔,最多支持100个。当touser为@all时忽略本参数
* @param totag 标签ID列表,多个接收者用‘|’分隔,最多支持100个。当touser为@all时忽略本参数
* @param msgtype 消息类型
* @param initializer 消息主体参数参考 https://work.weixin.qq.com/api/doc#90000/90135/90236
*/
public void send(String msgtype, String touser, String toparty, String totag, MapInitializer initializer, String agentId) {
log.info("企业应用{}发送{}消息给{}", agentId, msgtype, touser);
//准备构造json
JSONObject firstjsonObject = new JSONObject();
JSONObject msgtypejsonObject = new JSONObject();
//图文类json构造
JSONArray jsonArray = new JSONArray();
JSONObject secandjsonObject = new JSONObject();
//填充消息参数
Map map = new HashMap<>();
//填充图文类多节点参数
List
五、各类型消息推送单元测试(消息主体参数参考 https://work.weixin.qq.com/api/doc#90000/90135/90236)
package com.bootdo;
import com.bootdo.common.utils.MapInitializer;
import com.bootdo.common.utils.wechat.WxTempConstant;
import com.bootdo.wx.service.wechat.WeixinMessageService;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
public class BootdoApplicationTests {
@Autowired
WeixinMessageService weixinMessageService;
@Test
public void contextLoads() throws IOException {
final String agentId = "1000002";
final String touser = "WangLinJun";
final String toparty = "";
final String totag = "";
//文本消息
try {
weixinMessageService.send(WxTempConstant.TEMP_TEXT, touser, toparty, totag,
new MapInitializer() {
@Override
public void init(Map m) {
m.put("content", "你的快递已到,请携带工卡前往邮件中心领取。\n出发前可查看邮件中心视频实况,聪明避开排队。");
}
@Override
public void initListMap(List
以上代码请根据自己的业务进行更改