Java implements WeChat public account group sending text messages

WeChat Development Platform: WeChat Official Account Development Document

Don't talk nonsense, just go to the code

1. Controller layer call code

	/**
	 * 群发消息
	 * @param user
	 * @return
	 */
	@RequestMapping(value="/groupMessage",method=RequestMethod.POST,produces ="application/json;charset=utf-8")
	public JSONObject Message(@RequestBody(required=false)JSONObject obje) {
    
    
		JSONObject result=new JSONObject();
		logger.info("-----------开始群发------------");
		String content=obje.getString("content");//群发内容
		Integer code=wechatMsg.GroupMessage(wechatMsg.getToken(),content);//群发消息
		if(code==0) {
    
    
			result.put("code",0);
			result.put("data","群发成功");
		}else {
    
    
			result.put("code",1201);
			result.put("data","微信群发消息失败");
		}
		return result;
	}

2. Tool class WechatMsg code, the following is an example of mass text messaging. If mass text messaging is realized (for other messages, such as pictures and videos, please refer to the WeChat official account development document), you can copy it directly, and only need to modify the XXX The code is fine

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.demo.entity.DataEntity;
@Component
public class WechatMsg {
    
    	
	/**
	 * 获取token
	 * 
	 * @return token
	 */
	public String getToken() {
    
    
		// 授予形式
		String grant_type = "client_credential";
		//应用ID
		String appid = "XXXXXXXXXXXXXXXXXXXXXXXXX";
		//密钥
		String secret = "XXXXXXXXXXXXXXXXXXXXXXXXX";
		// 接口地址拼接参数
		String getTokenApi = "https://api.weixin.qq.com/cgi-bin/token?grant_type=" + grant_type + "&appid=" + appid
				+ "&secret=" + secret;
		String tokenJsonStr = doGetPost(getTokenApi, "GET", null);
		JSONObject tokenJson = JSONObject.parseObject(tokenJsonStr);
		String token = tokenJson.get("access_token").toString();
		System.out.println("获取到的TOKEN : " + token);
		return token;
	}
	/***
	 * 群发文本消息
	 * @param token
	 */
	public Integer GroupMessage(String token,String content) {
    
    
		// 接口地址
		String sendMsgApi = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token="+token;		
		 //整体参数map
        Map<String, Object> paramMap = new HashMap<String, Object>();
        //相关map
        Map<String, Object> dataMap1 = new HashMap<String, Object>();
        Map<String, String> dataMap2 = new HashMap<String, String>();
        dataMap1.put("is_to_all",true);//用于设定是否向全部用户发送,值为true或false,选择true该消息群发给所有用户,选择false可根据tag_id发送给指定群组的用户
        dataMap1.put("tag_id",1);//群发到的标签的tag_id,参见用户管理中用户分组接口,若is_to_all值为true,可不填写tag_id
        dataMap2.put("content",content);//要推送的内容
        paramMap.put("filter",dataMap1);//用于设定图文消息的接收者
        paramMap.put("text", dataMap2);//文本内容
        paramMap.put("msgtype","text");//群发的消息类型,图文消息为mpnews,文本消息为text,语音为voice,音乐为music,图片为image,视频为video,卡券为wxcard
        String back=doGetPost(sendMsgApi,"POST",paramMap);
        System.out.println("群发返回:"+back);
        JSONObject jsonObject =JSONObject.parseObject(back);//String转JSONObject,
        Integer re=jsonObject.getInteger("errcode");
        return re;
	}
    /**
     * 调用接口 post
     * @param apiPath
     */
    public String doGetPost(String apiPath,String type,Map<String,Object> paramMap){
    
    
        OutputStreamWriter out = null;
        InputStream is = null;
        String result = null;
        try{
    
    
            URL url = new URL(apiPath);// 创建连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod(type) ; // 设置请求方式
            connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
            connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
            connection.connect();
            if(type.equals("POST")){
    
    
                out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
                out.append(JSON.toJSONString(paramMap));
                out.flush();
                out.close();
            }
            // 读取响应
            is = connection.getInputStream();
            int length = (int) connection.getContentLength();// 获取长度
            if (length != -1) {
    
    
                byte[] data = new byte[length];
                byte[] temp = new byte[512];
                int readLen = 0;
                int destPos = 0;
                while ((readLen = is.read(temp)) > 0) {
    
    
                    System.arraycopy(temp, 0, data, destPos, readLen);
                    destPos += readLen;
                }
                result = new String(data, "UTF-8"); // utf-8编码
            }
        } catch (IOException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            try {
    
    
                is.close();
            } catch (IOException e) {
    
    
                e.printStackTrace();
            }
        }
        return  result;
    }
}

3. If your requirement is group sending, then it is over here. If the requirement is group sending (that is, when is_to_all is set to false), you need to get the tag id first. You can call the following method to get the tag id and get the tag id. Fill in the tag_id variable in the code above. Note: The value of name in the code below cannot be the same as the existing label name in the official account. Only after the following code is successfully called can a new label be generated on the official account

/**
	 * 调用这个方法获取标签ID后,还要在公众号上给标签添加用户
	 * @param token
	 * @return
	 */
	public Integer getTab(String token) {
    
    
		String sendMsgApi = "https://api.weixin.qq.com/cgi-bin/tags/create?access_token="+token;
		//整体参数map
        Map<String, Object> paramMap = new HashMap<String, Object>();
        //相关map
        Map<String, Object> dataMap1 = new HashMap<String, Object>();
        dataMap1.put("name","test6");//这里写你要创建的标签名
        paramMap.put("tag",dataMap1);
		String back=doGetPost(sendMsgApi,"POST",paramMap);
		System.out.println("请求获取标签接口返回:"+back);
		JSONObject jsonObject =JSONObject.parseObject(back).getJSONObject("tag");//String转JSONObject,
		Integer id=-1;//设id初始值为-1,如果最后返回id还是-1,代表获取标签失败
		if(jsonObject!=null) {
    
    
			id=jsonObject.getInteger("id");
		}
		return id;
	}

If you don’t understand or suggest, you can comment directly and I will solve it as soon as possible

Guess you like

Origin blog.csdn.net/qq_41936224/article/details/111193337