微信发送模板消息

Posted For_elegant

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了微信发送模板消息相关的知识,希望对你有一定的参考价值。

模板消息仅用于公众号向用户发送重要的服务通知,只能用于符合其要求的服务场景中,如信用卡刷卡通知,商品购买成功通知等。不支持广告等营销类消息以及其它所有可能对用户造成骚扰的消息。

 

关于使用规则,请注意:
1、所有服务号都可以在功能->添加功能插件处看到申请模板消息功能的入口,但只有认证后的服务号才可以申请模板消息的使用权限并获得该权限;
2、需要选择公众账号服务所处的2个行业,每月可更改1次所选行业;
3、在所选择行业的模板库中选用已有的模板进行调用;
4、每个账号可以同时使用25个模板。
5、当前每个账号的模板消息的日调用上限为10万次,单个模板没有特殊限制,以公众号MP后台开发者中心页面中标明的数字为准。

 

关于接口文档,请注意:

1、模板消息调用时主要需要模板ID和模板中各参数的赋值内容;
2、模板中参数内容必须以".DATA"结尾,否则视为保留字;

3、模板保留符号"{{ }}"。

 

模板申请成功之后直接新增不需要额外配置的,如果是在测试号中测试的,复制粘贴的时候要注意以上注意项

以下是我使用的模板消息

 

[plain] view plain copy
 
 print?
  1. {{first.DATA}}  
  2. 旅行活动名称:{{keyword1.DATA}}  
  3. 订单金额:{{keyword2.DATA}}  
  4. 旅行时间:{{keyword3.DATA}}  
  5. 参与人数:{{keyword4.DATA}}  
  6. {{remark.DATA}}  

官方的demo

 

[plain] view plain copy
 
 print?
  1. POST数据示例如下:  
  2.       {  
  3.            "touser":"OPENID",  
  4.            "template_id":"ngqIpbwh8bUfcSsECmogfXcV14J0tQlEpBO27izEYtY",  
  5.            "url":"http://weixin.qq.com/download",              
  6.            "data":{  
  7.                    "first": {  
  8.                        "value":"恭喜你购买成功!",  
  9.                        "color":"#173177"  
  10.                    },  
  11.                    "keynote1":{  
  12.                        "value":"巧克力",  
  13.                        "color":"#173177"  
  14.                    },  
  15.                    "keynote2": {  
  16.                        "value":"39.8元",  
  17.                        "color":"#173177"  
  18.                    },  
  19.                    "keynote3": {  
  20.                        "value":"2014年9月22日",  
  21.                        "color":"#173177"  
  22.                    },  
  23.                    "remark":{  
  24.                        "value":"欢迎再次购买!",  
  25.                        "color":"#173177"  
  26.                    }  
  27.            }  
  28.        }  

1.根据官方实例创建参数的Bean

[java] view plain copy
 
 

package cn.com.taiji.oosweb.httpserver;

public class TemplateData {
private String value;
private String color;

public String getValue() {
return value;
}

public void setValue(String value) {
this.value = value;
}

public String getColor() {
return color;
}

public void setColor(String color) {
this.color = color;
}
}


[java] view plain copy
 
 

package cn.com.taiji.oosweb.httpserver;

import java.util.Map;

public class WechatTemplate {
private String touser; //openId

private String template_id;

private String url;

private Map<String, TemplateData> data;

public String getTouser() {
return touser;
}

public void setTouser(String touser) {
this.touser = touser;
}

public String getTemplate_id() {
return template_id;
}

public void setTemplate_id(String template_id) {
this.template_id = template_id;
}

public String getUrl() {
return url;
}

public void setUrl(String url) {
this.url = url;
}

public Map<String, TemplateData> getData() {
return data;
}

public void setData(Map<String, TemplateData> data) {
this.data = data;
}
}

创建工具类NetTools:

package cn.com.taiji.oosweb.web.wx.authdeny;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import net.sf.json.JSONObject;

public class NetTools {
/**
* 发送https请求
*
* @param requestUrl 请求地址
* @param requestMethod 请求方式(GET、POST)
* @param outputStr 提交的数据
* @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
*/
public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
JSONObject jsonObject = null;
try {
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();

URL url = new URL(requestUrl);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(ssf);

conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
// 设置请求方式(GET/POST)
conn.setRequestMethod(requestMethod);

// 当outputStr不为null时向输出流写数据
if (null != outputStr) {
OutputStream outputStream = conn.getOutputStream();
// 注意编码格式
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}

// 从输入流读取返回内容
InputStream inputStream = conn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
StringBuffer buffer = new StringBuffer();
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}

// 释放资源
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
inputStream = null;
conn.disconnect();
jsonObject = JSONObject.fromObject(buffer.toString());
} catch (ConnectException ce) {
System.out.println("连接异常,超时;"+ce.getMessage());
} catch (Exception e) {
System.out.println("https请求异常:"+e.getMessage());
}
return jsonObject;
}
}

方法测试类main:

package cn.com.taiji.oosweb.httpserver;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

 

 

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.taiji.oosweb.manager.helper.JsonUtil;
import cn.com.taiji.oosweb.web.wx.authdeny.MyX509TrustManager;
import cn.com.taiji.oosweb.web.wx.authdeny.NetTools;


import net.sf.json.JSONObject;

import com.google.gson.Gson;

public class method {
static String appsecret ="";
static String appId ="";

public static void main(String[] args) {
appId = "wx2faec6d97bb8d50a";
appsecret = "ed4a837d65d26018e4eb96cc1006c078";
String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
//获取access_token
requestUrl = requestUrl.replace("APPID", appId);
requestUrl = requestUrl.replace("APPSECRET", appsecret);
JSONObject jsonObject = NetTools.httpsRequest(requestUrl, "GET", null);
String access_token = (String) jsonObject.get("access_token");
//获取行业信息
String hyxxUrl = "https://api.weixin.qq.com/cgi-bin/template/get_industry?access_token=ACCESS_TOKEN";
hyxxUrl = hyxxUrl.replace("ACCESS_TOKEN", access_token);
JSONObject hyxx = NetTools.httpsRequest(hyxxUrl, "GET", null);
String primary_industry = (String) JsonUtil.getJSONObject(hyxx.get("primary_industry").toString()).get("first_class");
//获取模板id,此处使用的是POST方式提交,使用工具类NetTools时放参数的格式如下
String mbIdUrl = "https://api.weixin.qq.com/cgi-bin/template/api_add_template";
JSONObject mbId = NetTools.httpsRequest(mbIdUrl, "POST", "access_token="+access_token+"&template_id_short=TM00050");
//获取模板列表
String mblbUrl = "https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token=ACCESS_TOKEN";
hyxxUrl = mblbUrl.replace("ACCESS_TOKEN", access_token);
JSONObject mblb = NetTools.httpsRequest(hyxxUrl, "GET", null);


String accessToken =access_token;
WechatTemplate wechatTemplate = new WechatTemplate();
wechatTemplate.setTemplate_id((String)mbId.get("template_id"));
wechatTemplate.setTouser("wd6wkXKIQf5qGBfYB_MFZ8w");
wechatTemplate.setUrl("http://music.163.com/#/song?id=27867140");

Map<String,TemplateData> m = new HashMap<String,TemplateData>();
TemplateData first = new TemplateData();
first.setColor("#000000");
first.setValue("您的户外旅行活动订单已经支付完成,可在我的个人中心中查看。");
m.put("first", first);

TemplateData keyword1 = new TemplateData();
keyword1.setColor("#000000");
keyword1.setValue("1.2发现尼泊尔—人文与自然的旅行圣地 ");
m.put("keyword1", keyword1);

TemplateData keyword2 = new TemplateData();
keyword2.setColor("#000000");
keyword2.setValue("5000元");
m.put("keyword2", keyword2);

TemplateData keyword3 = new TemplateData();
keyword3.setColor("#000000");
keyword3.setValue("2017.1.2");
m.put("keyword3", keyword3);

TemplateData keyword4 = new TemplateData();
keyword4.setColor("#000000");
keyword4.setValue("5");
m.put("keyword4", keyword4);

TemplateData remark = new TemplateData();
remark.setColor("#000000");
remark.setValue("请届时携带好身份证件准时到达集合地点,若临时退改将产生相应损失,敬请谅解,谢谢!");
m.put("remark", remark);
wechatTemplate.setData(m);
try {
sendTemplateMessage(accessToken, wechatTemplate);
} catch (Exception e) {
// logger.info("异常"+e.getMessage());
}

}
private final static String SEND_TEMPLAYE_MESSAGE_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";

public static void sendTemplateMessage(String accessToken, WechatTemplate wechatTemplate) {
String jsonString = new Gson().toJson(wechatTemplate).toString();
// System.err.println("-------"+jsonString);
String requestUrl = SEND_TEMPLAYE_MESSAGE_URL.replace("ACCESS_TOKEN", accessToken);
JSONObject failOrsucess = NetTools.httpsRequest(requestUrl, "POST",jsonString );
System.err.println(failOrsucess);




}


public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr)
{
JSONObject jsonObject = null;
StringBuffer buffer = new StringBuffer();
try
{
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new SecureRandom());

SSLSocketFactory ssf = sslContext.getSocketFactory();

URL url = new URL(requestUrl);
HttpsURLConnection httpUrlConn = (HttpsURLConnection)url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);

httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);

httpUrlConn.setRequestMethod(requestMethod);

if ("GET".equalsIgnoreCase(requestMethod)) {
httpUrlConn.connect();
}

if (outputStr != null) {
OutputStream outputStream = httpUrlConn.getOutputStream();

outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}

InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();

inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
// jsonObject = JSON.parseObject(buffer.toString());
// jsonObject = JSONObject.fromObject(buffer.toString());
} catch (ConnectException ce) {
// logger.error("Weixin server connection timed out.");
} catch (Exception e) {
// logger.error("https request error:{}", e);
}
return jsonObject;
}
}





























































































































































































































































































以上是关于微信发送模板消息的主要内容,如果未能解决你的问题,请参考以下文章

消息推送之微信模板消息

主动发送微信公众平台“模板消息”需要啥条件?

微信发送模板消息

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

微信开发-- 发送模板消息

php之微信公众号发送模板消息