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

        微信小程序订阅消息分为一次性订阅与长期订阅,长期订阅为政务、民生行业使用,在开发订阅消息时,遇到较多的问题是模板审核不通过,在网上查找资料得知,模板申请一般是审核不下来的,较多的情况是在小程序提供的公共模板库中选择适合的模板,微信小程序订阅消息简单的流程如下:

        1、登录微信公众平台;

        2、在订阅消息一次性订阅公共模板库中选择适合的模板;

        3、小程序调用wx.requestSubscribeMessage打开订阅询问框(在不弹框的情况下查找资料发现弹框在某个场景的方法里面调用而不是直接通过用户点击,这里使用在用户再用切换导航栏点击后加载页面时触发);

        4、用户选择接受对应的消息模板;

        5、Java后台调用接口发送订阅消息;

        实现代码:

         1、  小程序添加tab监听事件:

onTabItemTap: function (item) {
      tmplIds: ['xxxxxxxx','xxxxx'], // 模板id数组
      success (res) {
        console.log(res);
      },
      fail (error) {
        console.log(error);
      }
    })
 },

          2、用户切换导航菜单,弹窗询问框并点击允许:

         3、Java后台发送调用微信https://api.weixin.qq.com/cgi-bin/token接口获取access_token:

   /**
     * 调用微信开放接口 获取小程序全局唯一后台接口调用凭据(access_token)
     * @return 调用凭据
     */
    public static String getAccessToken(String appid, String appsecret){
        HttpClient httpClient = HttpClientBuilder.create().build();
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+appsecret;
        HttpGet request = new HttpGet(url);
        try {
            HttpResponse response = httpClient.execute(request);
            InputStreamReader inputStreamReader = new InputStreamReader(response.getEntity().getContent());
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            StringBuffer sb = new StringBuffer();
            String line = "";
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }
            String str = sb.toString();
            Map maps = (Map) JSON.parse(str);
            String string = maps.get("access_token").toString();
            return string;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

         4、Java发送订阅消息:

private Result sendMessage() throws IOException {
    InputStream is = null;
    BufferedReader rd = null;
    // 发送参数
    JSONObject xmlData = new JSONObject();
    xmlData.put("touser", openId);//接收者(用户)的 openid
    xmlData.put("template_id", templateId);//所需下发的订阅模板id
    xmlData.put("page", "pages/home/home");//点击模板卡片后的跳转页面,仅限本小程序内的页面
    xmlData.put("miniprogram_state", "formal");//跳转小程序类型:developer为开发版;trial为体验版;formal为正式版;默认为正式版
    xmlData.put("lang", "zh_CN");//进入小程序查看”的语言类型,支持zh_CN(简体中文)、en_US(英文)、zh_HK(繁体中文)、zh_TW(繁体中文),默认为zh_CN返回值
    // 设置参数
    JSONObject data = new JSONObject();
    JSONObject param = new JSONObject();
    param.put("value", value);
    data.put("thing1", param); // thing1为模板参数
    xmlData.put("data", data);
    log.info("发送模板消息xmlData:{}", xmlData);
    // 获取微信小程序token
    String accessToken = WxUtils.getAccessToken(wxConfig.getAppid(), wxConfig.getSecret());
    URL url = new URL("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken);
    HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
    httpConn.setRequestProperty("Host", "https://api.weixin.qq.com");
    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"));
	Map mapResult = JSONObject.parseObject(rd.readLine(), Map.class);
	if(mapResult.get("errcode").toString().equals("0") && mapResult.get("errmsg").toString().equals("ok")) {
		return Result.ok(mapResult);
	}
	return Result.error("小程序消息发送失败", mapResult);
}

        返回成功,小程序将受到消息通知。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

星辰寰宇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值