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

一、创建订阅消息模板

        1.登入微信公众平台: https://mp.weixin.qq.com/

        2.创建消息模板

        

        勾选右侧需要的关键字

        

     

 

二、代码实现

     1.小程序代码

      错误:errcode":43101 需要小程序允许接收通知才行,允许一次可发送一次,允许可叠加

//tmplIds模板id(一次订阅可能有多个id','隔开)
wx.requestSubscribeMessage({
      tmplIds: [''],
      success (res) { }
    })

    2.java 后端代码

        2.1 获取 AccessToken

        请求url:https://api.weixin.qq.com/cgi-bin/token

        官方文档: auth.getAccessToken | 微信开放文档 (qq.com) 

        doGet是我自己封装的请求

 

    public String getAccessToken(){
        String appid="";//小程序appid
        String appSecret="";//小程序密钥
        String url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+appSecret;

        String token="";
        try {
            token= doGetPost(url,"GET",null);
            //处理返回的值
            JSONObject tokenJson = JSONObject.parseObject(token);
            token = tokenJson.get("access_token").toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return token;
    }

     2.2 发送消息模板

        请求url:https://api.weixin.qq.com/cgi-bin/message/subscribe/send

        官方文档:subscribeMessage.send | 微信开放文档 (qq.com)

        我没有封装消息模板的详细内容参数,就直接json.parse

        模板文字描述参数根据模板详情的详细内容来改以此类推

        

 public Object text(){
        String accessToken=getAccessToken();//获取accessToken
        //模板文字描述参数
        Object data="{\"thing1\":{\"value\":\"日常保洁\"},\"thing2\":{\"value\":\"小红\"},\"phone_number3\":{\"value\":\"12345678900\"} }";
        //请求路径
        String url="https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token="+accessToken;
        //参数
        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("touser","");//接收者openid
        paramMap.put("template_id","");//所需下发的订阅模板id
        paramMap.put("page","pages/index/index");//点击模板卡片后的跳转页面,仅限本小程序内的页面。支持带参数,
        paramMap.put("data",JSON.parse(data.toString()));//模板内容,格式形如 { "key1": { "value": any }, "key2": { "value": any } } 
        Object o= null;
        try {
            o = doGetPost(url,"POST",paramMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return o;
    }

 

 public String doGetPost(String apiUrl,String methodType,Map<String,Object> map){

        OutputStreamWriter outputStreamWriter = null;
        InputStream inputStream = null;
        String result = null;
        try{
            URL url = new URL(apiUrl);// 创建连接
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setUseCaches(false);
            httpURLConnection.setInstanceFollowRedirects(true);
            httpURLConnection.setRequestMethod(methodType) ;
            httpURLConnection.setRequestProperty("Accept", "application/json");
            httpURLConnection.setRequestProperty("Content-Type", "application/json"); 
            httpURLConnection.connect();

            if(methodType.equals("POST")){
                outputStreamWriter = new OutputStreamWriter(httpURLConnection.getOutputStream(), "UTF-8"); 
                outputStreamWriter.append(JSON.toJSONString(map));
                outputStreamWriter.flush();
                outputStreamWriter.close();
            }
            // 读取响应
            inputStream = httpURLConnection.getInputStream();
            int length = (int) httpURLConnection.getContentLength();
            if (length != -1) {
                byte[] data = new byte[length];
                byte[] t = new byte[512];
                int len = 0;
                int pos = 0;
                while ((len = inputStream.read(t)) > 0) {
                    System.arraycopy(t, 0, data, pos, len);
                    pos += len;
                }
                result = new String(data, "UTF-8");

            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return  result;
    }

 

 

 

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值