Java代码实现向企业微信发送消息

1.向企业微信发送消息

        让用户订阅企业微信,从而用户的微信能收到发送的消息

1.1 注册企业微信

企业微信icon-default.png?t=N7T8https://work.weixin.qq.com/wework_admin/register_wx?from=myhome

1.2 创建企业微信应用

1.3 创建Java项目(我用的jdk1.8)

1.3.1 导入依赖

<!-- 企业微信配置依赖-->
<dependency>
        <groupId>com.github.binarywang</groupId>
        <artifactId>weixin-java-cp</artifactId>
        <version>4.0.8.B</version>
</dependency>
<!-- redis依赖-->
<dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
        <version>3.6.0</version>
</dependency>
<!-- fastjson-->
<dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.76</version>
</dependency>

1.3.2 创建配置类

package com.linkwx.company;

import com.alibaba.fastjson.JSON;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.api.impl.WxCpServiceImpl;
import me.chanjar.weixin.cp.config.impl.WxCpDefaultConfigImpl;
import org.apache.commons.lang3.StringUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * 推送企业微信配置
 * */
public class WxConfig {
    private static Integer agentId=应用id;
    private static String secret="应用密钥";
    private static String corpId="企业微信id";
    // 配置企业微信服务
    public static WxCpService getWxCpService() {
        WxCpService wxCpService=new WxCpServiceImpl();
        WxCpDefaultConfigImpl config =new WxCpDefaultConfigImpl();
        config.setAgentId(agentId);
        config.setCorpSecret(secret);
        config.setCorpId(corpId);
        resetTokenAndJsApi(wxCpService,config);
        return wxCpService;
    }
// 重置token
    public static void resetTokenAndJsApi(WxCpService wxCpService,WxCpDefaultConfigImpl wxCpDefaultConfig) {
    // 配置redis
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(8);
        jedisPoolConfig.setMaxTotal(18);
        // redis启动后,默认启动的是6379端口,没有密码可以不要最后的参数
        Jedis jedis =new JedisPool(jedisPoolConfig,"localhost",6379,5000,"111111").getResource();

        wxCpService.setWxCpConfigStorage(wxCpDefaultConfig);
        String wxAccessToken = "wx"+agentId;
        String json=jedis.get(wxAccessToken);
        if(!StringUtils.isEmpty(json)){
            wxCpDefaultConfig = JSON.parseObject(json,WxCpDefaultConfigImpl.class);
        }
        if(wxCpDefaultConfig.isAccessTokenExpired()){
            try {
                String accessToken = null;
                accessToken =wxCpService.getAccessToken(false);
                wxCpDefaultConfig.setAccessToken(accessToken);
            }catch (WxErrorException e){
                e.printStackTrace();
            }
        }
        if(wxCpDefaultConfig.isJsapiTicketExpired()){
            String jsApi = null;
            try {
                jsApi = wxCpService.getJsapiTicket();
                wxCpDefaultConfig.setJsapiTicket(jsApi);
            } catch (WxErrorException e) {
                e.printStackTrace();
            }
        }
        jedis.set(wxAccessToken,JSON.toJSONString(wxCpDefaultConfig));
        jedis.close();
    }
}

 

1.3.3 创建发送消息的方法调用企业微信接口

package com.linkwx.company;

import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.impl.WxCpMessageServiceImpl;
import me.chanjar.weixin.cp.bean.message.WxCpMessage;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 发送消息功能代码
 * */
public class sendMessage {
    public static void SendToWx(String user, String title, String message, String url)throws WxErrorException {
        //微信消息对象
        WxCpMessageServiceImpl wxCpMessageService = new WxCpMessageServiceImpl(WxConfig.getWxCpService());
        WxCpMessage wxCpMessage = new WxCpMessage();
        wxCpMessage.setSafe("0");
        wxCpMessage.setMsgType("textcard");

        //发送给用户:userid
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String time = format.format(new Date());
        //设置发送用户
        wxCpMessage.setToUser(user);
        //设置发送标题
        wxCpMessage.setTitle(title);
        //设置发送内容
        wxCpMessage.setDescription(message);
        //设置跳转url
        wxCpMessage.setUrl(url);
        wxCpMessage.setBtnTxt("api");
        wxCpMessageService.send(wxCpMessage);
    }

}

1.4 总结

        这个方法需要你服务器的ip是公网ip,然后需要在企业微信添加信任ip

 

  • 6
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
可以使用企业微信的API来实现机器人艾特群内成员的功能。以下是一个简单的Java代码示例: ```java import okhttp3.*; import org.json.JSONArray; import org.json.JSONObject; import java.io.IOException; public class ChatRobot { private static final String CORP_ID = "your_corp_id"; private static final String AGENT_ID = "your_agent_id"; private static final String SECRET = "your_secret"; private static final String BASE_URL = "https://qyapi.weixin.qq.com/cgi-bin"; public static void main(String[] args) throws IOException { // 获取access_token String accessToken = getAccessToken(CORP_ID, SECRET); // 发送消息 String groupId = "group_id"; // 要艾特的群组ID String content = "@all 请注意!"; // 艾特全体成员的消息内容 sendGroupMessage(accessToken, AGENT_ID, groupId, content); } /** * 获取access_token */ private static String getAccessToken(String corpId, String secret) throws IOException { String url = BASE_URL + "/gettoken?corpid=" + corpId + "&corpsecret=" + secret; OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(url).build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) { throw new IOException("Unexpected code " + response); } JSONObject responseBody = new JSONObject(response.body().string()); return responseBody.getString("access_token"); } /** * 发送消息,艾特全体成员 */ private static void sendGroupMessage(String accessToken, String agentId, String groupId, String content) throws IOException { String url = BASE_URL + "/message/send?access_token=" + accessToken; OkHttpClient client = new OkHttpClient(); JSONObject requestBody = new JSONObject(); requestBody.put("agentid", agentId); requestBody.put("msgtype", "text"); JSONObject textContent = new JSONObject(); textContent.put("content", content); requestBody.put("text", textContent); JSONObject mentionContent = new JSONObject(); JSONArray mentionList = new JSONArray(); mentionList.put("@all"); mentionContent.put("user_list", mentionList); requestBody.put("mention", mentionContent); JSONObject chatIdContent = new JSONObject(); chatIdContent.put("chatid", groupId); requestBody.put("chatid", chatIdContent); RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestBody.toString()); Request request = new Request.Builder().url(url).post(body).build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) { throw new IOException("Unexpected code " + response); } JSONObject responseBody = new JSONObject(response.body().string()); int errcode = responseBody.getInt("errcode"); if (errcode != 0) { throw new IOException("Send group message failed, errcode: " + errcode); } } } ``` 需要注意的是,发送消息需要使用企业微信的API密钥,所以需要先在企业微信后台中创建一个应用,并获取相应的CORP_ID、AGENT_ID和SECRET。此外,还需要获取access_token,用于接口调用的身份验证。具体实现可以参考上面的代码示例。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值