微信 模版消息 (六)

    xiaoxiao2025-08-13  10

    一、申请模板消息权限

    模板消息的申请需账号已经开通微信支付权限。

    在微信公众平台的后台,依次进入“功能->添加功能插件->模板消息”,即可申请模板消息。

    点击申请

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

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

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

    添加后就存放到“我的模板库”中了

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

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

    二、开发模板消息SDK

    模板消息的定义如下:

    模板消息也是使用access token作为授权来发送。

    获取access_token:连接

    三、构造模板消息体

    我们以一个消息品行业的购买成功通知的横版为例,它的内容如下。

    按照上述条件,我们构造消息体如下

    import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import net.sf.json.JSONObject; /** * 微信信息推送 * @author yuki_ho * */ public class PushMesgessUtil { private static String megstr2; private SimpleDateFormat sdf1=new SimpleDateFormat("HH点mm分"); private String wxmegurl="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="; private PushMesgessUtil(){} private static volatile PushMesgessUtil instance =null; public static PushMesgessUtil getInstance(){ if(instance==null){ synchronized(PushMesgessUtil.class){ if(instance==null){ instance=new PushMesgessUtil(); megstr2=loadJson("/wxtemplate/wxtemplate2.json"); // 替换模版 } } } return instance; } private static String loadJson(String jsonurl){ String path=PushMesgessUtil.class.getResource("/").getPath()+jsonurl; String jsonString=""; try { FileInputStream fileInputStream=new FileInputStream(path); InputStreamReader inputStreamReader=new InputStreamReader(fileInputStream,"UTF-8"); BufferedReader reader=new BufferedReader(inputStreamReader); String tempString=null; while((tempString=reader.readLine())!=null) jsonString+=tempString; reader.close(); } catch (Exception e) { e.printStackTrace(); } return jsonString; } public JSONObject sendResMeg(String towxid,String userName,String status){ String gourl="点击信息名片跳转地址"; String url=wxmegurl+"你的access_token"; String jsonText=megstr2.replace("OPENID", "接受人id") .replace("TEMPLATE_ID","微信官网生成的模版id") .replace("GOURL", gourl) .replace("FIRST", "尊敬的"+userName+",您已成为工程师!") .replace("USERNAME", userName) .replace("DULETIME", sdf1.format(new Date())) .replace("REMARK", "如有疑问,请致电:xxxxxx,祝你生活愉快!"); JSONObject jsonObject=JSONObject.fromObject(jsonText); return HttpClientUtil.httpRequest(url, EnumMethod.POST.name(), jsonObject.toString()); } public static void main(String[] args) { } } JSON文件: { "touser":"OPENID", "template_id":"TEMPLATE_ID", "url":"GOURL", "topcolor":"#FF0000", "data":{ "first": { "value":"FIRST", "color":"#173177" }, "keyword1": { "value":"USERNAME", "color":"#173177" }, "keyword2": { "value":"DULETIME", "color":"#173177" }, "remark": { "value":"REMARK", "color":"#008000" } } } 帮助类(HttpClientUtil): 连接
    转载请注明原文地址: https://ju.6miu.com/read-1301705.html
    最新回复(0)