微信

微信公众号群发消息和模版消息

2021-07-27  本文已影响0人  星钻首席小管家

1.WeiXinService

package com.zyjournals.web.sysadmin.module.weixin;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yx.lib.cache.YxCache;
import com.yx.lib.http.HttpResponseInfo;
import com.yx.lib.http.YxHttpClient;
import com.yx.lib.json.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 微信公共服务类
 * @author sp.
 * <br/>date: 2021-07-07.
 */
@Slf4j
@Service
public class WeiXinService {

    @Value("${wx.app.appid}")
    private String weixinAppid;

    @Value("${wx.app.appsecret}")
    private String weixinAppSecret;

    @Value("${wx.app.templateId}")
    private String templateId;

    @Resource
    @Lazy
    private YxCache wechatTokenCache;

    private String TOKEN_CACHE_KEY = "tokenCacheKey:";

    private String HOST_URL = "https://api.weixin.qq.com";

    /**
     * 获取token
     *
     * @return token
     */
    public String getToken() {
        String key = TOKEN_CACHE_KEY+"Platform";
        String token = wechatTokenCache.get(key, String.class);
        if(StringUtils.isNotEmpty(token)){
            Long expiresTime = wechatTokenCache.get(token, Long.class);
            if(expiresTime >Long.valueOf(System.currentTimeMillis())){
                return token;
            }
        }

        // 授予形式
        String grant_type = "client_credential";
        // 接口地址拼接参数
        String getTokenApi = "/cgi-bin/token?grant_type=" + grant_type + "&appid=" + weixinAppid
                + "&secret=" + weixinAppSecret;
        try {

            YxHttpClient yxHttpClient = new YxHttpClient(HOST_URL);
            HttpResponseInfo httpResponseInfo = yxHttpClient.sendGet(getTokenApi);
            String content = httpResponseInfo.getContent();

            JSONObject tokenJson = JSONObject.parseObject(content);

            //判断是否有ID返回
            if (tokenJson != null) {
                if (tokenJson.get("access_token") != null) {
                    token = tokenJson.get("access_token").toString();
                    String expiresTime = tokenJson.get("expires_in").toString();
                    wechatTokenCache.put(key,token,7000*1000L);
                    wechatTokenCache.put(token,System.currentTimeMillis()+Long.valueOf(expiresTime)*1000L,7000*1000L);
                    return token;
                }
            }
        } catch (NumberFormatException e) {
            log.info(e.getMessage());
        }
        return null;
    }

    /**
     * 发送模版消息
     * @param parameter
     * @return
     */
    public JsonResult sendTemplateMessage(TemplateMessageParameter parameter,String token){
        //系统参数
        HashMap<String, String> programMap = new HashMap<>();
        programMap.put("appid",weixinAppid);
        //所需跳转到小程序的具体页面路径,支持带参数,(示例index?foo=bar),要求该小程序已发布,暂不支持小游戏
        //programMap.put("pagepath",weixinAppid);

        //发送数据
        Map<String, String> parameterMap = new HashMap<>();
        Map<String, Object> dataMap = new HashMap<>();
        BeanUtil.copyProperties(parameter, parameterMap);
        //处理字体
        for (String key : parameterMap.keySet()) {
            if("url".equalsIgnoreCase(key)){
                continue;
            }
            Object value = parameterMap.get(key);
            if(ObjectUtils.isNotEmpty(value)){
                HashMap<String, String> map = new HashMap<>();
                map.put("value",value.toString());
                map.put("color","#173177");
                dataMap.put(key, map);
            }
        }

        //查询用户
        List userList = this.getUserList();
        for (Object o : userList) {
            //请求参数
            HashMap<String, Object> map = new HashMap<>();
            map.put("touser",o);
            map.put("template_id",templateId);
            map.put("url",parameter.getUrl());
            //map.put("miniprogram",programMap);
            map.put("data",dataMap);

            //发送请求
            String getTokenApi = "/cgi-bin/message/template/send?access_token=" + token;
            try {
                YxHttpClient yxHttpClient = new YxHttpClient(HOST_URL);
                HttpResponseInfo httpResponseInfo = yxHttpClient.sendPost(getTokenApi, JSON.toJSONString(map));
                String content = httpResponseInfo.getContent();

                JSONObject jsonObject = JSONObject.parseObject(content);

                //判断是否有ID返回
                if (jsonObject != null) {
                    if (jsonObject.get("errcode") != null) {
                        String errCode = jsonObject.get("errcode").toString();
                        if("0".equalsIgnoreCase(errCode)){
                            log.info(o+"推送成功!");
                        }
                    }
                }
            } catch (NumberFormatException e) {
                log.info(e.getMessage());
            }
        }
        return new JsonResult(true,"发送成功!");
    }

    /**
     * 获取用户列表-openID
     * @return
     */
    public List getUserList() {
        String access_token = this.getToken();
        String url = "/cgi-bin/user/get?access_token="+access_token;
        YxHttpClient yxHttpClient = new YxHttpClient(HOST_URL);
        HttpResponseInfo httpResponseInfo = yxHttpClient.sendGet(url);
        String content = httpResponseInfo.getContent();

        JSONObject resultJson = JSONObject.parseObject(content);

        JSONObject data = (JSONObject) resultJson.get("data");
        List openidlist = (List) data.get("openid");
        return openidlist;
    }

}

2.群发图文消息

package com.zyjournals.web.journaladmin.module.weixin.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yx.lib.http.HttpResponseInfo;
import com.yx.lib.http.YxHttpClient;
import com.zyjournals.web.journaladmin.module.weixin.vo.Material;
import com.zyjournals.web.journaladmin.module.weixin.vo.TuWen;
import com.zyjournals.web.journaladmin.module.weixin.vo.VideoIdDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.util.Base64;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 微信群发消息服务
 * @author sp.
 * <br/>date: 2021-07-07.
 */
@Slf4j
@Service
public class MassMsgService {

    /**
     * host
     */
    private static final String HOST_URL = "https://api.weixin.qq.com";
    /**
     * 素材列表
     */
    private static final String MATERIAL_LIST_URL = "/cgi-bin/material/batchget_material?access_token=ACCESS_TOKEN";
    /**
     * 添加图文素材地址
     */
    private static final String UPLOAD_NEWS_URL = "/cgi-bin/media/uploadnews?access_token=ACCESS_TOKEN";


    /**
     * 上传图文消息内的图片获取URL
     * @param token
     * @param filePath
     * @param filename
     * @return
     */
    public String formUpload(String filePath,String filename,String token) {
        String urlStr = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token="+token;
        String res = "";
        HttpURLConnection conn = null;
        // boundary就是request头和上传文件内容的分隔符
        String BOUNDARY = "---------------------------123821742118716";
        try {
            URL fileUrl = new URL(filePath);

            URL url = new URL(urlStr);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(30000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
            OutputStream out = new DataOutputStream(conn.getOutputStream());

            // file
            String inputName = "";
            String contentType = Files.probeContentType(Paths.get(filename));
            if (filename.endsWith(".png")) {
                contentType = "image/png";
            }
            if (contentType == null || contentType.equals("")) {
                contentType = "application/octet-stream";
            }

            StringBuffer strBuf = new StringBuffer();
            strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
            strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + filename + "\"\r\n");
            strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
            out.write(strBuf.toString().getBytes());
            DataInputStream in = new DataInputStream(fileUrl.openStream());
            int bytes = 0;
            byte[] bufferOut = new byte[1024];
            while ((bytes = in.read(bufferOut)) != -1) {
                out.write(bufferOut, 0, bytes);
            }
            in.close();
            byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
            out.write(endData);
            out.flush();
            out.close();

            // 读取返回数据
            StringBuffer strBuf2 = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                strBuf2.append(line).append("\n");
            }
            res = strBuf2.toString();
            reader.close();
            reader = null;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();
                conn = null;
            }
        }
        JSONObject object = JSONObject.parseObject(res);
        if (object != null) {
            if (object.get("url") != null) {
                return object.getString("url");
            }
        }
        return null;
    }

    /**
     * 上传图文消息内的图片获取URL
     * @param token
     * @param base64Str
     * @param filename
     * @return
     */
    public String formUploadBase64(String base64Str,String filename,String token) {
        String urlStr = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token="+token;
        String res = "";
        HttpURLConnection conn = null;
        // boundary就是request头和上传文件内容的分隔符
        String BOUNDARY = "---------------------------123821742118716";
        try {
            int prefixIndex = base64Str.indexOf(",");
            byte[] buffer = Base64.decodeBase64(base64Str.substring(prefixIndex + 1));

            //URL fileUrl = new URL(filePath);

            URL url = new URL(urlStr);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(30000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
            OutputStream out = new DataOutputStream(conn.getOutputStream());

            // file
            String inputName = "";
            String contentType = Files.probeContentType(Paths.get(filename));
            if (filename.endsWith(".png")) {
                contentType = "image/png";
            }
            if (contentType == null || contentType.equals("")) {
                contentType = "application/octet-stream";
            }

            StringBuffer strBuf = new StringBuffer();
            strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
            strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + filename + "\"\r\n");
            strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
            out.write(strBuf.toString().getBytes());
            DataInputStream in = new DataInputStream(new ByteArrayInputStream(buffer));
            int bytes = 0;
            byte[] bufferOut = new byte[1024];
            while ((bytes = in.read(bufferOut)) != -1) {
                out.write(bufferOut, 0, bytes);
            }
            in.close();
            byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
            out.write(endData);
            out.flush();
            out.close();

            // 读取返回数据
            StringBuffer strBuf2 = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                strBuf2.append(line).append("\n");
            }
            res = strBuf2.toString();
            reader.close();
            reader = null;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();
                conn = null;
            }
        }
        JSONObject object = JSONObject.parseObject(res);
        if (object != null) {
            if (object.get("url") != null) {
                return object.getString("url");
            }
        }
        return null;
    }




    /**
     * 微信保存临时素材方法
     * @param filePath   文件路径
     * @param type  媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb),图文消息(news)
     * @param token 微信令牌
     * @return 文件ID
     */
    public  String addMaterialEver(String filePath,String fileName,String type, String token,String videoJson) {
        try {
            //微信接口地址
            String path = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=" + token + "&type=" + type;
            //调用工具类进行上传
            String result = connectHttpsByPost(path,filePath,fileName,videoJson);
            log.info("转换前:"+result);
            //替换字符串中不需要的字符
            result = result.replaceAll("[\\\\]", "");
            log.info("result:" + result);
            //将字符串转换成json对象
            JSONObject resultJSON = JSONObject.parseObject(result);
            //判断是否有ID返回
            if (resultJSON != null) {
                if (resultJSON.get("media_id") != null) {
                    log.info("上传" + type + "临时素材成功");
                    return resultJSON.getString("media_id");
                } else if (resultJSON.get("thumb_media_id") != null) {
                    log.info("上传" + type + "临时素材成功");
                    return resultJSON.getString("thumb_media_id");
                }else {
                    log.info("上传" + type + "临时素材失败");
                }
            }
            return null;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 获取视频素材ID
     * @param token
     * @param dto
     * @return
     */
    public  String addMaterialEver(String token,VideoIdDTO dto) {
        //微信接口地址
        String path = "/cgi-bin/media/uploadvideo?access_token=" + token ;
        YxHttpClient yxHttpClient = new YxHttpClient(HOST_URL);
        HttpResponseInfo httpResponseInfo = yxHttpClient.sendPost(path, JSON.toJSONString(dto));
        String content = httpResponseInfo.getContent();

        JSONObject object = JSONObject.parseObject(content);
        //判断是否有ID返回
        if (object != null) {
            if (object.get("media_id") != null) {
                log.info("上传视频素材成功");
                return object.getString("media_id");
            }else {
                log.info("上传视频素材失败");
            }
        }
        return null;
    }

    /**
     * 新增其他类型永久素材
     * 1、公众号的素材库保存总数量有上限:图文消息素材、图片素材上限为100000,其他类型为1000。
     *
     * 2、素材的格式大小等要求与公众平台官网一致:
     *
     * 图片(image): 10M,支持bmp/png/jpeg/jpg/gif格式
     *
     * 语音(voice):2M,播放长度不超过60s,mp3/wma/wav/amr格式
     *
     * 视频(video):10MB,支持MP4格式
     *
     * 缩略图(thumb):64KB,支持JPG格式
     * @param filePath
     * @param fileName
     * @param type 媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb)
     * @param videoJson
     * @param token
     * @return
     */
    public String addMaterial(String filePath,String fileName,
                                                   String type,String videoJson,
                                                   String token) {
        try {
            //微信接口地址
            String path = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token="+ token + "&type=" + type;
            //调用工具类进行上传
            String result = connectHttpsByPost(path,filePath,fileName,videoJson);
            log.info("转换前:"+result);
            //替换字符串中不需要的字符
            result = result.replaceAll("[\\\\]", "");
            log.info("result:" + result);
            //将字符串转换成json对象
            JSONObject resultJSON = JSONObject.parseObject(result);
            //判断是否有ID返回
            if (resultJSON != null) {
                if (resultJSON.get("media_id") != null) {
                    log.info("上传" + type + "永久素材成功");
                    return resultJSON.getString("media_id");
                } else {
                    log.info("上传" + type + "永久素材失败");
                }
            }
            return null;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;

    }

    /**
     * 进行上传
     * @param wxUrl
     * @param path
     * @param fileName
     * @return
     * @throws IOException
     */
    private String connectHttpsByPost(String wxUrl,String path, String fileName,String videoDescriptionForm) throws IOException {
        URL fileUrl = new URL(path);
        URL urlObj = new URL(wxUrl);
        //连接
        HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
        String result = null;
        con.setDoInput(true);
        con.setDoOutput(true);
        // post方式不能使用缓存
        con.setUseCaches(false);

        // 设置请求头信息
        con.setRequestProperty("Connection", "Keep-Alive");
        con.setRequestProperty("Charset", "UTF-8");
        // 设置边界
        String BOUNDARY = "----------" + System.currentTimeMillis();
        con.setRequestProperty("Content-Type",
                "multipart/form-data; boundary="
                        + BOUNDARY);

        // 请求正文信息
        // 第一部分:
        StringBuilder sb = new StringBuilder();
        // 必须多两道线
        sb.append("--");
        sb.append(BOUNDARY);
        sb.append("\r\n");
        sb.append("Content-Disposition: form-data;name=\"media\";filelength=\"" + 0 + "\";filename=\""

                + fileName + "\"\r\n");
        sb.append("Content-Type:application/octet-stream\r\n\r\n");
        byte[] head = sb.toString().getBytes("utf-8");
        // 获得输出流
        OutputStream out = new DataOutputStream(con.getOutputStream());
        // 输出表头
        out.write(head);

        // 文件正文部分
        // 把文件已流文件的方式 推入到url中
        DataInputStream in = new DataInputStream(fileUrl.openStream());
        int bytes = 0;
        byte[] bufferOut = new byte[1024];
        while ((bytes = in.read(bufferOut)) != -1) {
            out.write(bufferOut, 0, bytes);
        }
        in.close();
        // 结尾部分
        // 定义最后数据分隔线
        byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");
        out.write(foot);

        if (videoDescriptionForm != null) {
            StringBuilder sb1 = new StringBuilder();
            sb1.append("--"); // 必须多两道线
            sb1.append(BOUNDARY);
            sb1.append("\r\n");
            sb1.append("Content-Disposition: form-data;name=\"description\";");
            sb1.append("Content-Type:application/octet-stream\r\n\r\n");
            out.write(sb1.toString().getBytes());
            out.write(videoDescriptionForm.getBytes());
            out.write(("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8"));// 定义最后数据分隔线
        }

        out.flush();
        out.close();
        StringBuffer buffer = new StringBuffer();
        BufferedReader reader = null;
        try {
            // 定义BufferedReader输入流来读取URL的响应
            reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            if (result == null) {
                result = buffer.toString();
            }
        } catch (IOException e) {
            log.info("发送POST请求出现异常!" + e.getMessage());
        } finally {
            if (reader != null) {
                reader.close();
            }
        }
        return result;
    }

    /**
     * 上传临时图文消息素材
     * @param articles
     * @param token
     * @return
     */
    public String uploadNews(List<TuWen> articles, String token){
        String url = UPLOAD_NEWS_URL.replace("ACCESS_TOKEN", token);

        //组装参数
        return addNews(articles, url);

    }

    /**
     * 上传永久图文消息素材
     * @param articles
     * @param token
     * @return
     */
    public String uploadPermanentNews(List<TuWen> articles, String token){
        //永久素材地址
        String url = "/cgi-bin/material/add_news?access_token="+token;
        return addNews(articles, url);

    }

    /**
     * 上传图文素材
     * @param articles
     * @param url
     * @return
     */
    private String addNews(List<TuWen> articles, String url) {
        //组装参数
        String str = JSONObject.toJSON(articles).toString();

        str = "{" + "\"articles\":" + str + "}";

        YxHttpClient yxHttpClient = new YxHttpClient(HOST_URL);
        HttpResponseInfo httpResponseInfo = yxHttpClient.sendPost(url, str);
        System.out.println(httpResponseInfo);
        String content = httpResponseInfo.getContent();

        JSONObject object = JSONObject.parseObject(content);
        //判断是否有ID返回
        if (object != null) {
            if (object.get("media_id") != null) {
                log.info("上传图文素材成功");
                return object.getString("media_id");
            } else {
                log.info("上传图文素材失败");
            }
        }
        return null;
    }

    /**
     * 获取永久素材列表(根据分类)
     * 图片(image)、视频(video)、语音 (voice)、图文(news)
     * 参数:type   offset    count
     * @throws IOException
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     */
    public String batchGetMaterial(String token) {
        //POST请求发送的json参数
        Material m = new Material();
        m.setType("news");
        m.setOffset(0);
        m.setCount(10);
        JSONObject json = (JSONObject) JSONObject.toJSON(m);
        String str = json.toString();
        YxHttpClient yxHttpClient = new YxHttpClient(HOST_URL);
        String url = MATERIAL_LIST_URL.replace("ACCESS_TOKEN", token);
        HttpResponseInfo httpResponseInfo = yxHttpClient.sendPost(url, str);
        String content = httpResponseInfo.getContent();
        System.out.println(httpResponseInfo);
        return content;
    }

    /***
     * 群发消息预览
     * @param token
     */
    public Integer sendMassPreview(String token,String json) {
        // 接口地址
        String sendMsgApi = "/cgi-bin/message/mass/preview?access_token="+token;
        YxHttpClient yxHttpClient = new YxHttpClient("https://api.weixin.qq.com");
        HttpResponseInfo back= yxHttpClient.sendPost(sendMsgApi, json);
        System.out.println("群发返回:"+back);
        //String转JSONObject,
        String httpContent = back.getContent();

        JSONObject object = JSONObject.parseObject(httpContent);
        //判断是否有ID返回
        if (object != null) {
            JSONObject jsonObject =JSONObject.parseObject(object.toString());
            Integer re=jsonObject.getInteger("errcode");
            return re;
        }
        return 0;
    }

    /**
     * 视频消息
     * @param token
     * @param mediaId
     * @param title
     * @param description
     * @return
     */
    public Integer sendVideoMassPreview(String token,String mediaId,String title,String description) {
        //整体参数map
        Map<String, Object> paramMap = new HashMap<String, Object>();
        //相关map
        Map<String, String> dataMap2 = new HashMap<String, String>();

        //要推送的内容
        dataMap2.put("media_id",mediaId);
        dataMap2.put("title",title);
        //dataMap2.put("description",description);
        dataMap2.put("content"," i专用保护");
        dataMap2.put("content_source_url","www.baidu.com");
        dataMap2.put("need_open_comment","0");


        //用于设定图文消息的接收者 oHzamwv-t1hPRbe4WluhAgpWDnUE
        paramMap.put("touser","oHzamwv-t1hPRbe4WluhAgpWDnUE");
        //文本内容
        paramMap.put("mpvideo", dataMap2);
        //群发的消息类型,图文消息为mpnews,文本消息为text,语音为voice,音乐为music,图片为image,视频为video,卡券为wxcard
        paramMap.put("msgtype","mpvideo");
        //不能省略
        paramMap.put("send_ignore_reprint", 0);
        String s = JSONObject.toJSONString(paramMap);
        return sendGroupMessage(token,s);
    }

    /**
     * 图文消息
     * @param token
     * @param mediaId
     * @return
     */
    public Integer sendImageMassPreview(String token,String mediaId) {
        //整体参数map
        Map<String, Object> paramMap = new HashMap<String, Object>();
        //相关map
        Map<String, String> dataMap2 = new HashMap<String, String>();
        //发送map
        Map<String, Boolean> filterMap = new HashMap<String, Boolean>();

        //要推送的内容
        dataMap2.put("media_id",mediaId);
        //用于设定图文消息的接收者
//        filterMap.put("is_to_all",true);

        String[] userArray={"oHzamwv-t1hPRbe4WluhAgpWDnUE","oHzamwgkcxtxwHYdC0_7e20HQ3w0"};

        paramMap.put("touser","osn6q6U4VIjvR4q1RVPFalkHnxZ4");
        //文本内容
        paramMap.put("mpnews", dataMap2);
        //群发的消息类型,图文消息为mpnews,文本消息为text,语音为voice,音乐为music,图片为image,视频为video,卡券为wxcard
        paramMap.put("msgtype","mpnews");
        //不能省略
        //paramMap.put("send_ignore_reprint", 0);
        String s = JSONObject.toJSONString(paramMap);
        return sendMassPreview(token,s);
    }

    /***
     * 群发消息
     * @param token
     */
    public Integer sendGroupMessage(String token,String content) {
        // 接口地址
        String sendMsgApi = "/cgi-bin/message/mass/sendall?access_token="+token;
        //发送请求
        YxHttpClient yxHttpClient = new YxHttpClient(HOST_URL);
        HttpResponseInfo back= yxHttpClient.sendPost(sendMsgApi, content);
        System.out.println("群发返回:"+back);
        //String转JSONObject,
        String httpContent = back.getContent();

        JSONObject object = JSONObject.parseObject(httpContent);
        //判断返回
        if (object != null) {
            JSONObject jsonObject =JSONObject.parseObject(object.toString());
            Integer re=jsonObject.getInteger("errcode");
            return re;
        }
        return 0;
    }



}
上一篇下一篇

猜你喜欢

热点阅读