模版消息的推送:
微信文档:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1433751277
需要的参数:
AppID; AppSecret; 模版id; 用户openid; ( 发送的数据:data )
1. 推送模版消息首先要获取商户的access_token
(access_token是公众号的全局唯一接口调用凭据,公众号调用各接口时都需使用access_token。开发者需要进行妥善保存。access_token的存储至少要保留512个字符空间。access_token的有效期目前为2个小时,需定时刷新,重复获取将导致上次获取的access_token失效。)
获取access_token
接口调用请求说明
https请求方式: GET
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
参数 | 是否必须 | 说明 |
grant_type | 是 | 获取access_token填写client_credential |
appid | 是 | 第三方用户唯一凭证 |
secret | 是 | 第三方用户唯一凭证密钥,即appsecret |
返回参数:{"access_token":"ACCESS_TOKEN","expires_in":7200}
代码:
String access_token = getAccess_token("APPID", "AppSecret");//封装方法
public String getAccess_token(String AppId, String AppSecret) throws Exception {
String getAccess_token = "https://api.weixin.qq.com/cgi-bin/token";
Map<String, Object> getMap = new HashMap<String, Object>();
getMap.put("grant_type", "client_credential");
getMap.put("appid", AppId);
getMap.put("secret", AppSecret);
String access_token = HttpMethodClient.sendGet(getAccess_token, getMap);
return access_token;
}
2. 发送模版消息:
接口调用请求说明
http请求方式: POST
https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN
参数 | 是否必填 | 说明 |
touser | 是 | 接收者openid |
template_id | 是 | 模板ID |
url | 否 | 模板跳转链接 |
miniprogram | 否 | 跳小程序所需数据,不需跳小程序可不用传该数据 |
appid | 是 | 所需跳转到的小程序appid(该小程序appid必须与发模板消息的公众号是绑定关联关系) |
pagepath | 否 | 所需跳转到小程序的具体页面路径,支持带参数,(示例index?foo=bar) |
data | 是 | 模板数据 |
color | 否 | 模板内容字体颜色,不填默认为黑色 |
封装要发送的数据(这个对格式要求特别厉害)
不同的模版data不同
代码:
1. 需要的子类:
package com.enation.app.shop.component.template.model;
/**
* 微信模版需要的数据
* @author yh
*/
public class TemplateParam {
// 参数名称
private String name;
// 参数值
private String value;
// 颜色
private String color;
public TemplateParam() {
super();
}
public TemplateParam(String name, String value, String color) {
this.name = name;
this.value = value;
this.color = color;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
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;
}
@Override
public String toString() {
return "TemplateParam [name=" + name + ", value=" + value + ", color=" + color + "]";
}
}
2. 需要的数据模版类:
package com.enation.app.shop.component.template.model;
import java.util.List;
/**
* 微信模版需要的数据
* @author yh
*
*/
public class WeixinTemplate {
// 消息接收方
private String toUser;
// 模板id
private String templateId;
// 模板消息详情链接
private String url;
// 消息顶部的颜色
private String topColor;
// 参数列表
private List<TemplateParam> templateParamList;
public String getToUser() {
return toUser;
}
public void setToUser(String toUser) {
this.toUser = toUser;
}
public String getTemplateId() {
return templateId;
}
public void setTemplateId(String templateId) {
this.templateId = templateId;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getTopColor() {
return topColor;
}
public void setTopColor(String topColor) {
this.topColor = topColor;
}
//封装成需要的json数据
public String toJSON() {
StringBuffer buffer = new StringBuffer();
buffer.append("{");
buffer.append(String.format("\"touser\":\"%s\"", this.toUser)).append(",");
buffer.append(String.format("\"template_id\":\"%s\"", this.templateId)).append(",");
buffer.append(String.format("\"url\":\"%s\"", this.url)).append(",");
buffer.append(String.format("\"topcolor\":\"%s\"", this.topColor)).append(",");
buffer.append("\"data\":{");
TemplateParam param = null;
for (int i = 0; i < this.templateParamList.size(); i++) {
param = templateParamList.get(i);
// 判断是否追加逗号
if (i < this.templateParamList.size() - 1){
buffer.append(String.format("\"%s\": {\"value\":\"%s\",\"color\":\"%s\"},", param.getName(), param.getValue(), param.getColor()));
}else{
buffer.append(String.format("\"%s\": {\"value\":\"%s\",\"color\":\"%s\"}", param.getName(), param.getValue(), param.getColor()));
}
}
buffer.append("}");
buffer.append("}");
return buffer.toString();
}
public List<TemplateParam> getTemplateParamList() {
return templateParamList;
}
public void setTemplateParamList(List<TemplateParam> templateParamList) {
this.templateParamList = templateParamList;
}
}
3. 发送请求的方法:
package com.enation.app.shop.component.template.test;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.entity.StringEntity;
import com.enation.framework.util.HttpMethodClient;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
public class DemoTest03 {
/**
* 获取Access_token
*/
public String getAccess_token(String AppId, String AppSecret) throws Exception {
String getAccess_token = "https://api.weixin.qq.com/cgi-bin/token";
Map<String, Object> getMap = new HashMap<String, Object>();
getMap.put("grant_type", "client_credential");
getMap.put("appid", AppId);
getMap.put("secret", AppSecret);
String access_token = HttpMethodClient.sendGet(getAccess_token, getMap);
return access_token;
}
//请求方法
public String getResult(String access_token, String data) throws Exception {
String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token;
String str = post(url, data);
return str;
}
public String post(String url, String data) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
post.setHeader("Content-Type", "application/json");
post.addHeader("Authorization", "Basic YWRtaW46");
String result = "";
try {
StringEntity s = new StringEntity(data, "utf-8");
s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(s);
// 发送请求
HttpResponse httpResponse = client.execute(post);
// 获取响应输入流
InputStream inStream = httpResponse.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "utf-8"));
StringBuilder strber = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
strber.append(line + "\n");
inStream.close();
result = strber.toString();
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
System.out.println("请求服务器成功,做相应处理");
} else {
System.out.println("请求服务端失败");
}
} catch (Exception e) {
System.out.println("请求异常");
throw new RuntimeException(e);
}
return result;
}
}
4. 测试方法:
package com.enation.app.shop.component.template.test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.enation.app.shop.component.template.model.TemplateParam;
import com.enation.app.shop.component.template.model.WeixinTemplate;
import net.sf.json.JSONObject;
public class Test {
public static void main(String[] args) throws Exception {
DemoTest03 dt = new DemoTest03();
String access_token = dt.getAccess_token("wxd44.(这里是AppId).c39b54", "b8fe14d6.(这里是:AppSecret).33fd51b911");// 封装方法
Map<String, Object> ac = JSONObject.fromObject(access_token);
List<TemplateParam> list = new ArrayList<TemplateParam>();
list.add(new TemplateParam("first", "恭喜你购买成功!", "#173177"));
list.add(new TemplateParam("keyword1", "1", "#173177"));
list.add(new TemplateParam("keyword2", "2", "#173177"));
list.add(new TemplateParam("keyword3", "3", "#173177"));
list.add(new TemplateParam("remark", "4", "#173177"));
WeixinTemplate tem = new WeixinTemplate();
tem.setToUser("oQmzW0y.(这里是用户:Openid).Jpfps_8");
tem.setTemplateId("uca47VkFua5gYDN.(这里是模版id)._ZwNXmwl7xDLzOKi0Y");
tem.setUrl("http://weixin.qq.com/");
tem.setTemplateParamList(list);
System.out.println(tem.toJSON());
String getResult = dt.getResult(ac.get("access_token").toString(), tem.toJSON());
System.out.println(getResult);
}
}
最后输出:{"errcode":0,"errmsg":"ok","msgid":240556716209766400}
就成功了