使用Java实现微信小程序订阅消息

首先到微信小程序的官网,选择合适自己的订阅消息模板。

寻找到适合自己的模板之后,记住模板ID,点开详情,记住每个字段id

微信小程序订阅消息官网文档介绍地址:小程序订阅消息 | 微信开放文档 (qq.com)

微信小程序订阅消息接口:发送订阅消息 | 微信开放文档 (qq.com)

咱们需要做的就是把所有需要发送的内容信息变成如下的请求格式发送到微信的api即可

下边打开IDAE,创建工具类

package com.lbk.hcix.kcsjlbk.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;


import javax.swing.*;

/**
 * @Author LBK
 * @Date 2022/12/18 18:11
 */
public class WxUtil {





    /**
     * 获取小程序全局唯一后台接口调用凭据(access_token)
     * @return
     */
//    public static String getWxAccessToken(){
//        //从redis缓存中获取AccessToken,有且未过期,直接返回;否则重新获取
//        String accessToken =RedisManager.get("accessToken");
//        if(Tool.notEmpty(accessToken)){
//            return accessToken;
//        }
//        //重新获取accessToken,并存入redis
//        String newToken = getAccessToken();
//        //存入redis
//        RedisManager.set("accessToken", newToken, 7000);
//        return newToken;
//    }
    /**
     * 调用微信开放接口 获取小程序全局唯一后台接口调用凭据(access_token)
     * @return
     */
    public static String getAccessToken(){

        //String APPID=App.APPID;
        //String APPSECRET=App.APP_SECRET;
        String APPID="自己的id";
        String APPSECRET="自己的密钥";
        String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+APPID+"&secret="+APPSECRET;
        System.out.println("accessTokenUrl = " + accessTokenUrl);
        HttpClientUtil hru = new HttpClientUtil();
        String access_token = hru.sendHttpGet(accessTokenUrl);
        JSONObject jsonObject= JSON.parseObject(access_token);
        String token = jsonObject.get("access_token").toString();//获取access_token
//        if(Tool.isEmpty(access_token)){
//            access_token="";
//        }
//        System.out.println("json:"+json.toString());
        System.out.println("access_token = " + token);
        return token;
    }

    /**
     * 调用微信开放接口subscribeMessage.send发送订阅消息(固定模板的订阅消息)
     * POST https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN
     */
    public static void sendSubscribeMessage(String toUserOpenId){
        HttpURLConnection httpConn = null;
        InputStream is = null;
        BufferedReader rd = null;
        String accessToken = null;
        String str = null;
        try
        {
            //获取token  小程序全局唯一后台接口调用凭据
            accessToken = getAccessToken();

            JSONObject xmlData = new JSONObject();
            xmlData.put("touser", toUserOpenId);//接收者(用户)的 openid
            xmlData.put("template_id", "a9Nk8CNzZVmhn5QPIDOlWp7FhbvzDqPFTHVhH9CAgJY");//所需下发的订阅模板id
            xmlData.put("page", "pages/index/index");//点击模板卡片后的跳转页面,仅限本小程序内的页面
            xmlData.put("miniprogram_state", "developer");//跳转小程序类型:developer为开发版;trial为体验版;formal为正式版;默认为正式版
            xmlData.put("lang", "zh_CN");//进入小程序查看”的语言类型,支持zh_CN(简体中文)、en_US(英文)、zh_HK(繁体中文)、zh_TW(繁体中文),默认为zh_CN返回值

            /**
             * 订阅消息参数值内容限制说明
             thing.DATA:20个以内字符;可汉字、数字、字母或符号组合
             time.DATA:24小时制时间格式(支持+年月日),支持填时间段,两个时间点之间用“~”符号连接
             */

            JSONObject data = new JSONObject();
            //取餐号
            JSONObject character_string4 = new JSONObject();//character_string4必须和模板消息的字段id一致,以下同样,必须要一致,注意时间格式,详情看图二
            character_string4.put("value", "1001");
            data.put("character_string4", character_string4);
            //购买商品
            JSONObject thing5 = new JSONObject();
            thing5.put("value", "牛肉水饺");
            data.put("thing5", thing5);
            //温馨提示
            JSONObject thing11 = new JSONObject();
            thing11.put("value", "请到前台出示二维码取餐哦!");
            data.put("thing11", thing11);

            xmlData.put("data", data);//小程序模板数据


            System.out.println("发送模板消息xmlData:" + xmlData);
            URL url = new URL(
                    "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token="
                            + accessToken);
            httpConn = (HttpURLConnection)url.openConnection();
            httpConn.setRequestProperty("Host", "https://api.weixin.qq.com");
            // httpConn.setRequestProperty("Content-Length", String.valueOf(xmlData.));
            httpConn.setRequestProperty("Content-Type", "text/xml; charset=\"UTF-8\"");
            httpConn.setRequestMethod("POST");
            httpConn.setDoInput(true);
            httpConn.setDoOutput(true);
            OutputStream out = httpConn.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(out, "UTF-8");
            osw.write(xmlData.toString());
            osw.flush();
            osw.close();
            out.close();
            is = httpConn.getInputStream();
            rd = new BufferedReader(new InputStreamReader(is, "UTF-8"));

            while ((str = rd.readLine()) != null)
            {
                System.out.println("返回数据:" + str);
            }
        }
        catch (Exception e)
        {
            System.out.println("发送模板消息失败.." + e.getMessage());
        }
    }

    /**
     * 调用微信开放接口subscribeMessage.send发送订阅消息    通用类
     * POST https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN
     */
    public static void sendCommonSubscribeMessage(Map<String,Object> params,JSONObject data){
        HttpURLConnection httpConn = null;
        InputStream is = null;
        BufferedReader rd = null;
        String accessToken = null;
        String str = null;
        try
        {
            //获取token  小程序全局唯一后台接口调用凭据
            accessToken = getAccessToken();

            JSONObject xmlData = new JSONObject();
            xmlData.put("touser", params.get("touser"));//接收者(用户)的 openid
            xmlData.put("template_id", params.get("template_id"));//所需下发的订阅模板id
            xmlData.put("page", params.get("page"));//点击模板卡片后的跳转页面,仅限本小程序内的页面
            xmlData.put("miniprogram_state", params.get("miniprogram_state"));//跳转小程序类型:developer为开发版;trial为体验版;formal为正式版;默认为正式版
            xmlData.put("lang", "zh_CN");//进入小程序查看”的语言类型,支持zh_CN(简体中文)、en_US(英文)、zh_HK(繁体中文)、zh_TW(繁体中文),默认为zh_CN返回值
            xmlData.put("data", data);//小程序模板数据


            System.out.println("发送模板消息xmlData:" + xmlData);
            URL url = new URL(
                    "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token="
                            + accessToken);
            httpConn = (HttpURLConnection)url.openConnection();
            httpConn.setRequestProperty("Host", "https://api.weixin.qq.com");
            // httpConn.setRequestProperty("Content-Length", String.valueOf(xmlData.));
            httpConn.setRequestProperty("Content-Type", "text/xml; charset=\"UTF-8\"");
            httpConn.setRequestMethod("POST");
            httpConn.setDoInput(true);
            httpConn.setDoOutput(true);
            OutputStream out = httpConn.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(out, "UTF-8");
            osw.write(xmlData.toString());
            osw.flush();
            osw.close();
            out.close();
            is = httpConn.getInputStream();
            rd = new BufferedReader(new InputStreamReader(is, "UTF-8"));

            while ((str = rd.readLine()) != null)
            {
                System.out.println("返回数据:" + str);
            }
        }
        catch (Exception e)
        {
            System.out.println("发送模板消息失败.." + e.getMessage());
        }
    }

    public static void main(String[] args) {

        String openid = "需要接收订阅消息的openid";//需要该用户已经授权过该订阅消息才能发送
        sendSubscribeMessage(openid);//调用发送方法测试结果,数据是写死的,开发者可根据实际情况进行改写填充,真正调用只需把数据传入sendCommonSubscribeMessage方法即可

    }
}

实际使用只需要把接收方的信息,模板 信息设置好,调用即可

//设置接收订阅消息
        Map<String,Object> params=new HashMap<String, Object>();
        params.put("touser", 内容);//接收者(用户)的 openid
        params.put("template_id", "BTZydqCApnRtRdFgabCSd2wAVosyxLhV46wnEnO2tb4");//所需下发的订阅模板id
        params.put("page", "/pages/test2/index“);//点击模板卡片后的跳转页面,仅限本小程序内的页面
        params.put("miniprogram_state", "trial");//跳转小程序类型:developer为开发版;trial为体验版;formal为正式版;默认为正式版
        params.put("lang", "zh_CN");//进入小程序查看”的语言类型,支持zh_CN(简体中文)、en_US(英文)、zh_HK(繁体中文)、zh_TW(繁体中文),默认为zh_CN返回值

        /**
         * data:小程序模板数据
         * 订阅消息参数值内容限制说明
         thing.DATA:20个以内字符;可汉字、数字、字母或符号组合
         time.DATA:24小时制时间格式(支持+年月日),支持填时间段,两个时间点之间用“~”符号连接
         */
        JSONObject data = new JSONObject();
        //订单号
        JSONObject character_string3= new JSONObject();
        character_string3.put("value", 内容);
        data.put("character_string3", character_string3);
        //购买商品
        JSONObject thing6= new JSONObject();
        thing6.put("value",内容);
        data.put("thing6", thing6);
        //创建时间
        JSONObject time7 = new JSONObject();
        time7.put("value", 内容);
        data.put("time7", time7);
        //金额
        JSONObject amount4 = new JSONObject();
        amount4.put("value", 内容);
        data.put("amount4", amount4);

        WxUtil.sendCommonSubscribeMessage(params,data);//调用发送

发送http请求工具类HttpClientUtil

package com.lbk.hcix.kcsjlbk.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.util.PublicSuffixMatcher;
import org.apache.http.conn.util.PublicSuffixMatcherLoader;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * httpClient 工具类
 * @create 2019-02-10 下午 2:49
 */
@Component
public class HttpClientUtil {
    
    /**
     * 默认参数设置
     * setConnectTimeout:设置连接超时时间,单位毫秒。
     * setConnectionRequestTimeout:设置从connect Manager获取Connection 超时时间,单位毫秒。
     * setSocketTimeout:请求获取数据的超时时间,单位毫秒。访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。 暂时定义15分钟
     */
    private RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(600000).setConnectTimeout(600000).setConnectionRequestTimeout(600000).build();
    
    /**
     * 静态内部类---作用:单例产生类的实例
     * @author Administrator
     *
     */
    private static class LazyHolder {    
       private static final HttpClientUtil INSTANCE = new HttpClientUtil();    
       
    }  
    HttpClientUtil(){}
    public static HttpClientUtil getInstance(){
        return LazyHolder.INSTANCE;    
    }
    
    /**
     * 发送 post请求
     * @param httpUrl 地址
     */
    public String sendHttpPost(String httpUrl) {
        HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost  
        return sendHttpPost(httpPost);
    }
    
    /**
     * 发送 post请求
     * @param httpUrl 地址
     * @param params 参数(格式:key1=value1&key2=value2)
     */
    public String sendHttpPost(String httpUrl, String params) {
        HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost  
        try {
            //设置参数
            StringEntity stringEntity = new StringEntity(params, "UTF-8");
            stringEntity.setContentType("application/x-www-form-urlencoded");
            httpPost.setEntity(stringEntity);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sendHttpPost(httpPost);
    }
    
    /**
     * 发送 post请求
     * @param httpUrl 地址
     * @param maps 参数
     */
    public String sendHttpPost(String httpUrl, Map<String, String> maps) {
        HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost  
        // 创建参数队列  
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        for (String key : maps.keySet()) {
            nameValuePairs.add(new BasicNameValuePair(key, maps.get(key)));
        }
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sendHttpPost(httpPost);
    }
    
    /**
     * 发送Post请求
     * @param httpPost
     * @return
     */
    private String sendHttpPost(HttpPost httpPost) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        String responseContent = null;
        try {
            // 创建默认的httpClient实例
            httpClient = HttpClients.createDefault();
            httpPost.setConfig(requestConfig);
            // 执行请求
            long execStart = System.currentTimeMillis();
            response = httpClient.execute(httpPost);
            long execEnd = System.currentTimeMillis();
            System.out.println("=================执行post请求耗时:"+(execEnd-execStart)+"ms");
            long getStart = System.currentTimeMillis();
            entity = response.getEntity();
            responseContent = EntityUtils.toString(entity, "UTF-8");
            long getEnd = System.currentTimeMillis();
            System.out.println("=================获取响应结果耗时:"+(getEnd-getStart)+"ms");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭连接,释放资源
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseContent;
    }

    /**
     * 发送 get请求
     * @param httpUrl
     */
    public String sendHttpGet(String httpUrl) {
        HttpGet httpGet = new HttpGet(httpUrl);// 创建get请求
        return sendHttpGet(httpGet);
    }
    
    /**
     * 发送 get请求Https
     * @param httpUrl
     */
    public String sendHttpsGet(String httpUrl) {
        HttpGet httpGet = new HttpGet(httpUrl);// 创建get请求
        return sendHttpsGet(httpGet);
    }
    
    /**
     * 发送Get请求
     * @param httpGet
     * @return
     */
    private String sendHttpGet(HttpGet httpGet) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        String responseContent = null;
        try {
            // 创建默认的httpClient实例.

            
            httpClient = HttpClients.createDefault();

            httpGet.setConfig(requestConfig);
            // 执行请求
            response = httpClient.execute(httpGet);
            entity = response.getEntity();
            responseContent = EntityUtils.toString(entity, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭连接,释放资源
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseContent;
    }
    
    /**
     * 发送Get请求Https
     * @param httpGet
     * @return
     */
    private String sendHttpsGet(HttpGet httpGet) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        String responseContent = null;
        try {
            // 创建默认的httpClient实例.
            PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader.load(new URL(httpGet.getURI().toString()));
            DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher);
            httpClient = HttpClients.custom().setSSLHostnameVerifier(hostnameVerifier).build();
            httpGet.setConfig(requestConfig);
            // 执行请求
            response = httpClient.execute(httpGet);
            entity = response.getEntity();
            responseContent = EntityUtils.toString(entity, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭连接,释放资源
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseContent;
    }

    /**
     * 发送xml数据
     * @param url
     * @param xmlData
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static HttpResponse sendXMLDataByPost(String url, String xmlData)
            throws ClientProtocolException, IOException {
        HttpClient httpClient = HttpClients.createDefault();
        HttpPost httppost = new HttpPost(url);
        StringEntity entity = new StringEntity(xmlData);
        httppost.setEntity(entity);
        httppost.setHeader("Content-Type", "text/xml;charset=UTF-8");
        HttpResponse response = httpClient.execute(httppost);
        return response;
    }

    /**
     * 获得响应HTTP实体内容
     *
     * @param response
     * @return
     * @throws IOException
     * @throws UnsupportedEncodingException
     */
    public static String getHttpEntityContent(HttpResponse response) throws IOException, UnsupportedEncodingException {
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream is = entity.getContent();
            BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String line = br.readLine();
            StringBuilder sb = new StringBuilder();
            while (line != null) {
                sb.append(line + "\n");
                line = br.readLine();
            }
            return sb.toString();
        }
        return "";
    }


}
  • 2
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
要在Java实现小程序消息推送,你可以按照以下步骤进行操作: 1. 创建一个Vo类来封装传送的参数。你可以使用Lombok库来简化代码,例如创建一个名为TemplateDataVo的类,其中包含一个value属性用于封装消息内容。 2. 创建一个名为WxMssVo的类,用于封装小程序推送所需的数据。该类应包含以下属性: - touser:用户的openid - template_id:模板id - page:跳转路径(默认为小程序首页) - data:推送的消息内容,使用Map<String, TemplateDataVo>来封装 3. 在WxMssVo类中定义好属性后,你可以将其提供给Java的其他代码调用,或者提供一个接口供外界传入openid并推送相应的消息。 总结起来,你需要定义好Vo类来封装传送的参数,包括消息内容、用户openid、模板id等。然后,你就可以通过调用相关代码或提供接口来实现小程序消息推送功能。123 #### 引用[.reference_title] - *1* [java编写微信小程序消息提醒推送](https://blog.csdn.net/weixin_55823910/article/details/130558549)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}} ] [.reference_item] - *2* *3* [java实现小程序订阅消息推送(附源码)](https://blog.csdn.net/qq_41940721/article/details/119945990)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}} ] [.reference_item] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值