微信开发平台:微信公众号开发文档

废话不多说,直接上代码

1、Controller层调用代码

/**
	 * 群发消息
	 * @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、工具类WechatMsg代码,下面以群发文本消息为例,如果是实现群发文本消息(群发其它消息,如图片视频等,请参考微信公众号开发文档),可以直接复制,只需要修改XXX的地方代码就可以了

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、如果你的需求是群发,那么到这里就结束了,如果需求是分组发(也就是is_to_all设为false时),需要先获取标签id,可以调用下面方法获取标签id,获取到的标签id填入上面代码中的tag_id变量。注意:下面代码中name的value值不能和公众号中已存在的标签名一样,调用下面代码成功后才能在公众号生成新标签

/**
	 * 调用这个方法获取标签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;
	}