栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【Java中实现微信公众号模板消息推送】

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【Java中实现微信公众号模板消息推送】

主要流程:
1、在微信公众测试平台上注册账号,关注测试公众号,新增消息模板
2、拿到需要的参数openId appId appsecret 模板Id后进行开发
微信公众平台测试号管理地址 https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index

微信开放文档地址 https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_access_token.html

微信模板消息接口文档1 https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Template_Message_Interface.html

微信模板消息接口文档2 https://mp.weixin.qq.com/debug/cgi-bin/readtmpl?t=tmplmsg/faq_tmpl

微信获取Access_token接口文档 https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_access_token.html

3、消息参数定义规则


4、完了之后就只需简单的在Java中调用外部第三方接口了,完整代码如下

package com.nearfartec.travel.commodity.wx;

import lombok.*;

import java.io.Serializable;


@Setter
@Getter
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class DataEntity implements Serializable {

    private String value;

    private String color;

}

package com.nearfartec.travel.commodity.wx;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.nearfartec.framework.lib.utils.DateUtils;
import com.nearfartec.travel.commodity.enums.RoomServiceTypeEnum;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;


@Slf4j
//@Component
public class WeChatMsg {

    private final static String GET = "GET";
    private final static String POST = "POST";
    
    private final static String GRANT_TYPE = "client_credential";

    
    private final static String SEND_MSG_API_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";

    
    @Value("${weixin.msg.appid}")
    private String appId = "xxxxxxxxxxx";

    
    @Value("${weixin.msg.app-secret}")
    private String appSecret = "xxxxxxxxxxxxxxxxx";

    
    @Value("${weixin.msg.msg-template-id}")
    private String msgTemplateId = "24uPs-Rw5Q8sKPheSWoG4NmINkwc9WUm6NgJZ0Aw66k";

    
    @Value("${weixin.msg.template-to-url}")
    private String templateToUrl = "www.baidu.com";

    
    @Value("${weixin.msg.mini-program-app-id}")
    private String miniProgramAppId;

    
    @Value("${weixin.msg.mini-program-page-path}")
    private String miniProgramPagePath;

    
    public String getToken() {

        //接口地址拼接参数
        String getTokenApi = "https://api.weixin.qq.com/cgi-bin/token?grant_type=" + GRANT_TYPE + "&appid=" + appId + "&secret=" + appSecret;

        String tokenJsonStr = doGetPost(getTokenApi, GET, null);
        JSONObject tokenJson = JSONObject.parseObject(tokenJsonStr);
        String token = tokenJson.get("access_token").toString();
        log.info("获取到的TOKEN :{}", token);

        return token;
    }

    
    public void sendWeChatMsg(String openId,String roomStoreName,String roomName,String roomServiceType,String applyTime) {
        //接口地址
        String sendMsgApi = SEND_MSG_API_URL + getToken();
        //openId
        //String toUser = "oBH8O0kmvQ5nXiDN0JWQ_79gfP1g";
        //消息模板ID
        //String template_id = "dMprAMJa_FA6KuimBWNonuyFtyp43_SJw8Um3jyeuZM";
        //模板跳转链接
        //String toUrl = "http://weixin.qq.com/download";

        //整体参数map
        Map paramMap = new HashMap<>();
        //点击消息跳转相关参数map
        Map miniprogramMap = new HashMap<>();
        //消息主题显示相关map
        Map dataMap = new HashMap<>();

        miniprogramMap.put("appid", miniProgramAppId);
        miniprogramMap.put("pagepath", miniProgramPagePath);

        dataMap.put("roomStoreName", DataEntity.builder().value(roomStoreName).color("#173177").build());
        dataMap.put("roomName", DataEntity.builder().value(roomName).color("#173177").build());
        dataMap.put("roomServiceType", DataEntity.builder().value(roomServiceType).color("#173177").build());
        dataMap.put("applyTime", DataEntity.builder().value(applyTime).color("#173177").build());

        paramMap.put("touser", openId);
        paramMap.put("template_id", msgTemplateId);
        paramMap.put("url", templateToUrl);
        paramMap.put("miniprogram", miniprogramMap);
        paramMap.put("data", dataMap);
        String postResult = doGetPost(sendMsgApi, POST, paramMap);
        log.info("openId : {} ,推送结果:{}",openId,postResult);

    }

    
    public String doGetPost(String apiPath, String type, Map paramMap) {

        OutputStreamWriter out ;
        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 (StrUtil.equals(type, POST)) {
                // utf-8编码
                out = new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.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;
                }
                // utf-8编码
                result = new String(data, StandardCharsets.UTF_8);

            }
        } catch (IOException e) {
            log.error("IO异常", e);
        } finally {
            try {
                if (ObjectUtil.isNotNull(is)) {
                    is.close();
                }
            } catch (IOException e) {
                log.error("IO流关闭异常", e);
            }
        }
        return result;
    }

    public static void main(String[] args) {
        String openId = "oEuw462CDmk62pPRWQbxLRDyTvGM";
        //String openId = "oEuw46zox6DYwSncYZ5UNPJS0nk8";
        WeChatMsg chatMsg = new WeChatMsg();
        chatMsg.sendWeChatMsg(openId,"波罗蜜多酒店","酒店一楼1106", RoomServiceTypeEnum.CLEAN.getName(), DateUtils.getTime());
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/919172.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号