企业微信发送文本消息工具类,基于hutool工具类,超简洁

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,"我是一条测试消息"); 
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值