1. ConfirmTemplate(推送接口)
package com.zero.jimu.utils.pushMessage;
import com.google.gson.Gson;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class ConfirmTemplate {
private static Logger logger = LoggerFactory.getLogger(ConfirmTemplate.class);
//微信模板接口
private final String SEND_TEMPLAYE_MESSAGE_URL = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=ACCESS_TOKEN";//接口地址
private final String APPID = "wx1000000000000000";
private final String SECRET = "ffjshdjhfuis5648156156";
//获取微信ACCESS_TOKEN接口
private final String aturl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APPID + "&secret=" + SECRET;
//确认模板ID
private static String confirm_template_id="jaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
//取消模板ID
private static String cancel_template_id="Caaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
//拍摄提醒模板ID
private static String push_template_id="6dsadasdasdsadasdsadas";
//商家确认跳转路径及备注信息
private static String confirm_status="商家已确认";
private static String confirm_url="pages/Trip/trip";
private static String confirm_remark = "商家已确认,请及时查看日程";
//商家取消跳转路径及备注信息
private static String cancel_url="pages/index/index";
private static String cancel_remark="非常抱歉,由于该空间当天档期已满,请选好日期和时段重新下单";
//商家超时取消备注信息
private static String cancel_timeout_remark="非常抱歉,由于商家超过规定接单时间未能成功接单,请选好日期和时段重新下单";
private static String cancel_timeout_remark1="非常抱歉,由于您选择的拍摄开始时间已过,商家无法完成正常接单,请选好日期和时段重新下单";
private static String cancel_timeout_remark2="非常抱歉,由于您下的订单为当天拍摄订单,商家未能及时接单,请选好日期和时段重新下单";
/**
* 提醒拍摄推送
* @param openId
* @param form_id
* @param shootDate
* @param shootSite
*/
public void pushRemindMessage(String openId,String form_id,String shootDate,String shootSite){
//获取模板消息接口获取的accessToken
ConfirmTemplate confirmTemplate = new ConfirmTemplate();
AccessTokenDemo demo = confirmTemplate.getAccess_token();
String access_token=demo.getAccess_token();
WechatTemplate wechatTemplate = new WechatTemplate();
wechatTemplate.setTouser(openId); //此处是用户的OpenId
wechatTemplate.setForm_id(form_id);//表单提交场景下,为 submit 事件带上的 formId;支付场景下,为本次支付的 prepay_id
wechatTemplate.setTemplate_id(push_template_id);//所需下发的模板消息的id
wechatTemplate.setPage(confirm_url);//设置小程序跳转路径
//设置模板内容
Map<String,TemplateData> m = new HashMap<>();
TemplateData keyword1 = new TemplateData();
TemplateData keyword2 = new TemplateData();
keyword1.setColor("#000000");
keyword2.setColor("#000000");
keyword1.setValue(shootDate);
keyword2.setValue(shootSite);
m.put("keyword1", keyword1);
m.put("keyword2", keyword2);
wechatTemplate.setData(m);
try {
confirmTemplate.sendTemplateMessage(access_token, wechatTemplate);
} catch (Exception e) {
logger.info("异常"+e.getMessage());
}
}
/**
* 商家确认(取消)订单后,通过微信公众号推送消息给客户
* @param openId
* @param form_id
* @param spaceName
* @param status
* @param payMoney
*/
public void pushMessage(String openId,String form_id,String spaceName,String status,String payMoney){
//获取模板消息接口获取的accessToken
ConfirmTemplate confirmTemplate = new ConfirmTemplate();
AccessTokenDemo demo = confirmTemplate.getAccess_token();
String access_token=demo.getAccess_token();
WechatTemplate wechatTemplate = new WechatTemplate();
wechatTemplate.setTouser(openId); //此处是用户的OpenId
wechatTemplate.setForm_id(form_id);//表单提交场景下,为 submit 事件带上的 formId;支付场景下,为本次支付的 prepay_id
if(status.equals("2")){ //商家确认
wechatTemplate.setTemplate_id(confirm_template_id);//所需下发的模板消息的id
wechatTemplate.setPage(confirm_url);//设置小程序跳转路径
}
if(status.equals("6")||status.equals("8")||status.equals("9")||status.equals("10")){ //商家取消
wechatTemplate.setTemplate_id(cancel_template_id);//所需下发的模板消息的id
wechatTemplate.setPage(cancel_url);//设置小程序跳转路径
}
//设置模板内容
Map<String,TemplateData> m = new HashMap<>();
TemplateData keyword1 = new TemplateData();
TemplateData keyword2 = new TemplateData();
TemplateData keyword3 = new TemplateData();
TemplateData keyword4 = new TemplateData();
keyword1.setColor("#000000");
keyword2.setColor("#000000");
keyword3.setColor("#000000");
keyword4.setColor("#000000");
keyword1.setValue(spaceName);
if(status.equals("2")){ //商家确认
keyword2.setValue(confirm_status);
keyword3.setValue(payMoney);
keyword4.setValue(confirm_remark);
m.put("keyword4", keyword4);
}
if(status.equals("6")){ //商家取消
keyword2.setValue(payMoney);
keyword3.setValue(cancel_remark);
}
if(status.equals("8")){ //商家超时取消
keyword2.setValue(payMoney);
keyword3.setValue(cancel_timeout_remark);
}
if(status.equals("9")){ //下已经过了拍摄开始时间的单子
keyword2.setValue(payMoney);
keyword3.setValue(cancel_timeout_remark1);
}
if(status.equals("10")){ //拍摄时间已过
keyword2.setValue(payMoney);
keyword3.setValue(cancel_timeout_remark2);
}
m.put("keyword1", keyword1);
m.put("keyword2", keyword2);
m.put("keyword3", keyword3);
wechatTemplate.setData(m);
try {
confirmTemplate.sendTemplateMessage(access_token, wechatTemplate);
} catch (Exception e) {
logger.info("异常"+e.getMessage());
}
}
/**
* 推送动作
* @param accessToken
* @param wechatTemplate
*/
public void sendTemplateMessage(String accessToken, WechatTemplate wechatTemplate) {
String jsonString = new Gson().toJson(wechatTemplate).toString();
String requestUrl = SEND_TEMPLAYE_MESSAGE_URL.replace("ACCESS_TOKEN", accessToken);
//logger.info("请求参数",jsonString);//发送 post请求 发送json数据
HttpClientUtil httpClientUtil = new HttpClientUtil();
String json = httpClientUtil.sendHttpPostJson(requestUrl, jsonString);
WeiXinResponse weiXinResponse = new Gson().fromJson(json, WeiXinResponse.class);
//logger.info("jsonObject="+weiXinResponse);
if (null != weiXinResponse) {
int errorCode = weiXinResponse.getErrcode();
if (0 == errorCode) {
//logger.info("模板消息发送成功");
} else {
String errorMsg = weiXinResponse.getErrmsg();
//logger.info("模板消息发送失败,错误是 "+errorCode+",错误信息是"+ errorMsg);
}
}
}
/**
* 获取AccessToken
*/
public AccessTokenDemo getAccess_token() {
try {
String access_token = "";
DefaultHttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(aturl);
HttpResponse response = client.execute(request);
HttpClientUtil httpClientUtil = new HttpClientUtil();
String httpGet = httpClientUtil.sendHttpGet(aturl);
Gson gson=new Gson();
AccessTokenDemo jsonResult=new AccessTokenDemo();
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String strResult = EntityUtils.toString(response.getEntity());
//System.out.println("get请求结果:" + strResult);
//System.out.println("结果回调" +response.getStatusLine().getStatusCode() );
jsonResult = gson.fromJson(strResult, AccessTokenDemo.class);
access_token = jsonResult.getAccess_token();
String expires_in =jsonResult.getExpires_in();
//logger.info("access_token{}: expires_in{}:",access_token,expires_in);
}
return jsonResult;
} catch (ClientProtocolException e) {
//e.printStackTrace();
} catch (IOException e) {
//e.printStackTrace();
} return null;
}
}
2. AccessTokenDemo(微信小程序ACCESS_TOKEN)
package com.zero.jimu.utils.pushMessage;
/**
* 微信小程序ACCESS_TOKEN
*/
public class AccessTokenDemo {
private String access_token;
private 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;
}
}
3. HttpClientUtil (http工具类)
package com.zero.jimu.utils.pushMessage;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
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.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.util.PublicSuffixMatcher;
import org.apache.http.conn.util.PublicSuffixMatcherLoader;
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.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.net.URL;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* http工具类
*/
public class HttpClientUtil {
private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
//设置数据传输处理时间、建立连接的timeout时间、从连接池中后去连接的timeout时间
private RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(15000).setConnectTimeout(15000)
.setConnectionRequestTimeout(15000).build();
private boolean checkTimeout = true;
public HttpClientUtil() {
super();
}
/**
* 发送 post请求 发送json数据
*/
public static String sendHttpPostJson(String url, String json) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建请求内容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return resultString;
}
/**
* 发送 get请求
*
* @param httpUrl
*/
public String sendHttpGet(String httpUrl) {
logger.info("请求sendHttpGet方法,参数httpUrl=" + httpUrl);
HttpGet httpGet = new HttpGet(httpUrl);// 创建get请求
return httpGet(httpGet);
}
/**
* 发送 get请求Https
*
* @param httpUrl
*/
public String sendHttpsGet(String httpUrl) {
logger.info("请求sendHttpsGet方法,参数httpUrl=" + httpUrl);
HttpGet httpGet = new HttpGet(httpUrl);// 创建get请求
return httpsGet(httpGet);
}
/**
* 发送Get请求
*
* @param httpGet
* @return
*/
private String httpGet(HttpGet httpGet) {
//logger.info("请求httpGet方法");
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
HttpEntity entity = null;
String responseContent = null;
try {
// 创建默认的httpClient实例.
httpClient = HttpClients.createDefault();
if (this.checkTimeout)
httpGet.setConfig(requestConfig);
// 执行请求
response = httpClient.execute(httpGet);
entity = response.getEntity();
responseContent = EntityUtils.toString(entity, "UTF-8");
//logger.info("请求httpGet方法响应信息:responseContent=" + responseContent);
} catch (Exception e) {
//logger.error("请求httpGet方法异常,异常信息:" + e.getMessage());
e.printStackTrace();
} finally {
try {
// 关闭连接,释放资源
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (Exception e) {
//logger.error("请求httpGet方法,关闭连接异常,异常信息:" + e.getMessage());
e.printStackTrace();
}
}
return responseContent;
}
/**
* 发送Get请求Https
*
* @param httpGet
* @return
*/
private String httpsGet(HttpGet httpGet) {
//logger.info("请求httpsGet方法");
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
HttpEntity entity = null;
String responseContent = null;
try {
// 创建默认的httpClient实例.
PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader
.load(new URL(httpGet.getURI().toString()));
DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher);
httpClient = HttpClients.custom().setSSLHostnameVerifier(hostnameVerifier).build();
if (this.checkTimeout)
httpGet.setConfig(requestConfig);
// 执行请求
response = httpClient.execute(httpGet);
entity = response.getEntity();
responseContent = EntityUtils.toString(entity, "UTF-8");
//logger.info("请求httpsGet方法响应信息:responseContent=" + responseContent);
} catch (Exception e) {
//logger.error("请求httpsGet方法异常,异常信息:" + e.getMessage());
e.printStackTrace();
} finally {
try {
// 关闭连接,释放资源
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (Exception e) {
//logger.error("请求httpsGet方法,关闭连接异常,异常信息:" + e.getMessage());
e.printStackTrace();
}
}
return responseContent;
}
/**
* 发送 post请求
*
* @param httpUrl
* 地址
*/
public String sendHttpPost(String httpUrl) {
//logger.info("请求sendHttpPost方法,请求参数httpUrl=" + httpUrl);
HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
return httpPost(httpPost);
}
/**
* 发送 post请求
*
* @param httpUrl
* 地址
* @param params
* 参数(格式:key1=value1&key2=value2)
*/
public String sendHttpPost(String httpUrl, String params) {
//logger.info("请求sendHttpPost方法,请求参数httpUrl=" + httpUrl + ",params=" + params);
String responseContent = null;
HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
try {
// 设置参数
StringEntity stringEntity = new StringEntity(params, "UTF-8");
stringEntity.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(stringEntity);
responseContent = httpPost(httpPost);
} catch (Exception e) {
//logger.error("请求sendHttpPost方法异常,异常信息:" + e.getMessage());
e.printStackTrace();
}
return responseContent;
}
/**
* 发送 post请求
*
* @param httpUrl
* 地址
* @param maps
* 参数
*/
public String sendHttpPost(String httpUrl, Map<String, String> maps) {
//logger.info("请求sendHttpPost方法,请求参数httpUrl=" + httpUrl + ",maps=" + maps);
HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
// 创建参数队列
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
for (String key : maps.keySet()) {
nameValuePairs.add(new BasicNameValuePair(key, maps.get(key)));
}
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
} catch (Exception e) {
//logger.error("请求sendHttpPost方法异常,异常信息:" + e.getMessage());
e.printStackTrace();
}
return httpPost(httpPost);
}
/**
* 发送Post请求
*
* @param httpPost
* @return
*/
private String httpPost(HttpPost httpPost) {
//logger.info("请求httpPost方法");
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
HttpEntity entity = null;
String responseContent = null;
try {
// 创建默认的httpClient实例.
httpClient = HttpClients.createDefault();
if (this.checkTimeout)
httpPost.setConfig(requestConfig);
// 执行请求
response = httpClient.execute(httpPost);
entity = response.getEntity();
responseContent = EntityUtils.toString(entity, "UTF-8");
//logger.info("请求httpPost方法响应信息:responseContent=" + responseContent);
} catch (Exception e) {
//logger.error("请求httpPost方法异常,异常信息:" + e.getMessage());
e.printStackTrace();
} finally {
try {
// 关闭连接,释放资源
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (Exception e) {
//logger.error("请求httpPost方法,关闭连接异常,异常信息:" + e.getMessage());
e.printStackTrace();
}
}
return responseContent;
}
public String sendHttpsPost(String httpUrl, Map<String, String> maps) {
//logger.info("请求sendHttpsPost方法,参数httpUrl=" + httpUrl + ",maps=" + maps);
String responseContent = null;
HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
// 创建参数队列
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
if (null != maps) {
for (String key : maps.keySet()) {
nameValuePairs.add(new BasicNameValuePair(key, maps.get(key)));
}
}
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
responseContent = httpsPost(httpPost);
} catch (Exception e) {
//logger.error("请求sendHttpPost方法异常,异常信息:" + e.getMessage());
e.printStackTrace();
}
return responseContent;
}
private String httpsPost(HttpPost httpPost) throws Exception {
//logger.info("请求httpsPost方法");
// 采用绕过验证的方式处理https请求
SSLContext sslcontext = createIgnoreVerifySSL();
// 设置协议http和https对应的处理socket链接工厂的对象
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslcontext)).build();
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
HttpClients.custom().setConnectionManager(connManager);
// 创建自定义的httpclient对象
CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();
// 执行请求操作,并拿到结果(同步阻塞)
CloseableHttpResponse response = client.execute(httpPost);
// 获取结果实体
HttpEntity entity = response.getEntity();
String body = "";
if (entity != null) {
// 按指定编码转换结果实体为String类型
body = EntityUtils.toString(entity, "UTF-8");
}
//logger.info("请求httpsPost方法响应信息:body=" + body);
EntityUtils.consume(entity);
// 释放链接
response.close();
return body;
}
/**
* 绕过验证
*
* @return
* @throws Exception
*/
private SSLContext createIgnoreVerifySSL() throws Exception {
SSLContext sc = SSLContext.getInstance("SSL");
// 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法
X509TrustManager trustManager = new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
};
sc.init(null, new TrustManager[] { trustManager }, null);
return sc;
}
/**
* 是否校验超时时间
*
* @return true:校验<br>
* false:不校验(默认)
*/
public boolean isCheckTimeout() {
return checkTimeout;
}
/**
* 设置是否校验超时时间
*
* @param checkTimeout
* true:校验<br>
* false:不校验(默认)
*/
public void setCheckTimeout(boolean checkTimeout) {
this.checkTimeout = checkTimeout;
}
}
4. TemplateData
package com.zero.jimu.utils.pushMessage;
/**
* 模板消息Template数据封装
*/
public class TemplateData {
private String value;
private String color;//模板内容字体的颜色,不填默认黑色 【废弃】
public TemplateData() {
super();
}
public TemplateData(String value, String color) {
this.value = value;
this.color = 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;
}
}
5. WechatTemplate
package com.zero.jimu.utils.pushMessage;
import java.util.Map;
/**
* 发送模版消息post参数封装
*/
public class WechatTemplate {
private String touser;//接收者(用户)的 openid
private String template_id;//所需下发的模板消息的id
private String page;//点击模板卡片后的跳转页面,仅限本小程序内的页面。支持带参数,(示例index?foo=bar)。该字段不填则模板无跳转。
private String form_id;//表单提交场景下,为 submit 事件带上的 formId;支付场景下,为本次支付的 prepay_id
private String emphasis_keyword;//模板需要放大的关键词,不填则默认无放大
private Map<String, TemplateData> data;//模板内容,不填则下发空模板
public WechatTemplate() {
super();
}
public WechatTemplate(String touser, String template_id, String page, String form_id, String emphasis_keyword, Map<String, TemplateData> data) {
this.touser = touser;
this.template_id = template_id;
this.page = page;
this.form_id = form_id;
this.emphasis_keyword = emphasis_keyword;
this.data = 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 getPage() {
return page;
}
public void setPage(String page) {
this.page = page;
}
public String getForm_id() {
return form_id;
}
public void setForm_id(String form_id) {
this.form_id = form_id;
}
public String getEmphasis_keyword() {
return emphasis_keyword;
}
public void setEmphasis_keyword(String emphasis_keyword) {
this.emphasis_keyword = emphasis_keyword;
}
public Map<String, TemplateData> getData() {
return data;
}
public void setData(Map<String, TemplateData> data) {
this.data = data;
}
}
6. WeiXinResponse
package com.zero.jimu.utils.pushMessage;
/**
* 微信返回错误信息
*/
public class WeiXinResponse {
private Integer errcode;
private String errmsg;
private String msgid;
public Integer getErrcode() {
return errcode;
}
public void setErrcode(Integer errcode) {
this.errcode = errcode;
}
public String getErrmsg() {
return errmsg;
}
public void setErrmsg(String errmsg) {
this.errmsg = errmsg;
}
public String getMsgid() {
return msgid;
}
public void setMsgid(String msgid) {
this.msgid = msgid;
}
}