【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;

/**
 * <p>ClassName:DataEntity</p>
 * <p>Description: 公众号推送数据  </p>
 *
 * @author XiangBo
 * @date 2022-05-18 14:35
 */
@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;

/**
 * <p>ClassName:WeChatMsgUtil</p>
 * <p>Description: xxxxxx  </p>
 *
 * @author XiangBo
 * @date 2022-05-18 13:37
 */
@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";

    /** 发送模板消息url **/
    private final static String SEND_MSG_API_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";

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

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

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

    /** 模板跳转链接 **/
    @Value("${weixin.msg.template-to-url}")
    private String templateToUrl = "www.baidu.com";

    /** 模板跳转小程序AppId **/
    @Value("${weixin.msg.mini-program-app-id}")
    private String miniProgramAppId;

    /** 模板跳转小程序路径 **/
    @Value("${weixin.msg.mini-program-page-path}")
    private String miniProgramPagePath;

    /**
     * 获取token
     *
     * @return token
     */
    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;
    }

    /**
     * 发送微信推送消息
     *
     * @param openId 微信openId
     * @param roomStoreName param1 参数1
     * @param roomName param2 参数2
     * @param roomServiceType param3 参数3
     * @param applyTime param3 参数3
     */
    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<String, Object> paramMap = new HashMap<>();
        //点击消息跳转相关参数map
        Map<String, String> miniprogramMap = new HashMap<>();
        //消息主题显示相关map
        Map<String, Object> 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);

    }

    /**
     * 调用接口 post
     *
     * @param apiPath URL
     */
    public String doGetPost(String apiPath, String type, Map<String, Object> 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());
    }
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要将Java应用程序连接到微信公众号推送消息,您需要使用微信公众平台提供的API和Java的HTTP客户端库。以下是一些步骤: 1. 在微信公众平台上注册并获取应用程序的appID和appSecret。 2. 在Java应用程序使用HTTP客户端库发送HTTP请求来获取access_token,该token是访问API的凭证。 3. 通过微信公众平台提供的模板消息接口,构建一个消息模板。 4. 在Java应用程序使用HTTP客户端库发送HTTP请求,将模板消息发送到微信公众号。 下面是一个示例代码片段,演示如何使用Java和OkHttp库来发送一个简单的文本消息: ```java OkHttpClient client = new OkHttpClient(); String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET"; Request request = new Request.Builder() .url(url) .build(); Response response = client.newCall(request).execute(); JSONObject jsonObject = new JSONObject(response.body().string()); String access_token = jsonObject.getString("access_token"); String postUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token; String json = "{\"touser\":\"OPENID\",\"template_id\":\"TEMPLATE_ID\",\"data\":{\"content\":{\"value\":\"Hello World\"}}}"; RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json); Request postRequest = new Request.Builder() .url(postUrl) .post(body) .build(); Response postResponse = client.newCall(postRequest).execute(); ``` 在上面的代码,您需要将APPID和APPSECRET替换为您的应用程序的实际值。您还需要将OPENID替换为要发送消息的用户的openid,以及TEMPLATE_ID替换为您的消息模板的实际ID。 希望这可以帮助您开始将Java应用程序连接到微信公众号推送消息

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值