最近工作上用到了微信服务号的模板消息推送, 正好也写出来给大家分享下;
1.登录微信服务号获得AppID和AppSecret
1).登录该页面:https://mp.weixin.qq.com/
2).进入首页, 左边导航栏最下方 </>开发 基本配置
3).拿到appid, appSecret, 设置白名单
获得基本参数.jpg
2.代码开发
1. 先准备四个实体类
package cn.cooplan.data_statistical.pojo.wx;
/**
* 模板消息跳转小程序, 封装参数的类
* @Author MaoLG
* @Date 2018/11/13 17:23
*/
public class Miniprogram {
private String appid;
private String pagepath;
public String getAppid() {
return appid;
}
public void setAppid(String appid) {
this.appid = appid;
}
public String getPagepath() {
return pagepath;
}
public void setPagepath(String pagepath) {
this.pagepath = pagepath;
}
}
package cn.cooplan.data_statistical.pojo.wx;
/**
* 模板消息的内容,
* 封装模板消息具体内容的类
* @Author MaoLG
* @Date 2018/11/13 16:32
*/
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;
}
}
package cn.cooplan.data_statistical.pojo.wx;
import java.util.Map;
/**
* 包含Miniprogram, TemplateData
* 参数的类, 调用微信发送模板消息的参数类
* @Author MaoLG
* @Date 2018/11/13 16:33
*/
public class WechatTemplate {
private String touser;
private Miniprogram miniprogram;
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 Miniprogram getMiniprogram() {
return miniprogram;
}
public void setMiniprogram(Miniprogram miniprogram) {
this.miniprogram = miniprogram;
}
public void setData(Map<String, TemplateData> data) {
this.data = data;
}
}
package cn.cooplan.data_statistical.pojo.wx;
/**
* 封装获取token的实体类
* @author MaoLG
* @Date 2018/11/13 23:21
*/
public class AccessToken {
String access_token; //token
String expires_in; //过期时间
public String getAccess_token() {
return access_token;
}
public void setAccess_token(String access_token) {
this.access_token = access_token;
}
public String getExpires_in() {
return expires_in;
}
public void setExpires_in(String expires_in) {
this.expires_in = expires_in;
}
}
2.工具类
用了一个对象转json的工具
<!-- fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.51</version>
</dependency>
<!-- httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
package cn.cooplan.data_statistical.util;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.util.StringUtils;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* http请求封装的类
*/
public class HttpClientUtils {
/**
* httpclient执行get请求
*
* @param url
* @param params
* @return
*/
public static String doGet(String url, Map<String, String> params) {
// 创建httpclient
CloseableHttpClient httpClient = HttpClients.createDefault();
String result = "";
CloseableHttpResponse httpResponse = null;
try {
// 构建uri
URIBuilder builder = new URIBuilder(url);
// 构建参数
if (params != null) {
for (Map.Entry<String, String> param : params.entrySet()) {
builder.addParameter(param.getKey(), param.getValue());
}
}
URI uri = builder.build();
// 构建get请求
HttpGet httpGet = new HttpGet(uri);
// 执行
httpResponse = httpClient.execute(httpGet);
result = EntityUtils.toString(httpResponse.getEntity(), Charset.defaultCharset());
} catch (Exception e) {
e.printStackTrace();
} finally {
close(httpClient, httpResponse);
}
return result;
}
/**
* 执行get请求没有参数
*
* @param url
* @return
*/
public static String doGet(String url) {
return doGet(url, null);
}
/**
* 执行post请求
*
* @param url
* @param params
* @return
*/
public static String doPost(String url, Map<String, String> params) {
// 创建httpclient
CloseableHttpClient httpClient = HttpClients.createDefault();
String result = "";
CloseableHttpResponse httpResponse = null;
try {
// 构建请求
HttpPost httpPost = new HttpPost(url);
// 构建参数
if (params != null) {
List<NameValuePair> paramList = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> param : params.entrySet()) {
paramList.add(new BasicNameValuePair(param.getKey(), param.getValue()));
}
// 模拟form表单entity
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(paramList, Charset.defaultCharset());
httpPost.setEntity(formEntity);
}
// 执行
httpResponse = httpClient.execute(httpPost);
result = EntityUtils.toString(httpResponse.getEntity(), Charset.defaultCharset());
} catch (Exception e) {
e.printStackTrace();
} finally {
close(httpClient, httpResponse);
}
return result;
}
/**
* 执行post请求没有参数
*
* @param url
* @return
*/
public static String doPost(String url) {
return doPost(url, null);
}
/**
* 执行post请求,参数为json字符串
*
* @param url
* @param jsonParam
* @return
*/
public static String doPostJsonParam(String url, String jsonParam) {
// 创建httpclient
CloseableHttpClient httpClient = HttpClients.createDefault();
String result = "";
CloseableHttpResponse httpResponse = null;
try {
// 构建请求
HttpPost httpPost = new HttpPost(url);
if (!StringUtils.isEmpty(jsonParam)) {
// 创建请求实体
StringEntity stringEntity = new StringEntity(jsonParam, ContentType.APPLICATION_JSON);
httpPost.setEntity(stringEntity);
}
// 执行
httpResponse = httpClient.execute(httpPost);
result = EntityUtils.toString(httpResponse.getEntity(), Charset.defaultCharset());
} catch (Exception e) {
e.printStackTrace();
} finally {
close(httpClient, httpResponse);
}
return result;
}
/**
* 关闭httpClient和httpResponse
*
* @param httpClient
* @param httpResponse
*/
private static void close(CloseableHttpClient httpClient, CloseableHttpResponse httpResponse) {
if (httpResponse != null) {
try {
httpResponse.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (httpClient != null) {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
3.发送模板消息代码
package cn.cooplan.data_statistical.controller;
import cn.cooplan.data_statistical.pojo.wx.TemplateData;
import cn.cooplan.data_statistical.pojo.wx.WechatTemplate;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
/**
* @Author MaoLG
* @Date 2018/11/13 15:51
*/
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/messageTemplate/")
public class MessageTemplateController {
//服务号的appid
private final String appid = "appid";
//secret 公众号密钥
private final String secret = "appsecret";
@RequestMapping("sendMsg")
Object getToken() throws Exception {
String token = null;
//获得access_token的接口
String getTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
+ appid + "&secret=" + secret;
String openid = "用户的openid";
String sendUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token;
//发送的内容
WechatTemplate wechatTemplate = new WechatTemplate();
//跳转小程序配置
Miniprogram miniprogram = new Miniprogram();
miniprogram.setAppid("小程序的appid");
miniprogram.setPagepath("跳转小程序的路径例如:/index/index");
wechatTemplate.setMiniprogram(miniprogram);
//设置模板id
wechatTemplate.setTemplate_id("-azowud2f5i-hj6M7oeQ0-1DZXUmHobXMLTGaDosLUs");
wechatTemplate.setTouser(openid);
//模板消息点击跳转路径, 如果不配置跳转小程序,可以设置跳转该路径
wechatTemplate.setUrl("http://www.baidu.com");
Map<String,TemplateData> m = new HashMap<String,TemplateData>();
TemplateData first = new TemplateData();
first.setColor("#173177");
first.setValue("娱乐会所消费订单");
m.put("first", first);
TemplateData keyword1 = new TemplateData();
keyword1.setColor("#173177");
keyword1.setValue("冰火两重天套餐服务");
m.put("keyword1", keyword1);
TemplateData keyword2 = new TemplateData();
keyword2.setColor("#173177");
keyword2.setValue("xx先生");
m.put("keyword2", keyword2);
TemplateData keyword3 = new TemplateData();
keyword3.setColor("#173177");
keyword3.setValue("998");
m.put("keyword3", keyword3);
TemplateData keyword4 = new TemplateData();
keyword4.setColor("#173177");
keyword4.setValue("2018-11-10");
m.put("keyword4", keyword4);
TemplateData remark = new TemplateData();
remark.setColor("#173177");
remark.setValue("感谢您的光临!");
m.put("remark", remark);
wechatTemplate.setData(m);
String jsonString = JSON.toJSONString(wechatTemplate);
System.out.println(jsonString);
PrintWriter out = null;
BufferedReader in = null;
JSONObject jsonObject = null;
String result = "";
URL realUrl = new URL(sendUrl);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流(设置请求编码为UTF-8)
out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
// 发送请求参数
out.print(jsonString);
// flush输出流的缓冲
out.flush();
// 获取请求返回数据(设置返回数据编码为UTF-8)
in = new BufferedReader(
new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
System.out.println(result);
return "";
}
}
成功后模板消息
网友评论