您的位置:首页 > 移动开发 > 微信开发

微信公众平台开发-发送模板消息

2017-04-06 09:39 471 查看
微信公众账号开发-发送模板消息:

 

内容概要

本篇文章主要叙述如何在微信公众帐号上实现“发送模板消息开发”功能。包含json的封装与解析。

 

何谓模板消息

为了保证用户不受到骚扰,在开发者出现需要主动提醒、通知用户时,才允许开发者在公众平台网站中模板消息库中选择模板,选择后获得模板ID,再根据模板ID向用户主动推送提醒、通知消息。

 

注意:模板消息只能开发者主动向微信用户发送,不能有用户被动发起。

 

寻找接口(数据源)

开发者需向微信服务器发送post请求,并携带根据模板配装好的一个json包。

请求地址:

https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN

json格式:

 

参考微信接口文档https://mp.weixin.qq.com/advanced/tmplmsg?action=faq&token=663979174&lang=zh_CN

 

开发步骤

1) 获取模板ID

2) 构造模版消息体并请求接口

 

代码及实现

获取模板id:

1、具有支付能力的公众号才可以使用模板消息进行服务。在微信公众平台的后台,依次进入“功能->添加功能插件->模版消息”,即可申请模版消息。



点击申请



申请时,选择2个和自己相关的两个行业即可。



提交并且申请通过后,可以在模版库中看到模版消息列表



进入想使用的模板,点击添加



添加后就存到“我的模板库”中了(每个账号可以最多可以添加10个模板到“我的模板库”中)



查看模版的详情,可以看到模版id及各项内容参数名。



不同的模版消息的内容结构不一样。这些id及字段名将在程序中使用到。

 

 

 

 

注意:如果模板库中没有你想使用的模板时,可以在模板库页面点击“帮助我们完善模板库”创建自己的消息模板,创建消息模板需要申请,审核通过后该模板将被添加到该行业的模板库中。每个账号每月只能申请3个模板。



点击帮助我们完善模板库

 


 

 

 

代码实现(Java,建议将代码复制到Eclipse编辑器,看起来效果就不凌乱了):

 

1、构造模板体(json包),以交易提醒模板为例,这里封装成一个TradingNotice类。构造该类时需传入接收者微信的openid、模板id、模板主体颜色、用户名。代码中采用LinkedHashMap是为了保证数据是以存入的顺序排序,从而保证json格式的结构不被打乱。

import java.util.LinkedHashMap;

import java.util.Map;

 

public classTradingNotice {

   privateMap<String,Object>map;

   privateMap<String,Object>data;

  

   public TradingNotice(Stringtouser, String template_id, Stringurl, String topcolor,Stringuser)
{

      map=newLinkedHashMap<String, Object>();

      data=newLinkedHashMap<String, Object>();

     

      LinkedHashMap<String,String>first=newLinkedHashMap<String,String>();

      first.put("value","尊敬的" +user + ":\n\n您尾号为0426的招商银行卡最近有一笔交易(测试)");

      first.put("color","#743A3A");

      data.put("first",first);

 

      LinkedHashMap<String,String>keyword1=newLinkedHashMap<String,String>();

      keyword1.put("value","YXJ134953845");

      keyword1.put("color","#FF0000");

      data.put("keyword1",keyword1);

 

      LinkedHashMap<String,String>keyword2=newLinkedHashMap<String,String>();

      keyword2.put("value","2014/08/18 13:18");

      keyword2.put("color","#C4C400");

      data.put("keyword2",keyword2);

 

      LinkedHashMap<String,String>keyword3=newLinkedHashMap<String,String>();

      keyword3.put("value","1888888888");

      keyword3.put("color","#0000FF");

      data.put("keyword3",keyword3);

 

      LinkedHashMap<String,String>keyword4=newLinkedHashMap<String,String>();

      keyword4.put("value","消费");

      keyword4.put("color","#008000");

      data.put("keyword4",keyword4);

     

      LinkedHashMap<String,String>keyword5=newLinkedHashMap<String,String>();

      keyword5.put("value","26万元");

      keyword5.put("color","#008000");

      data.put("keyword5",keyword5);

 

      LinkedHashMap<String,String>remark=newLinkedHashMap<String,String>();

      remark.put("value","\n\n截止2014/08/18 13:18您招商信用账户可用余额未20000元");

      remark.put("color","#000000");

      data.put("remark",remark);

 

      map.put("touser",touser);

      map.put("template_id",template_id);

      map.put("url",url);

      map.put("topcolor",topcolor);

      map.put("data",data);

   }

 

   public Map<String,Object> getMap() {

      return map;

   }

 

   public void setMap(Map<String,Object> map){

      this.map =map;

   }

 

   public Map<String,Object> getDate() {

      return data;

   }

 

   public void setDate(Map<String,Object> date){

      this.data =date;

   }

}

 

2、方法create_TN_Json用来构造json包,方法getUserData用来获取关注者昵称,需传入客户的openid。方法getUserList用来获取微信关注者列表,将所有关注者的openid保存在一个ArrayList中。由于获取关注者列表一次只能获取1000个微信号,所以当关注者多余1000的时候循环调用方法getUserJson来获取所有关注者账号。

获取关注这列表可参考微信公众平台接口文档,地址http://mp.weixin.qq.com/wiki/index.php?title=获取关注者列表

方法send_Json用来发送模板消息请求,必须采用post请求

 

import java.io.BufferedReader;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.io.OutputStreamWriter;

import java.NET.HttpURLConnection;

import java.Net.URL;

import java.util.ArrayList;

import java.util.Iterator;

 

import wx.sunl.menus.Get_Token;

import wx.sunl.template.TradingNotice;

import net.sf.json.JSONObject;

 

public classCreate_Json {

   //获取交易提醒json;

   public static JSONObjectcreate_TN_Json(String touser,String user){

      JSONObjectjsonObject=null;

      //模板id

      Stringtemplate_id="15Eox4OfGsjFYaVRwk9Dbos_aaIkzveCkpG3AsnKqLA";

      //点击模板后的链接地址

      Stringurl="www.baidu.com";

      //模板的主题颜色

      Stringtopcolor="#008000";

      //构造json

      TradingNoticewn = new TradingNotice(touser,template_id,url,topcolor,user);

      jsonObject=JSONObject.fromObject(wn.getMap());

      return jsonObject;

   }

   //入口;

   public static void main(String[] args){

      //检查access_token是否过期,如果过期重新产生

      //Get_Token.TwoDate();

      //调用getUserList获取关注者列表

      ArrayList<String>users= getUserList();

      if(users!=null){

         Iterator<String>user=users.iterator();

         JSONObjectjsonObject1=null;

         Stringopen_id= null;

         StringuserName= null;

         while(user.hasNext()){

            open_id = user.next();

            //调用getUserData获取关注者昵称

            userName = getUserData(open_id);

            if(userName!=null){

                //创建交易提醒json包;

                jsonObject1 = Create_Json.create_TN_Json(open_id,userName);

                //发送交易提醒模板消息;

                send_Json(jsonObject1.toString(),Get_Token.access_token);

            }

         }

      }

   }

  

   //获取用户基本信息(UnionID机制);

   public static StringgetUserData(String openid){

        StringBuffer bufferRes =new StringBuffer();

        String result=null;

        try {

                URL realUrl = new URL("https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + Get_Token.access_token +"&openid=" + openid+"&lang=zh_CN");

                HttpURLConnection conn = (HttpURLConnection)realUrl.openConnection();

                // 请求方式

                conn.setDoOutput(true);

                conn.setDoInput(true);

                conn.setRequestMethod("GET");

                conn.setUseCaches(false);

                conn.setInstanceFollowRedirects(true);

                conn.setRequestProperty("Content-Type","application/json");

                conn.connect();

                // 获取URLConnection对象对应的输入流

                InputStream in =conn.getInputStream();

                BufferedReader read =new BufferedReader(new InputStreamReader(in,"UTF-8"));

                String valueString =null;

                while ((valueString=read.readLine())!=null){

                        bufferRes.append(valueString);

                }

                System.out.println(bufferRes);

                in.close();

                if (conn !=null){

                    // 关闭连接

                    conn.disconnect();

                }

        } catch (Exceptione) {

                e.printStackTrace();

        }

        //将返回的字符串转换成json

        JSONObject jsonObject = JSONObject.fromObject(bufferRes.toString());

        //解析json中的数据

        String subscribe = jsonObject.get("subscribe").toString();

        //等于1表示有关注者,0表示没有关注者

        if("1".equals(subscribe.toString())){

          //解析出关注者的昵称

          result = (String)jsonObject.get("nickname");

        }

        returnresult;

   }

  

   //获取关注列表;

   @SuppressWarnings("unchecked")

   public static ArrayList<String>getUserList() {

        StringBuffer bufferRes =new StringBuffer();

        ArrayList<String> users =null;

        try {

                URL realUrl = new URL("https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + Get_Token.access_token);

                HttpURLConnection conn = (HttpURLConnection)realUrl.openConnection();

                // 请求方式

                conn.setDoOutput(true);

                conn.setDoInput(true);

                conn.setRequestMethod("GET");

                conn.setUseCaches(false);

                conn.setInstanceFollowRedirects(true);

                conn.setRequestProperty("Content-Type","application/json");

                conn.connect();

                // 获取URLConnection对象对应的输入流

                InputStream in =conn.getInputStream();

                BufferedReader read =new BufferedReader(new InputStreamReader(in,"UTF-8"));

                String valueString =null;

                while ((valueString=read.readLine())!=null){

                        bufferRes.append(valueString);

                }

                System.out.println(bufferRes);

                in.close();

                if (conn !=null){

                    // 关闭连接

                    conn.disconnect();

                }

        } catch (Exceptione) {

                e.printStackTrace();

        }

        //将返回的字符串转换成json

        JSONObject jsonObject = JSONObject.fromObject(bufferRes.toString());

        //解析json中表示openid的列表

        JSONObject data = (JSONObject)jsonObject.get("data");

        if(data!=null){

          //将openid列表转化成数组保存

          users = newArrayList<String>(data.getJSONArray("openid"));

          //获取关注者总数

          intcount = Integer.parseInt(jsonObject.get("total").toString());

          if(count>1000){

             JSONObjectobject=jsonObject;

             Stringnext_openid=null;

             JSONObjectob_data=null;

             ArrayList<String>ob_user=null;

             //大于1000需要多次获取,或许次数为count/1000

             for(inti=0;i<count/1000;i++){

                //解析出下次获取的启示openid

                next_openid = object.get("next_openid").toString();

                object = getUserJson(next_openid);

                ob_data = (JSONObject)object.get("data");

                ob_user = newArrayList<String>(ob_data.getJSONArray("openid"));

                for(Stringopen_id : ob_user){

                    //将多次获取的openid添加到同一个数组

                    users.add(open_id);

                }

            }

          }

        }

        returnusers;

   }

   

   //连续获取关注列表;

   public static JSONObjectgetUserJson(String next_openid) {

        StringBuffer bufferRes =new StringBuffer();

        try {

                URL realUrl = new URL("https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + Get_Token.access_token +"&next_openid=" + next_openid);

                HttpURLConnection conn = (HttpURLConnection)realUrl.openConnection();

                // 请求方式

                conn.setDoOutput(true);

               conn.setDoInput(true);

                conn.setRequestMethod("GET");

                conn.setUseCaches(false);

                conn.setInstanceFollowRedirects(true);

                conn.setRequestProperty("Content-Type","application/json");

               conn.connect();

                // 获取URLConnection对象对应的输入流

                InputStream in =conn.getInputStream();

                BufferedReader read =new BufferedReader(new InputStreamReader(in,"UTF-8"));

                String valueString =null;

                while ((valueString=read.readLine())!=null){

                        bufferRes.append(valueString);

                }

                System.out.println(bufferRes);

                in.close();

                if (conn !=null){

                    // 关闭连接

                    conn.disconnect();

                }

        } catch (Exceptione) {

                e.printStackTrace();

        }

       

        JSONObject jsonObject = JSONObject.fromObject(bufferRes);

        returnjsonObject;

   }

  

   //发送模板;

   publicstaticvoidsend_Json(Stringparams,StringaccessToken){

        StringBuffer bufferRes =new StringBuffer();

        try {

                URL realUrl = new URL("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+accessToken);

                HttpURLConnection conn = (HttpURLConnection)realUrl.openConnection();

                // 请求方式

                conn.setDoOutput(true);

                conn.setDoInput(true);

                conn.setRequestMethod("POST");

                conn.setUseCaches(false);

                conn.setInstanceFollowRedirects(true);

                conn.setRequestProperty("Content-Type","application/json");

                conn.connect();

                // 获取URLConnection对象对应的输出流

                OutputStreamWriter out =new OutputStreamWriter(conn.getOutputStream(),"UTF-8");

                // 发送请求参数

                //out.write(URLEncoder.encode(params,"UTF-8"));

                //发送json

                out.write(params);

               out.flush();

                out.close();

                InputStream in =conn.getInputStream();

                BufferedReader read =new BufferedReader(new InputStreamReader(in,"UTF-8"));

                String valueString =null;

                while ((valueString=read.readLine())!=null){

                        bufferRes.append(valueString);

                }

                //输出返回的json

                System.out.println(bufferRes);

                in.close();

                if (conn !=null){

                    // 关闭连接

                    conn.disconnect();

                }

        } catch (Exceptione) {

                e.printStackTrace();

        }

   }

}

 

 

 

注意:

创建json包时要根据模板内容构造。

列如:交易提醒创建的json为:

{"touser":"",

"template_id":"",

"url":"",

"topcolor":"",

"data":{

"first":{"value":"","color":""},

"keyword1":{"value":"","color":""},

"keyword2":{"value":"","color":""},

"keyword3":{"value":"","color":""},

"keyword4":{"value":"","color":""},

"keyword5":{"value":"","color":""},

"remark":{"value":"","color":""}}}

 

笔试通知提醒创建的json为:

{"touser":"",

"template_id":"",

"url":"",

"topcolor":"",

"data":{

"first":{"value":"","color":""},

"company":{"value":"","color":""},

"datetime":{"value":"","color":""},

"address":{"value":"","color":""},

"contact":{"value":"","color":""},

"remark":{"value":"","color":""}}}

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: