微信小程序订阅消息(java后端实现)开发
订阅消息说明
订阅消息是微信近期新出的一个能力,用来代替原有的模板消息(原有的模板消息即将下线)
订阅消息的功能较模板消息有所提升,"7天"的限制取消,同时有"一次性"和"永久"订阅.(功能上是这样说的,但是实际开发时发现"永久"订阅还是对小程序的服务类目有要求的,客户的小程序只支持"一次性"订阅)
官方通道:
小程序前端:点击进入
小程序服务端:点击进入
开发思路
用户在小程序内触发按钮或进行支付操作时前端调用订阅消息授权框,默认一次授权只能发送一次订阅消息
如果用户勾选"下次自动授权",下次将不再弹出授权框->点击按钮直接拥有一次发送订阅消息的机会,此处不需要模板消息的"formId",较之前更简单
经过测试,如果在小程序上多次点击触发授权的按钮,发送订阅消息的机会可以累加!!!
(如,1分钟内点击了10次按钮,后面将拥有10次发送订阅消息的机会,什么时候发都可以)
代码实现(仅java后端)
实体类部分
1.TemplateParam.java
publicclassTemplateParam{
privateStringkey;
privateStringvalue;
publicTemplateParam(Stringkey,Stringvalue){
this.key=key;
this.value=value;
}
publicStringgetValue(){
returnvalue;
}
publicvoidsetValue(Stringvalue){
this.value=value;
}
publicStringgetKey(){
returnkey;
}
publicvoidsetKey(Stringkey){
this.key=key;
}
}
2.Template.java
importjava.util.List;
publicclassTemplate{
privateStringtouser;
privateStringtemplate_id;
privateStringpage;
privateListtemplateParamList;
publicStringgetTouser(){
returntouser;
}
publicvoidsetTouser(Stringtouser){
this.touser=touser;
}
publicStringgetTemplate_id(){
returntemplate_id;
}
publicvoidsetTemplate_id(Stringtemplate_id){
this.template_id=template_id;
}
publicStringgetPage(){
returnpage;
}
publicvoidsetPage(Stringpage){
this.page=page;
}
publicStringtoJSON(){
StringBufferbuffer=newStringBuffer();
buffer.append("{");
buffer.append(String.format("\"touser\":\"%s\"",this.touser)).append(",");
buffer.append(String.format("\"template_id\":\"%s\"",this.template_id)).append(",");
buffer.append(String.format("\"page\":\"%s\"",this.page)).append(",");
buffer.append("\"data\":{");
TemplateParamparam=null;
for(inti=0;igetTemplateParamList(){
returntemplateParamList;
}
publicvoidsetTemplateParamList(ListtemplateParamList){
this.templateParamList=templateParamList;
}
}
工具类部分
1.CommonUtil.java
importjava.io.BufferedReader;
importjava.io.InputStream;
importjava.io.InputStreamReader;
importjava.io.OutputStream;
importjava.io.UnsupportedEncodingException;
importjava.net.ConnectException;
importjava.net.HttpURLConnection;
importjava.net.URL;
importjavax.net.ssl.HttpsURLConnection;
importjavax.net.ssl.SSLContext;
importjavax.net.ssl.SSLSocketFactory;
importjavax.net.ssl.TrustManager;
importnet.sf.json.JSONObject;
publicclassCommonUtil{
publicstaticJSONObjecthttpsRequest(StringrequestUrl,StringrequestMethod,StringoutputStr){
JSONObjectjsonObject=null;
StringBufferbuffer=newStringBuffer();
try{
//创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[]tm={newMyX509TrustManager()};
SSLContextsslContext=SSLContext.getInstance("SSL","SunJSSE");
sslContext.init(null,tm,newjava.security.SecureRandom());
//从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactoryssf=sslContext.getSocketFactory();
URLurl=newURL(requestUrl);
HttpsURLConnectionhttpUrlConn=(HttpsURLConnection)url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
//设置请求方式(GET/POST)
httpUrlConn.setRequestMethod(requestMethod);
if("GET".equalsIgnoreCase(requestMethod)){
httpUrlConn.connect();
}
//当有数据需要提交时
if(null!=outputStr){
OutputStreamoutputStream=httpUrlConn.getOutputStream();
//注意编码格式,防止中文乱码
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
//将返回的输入流转换成字符串
InputStreaminputStream=httpUrlConn.getInputStream();
InputStreamReaderinputStreamReader=newInputStreamReader(inputStream,"utf-8");
BufferedReaderbufferedReader=newBufferedReader(inputStreamReader);
Stringstr=null;
while((str=bufferedReader.readLine())!=null){
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
//释放资源
inputStream.close();
inputStream=null;
httpUrlConn.disconnect();
jsonObject=JSONObject.fromObject(buffer.toString());
}catch(ConnectExceptionce){
ce.printStackTrace();
}catch(Exceptione){
e.printStackTrace();
}
returnjsonObject;
}
publicstaticStringhttpRequest(StringrequestUrl,StringrequestMethod,StringoutputStr){
StringBufferbuffer=newStringBuffer();
try{
URLurl=newURL(requestUrl);
HttpURLConnectionhttpUrlConn=(HttpURLConnection)url.openConnection();
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
//设置请求方式(GET/POST)
httpUrlConn.setRequestMethod(requestMethod);
if("GET".equalsIgnoreCase(requestMethod)){
httpUrlConn.connect();
}
//当有数据需要提交时
if(null!=outputStr){
OutputStreamoutputStream=httpUrlConn.getOutputStream();
//注意编码格式,防止中文乱码
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
//将返回的输入流转换成字符串
InputStreaminputStream=httpUrlConn.getInputStream();
InputStreamReaderinputStreamReader=newInputStreamReader(inputStream,"utf-8");
BufferedReaderbufferedReader=newBufferedReader(inputStreamReader);
Stringstr=null;
while((str=bufferedReader.readLine())!=null){
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
//释放资源
inputStream.close();
inputStream=null;
httpUrlConn.disconnect();
//jsonObject=JSONObject.fromObject(buffer.toString());
}catch(ConnectExceptionce){
ce.printStackTrace();
}catch(Exceptione){
e.printStackTrace();
}
returnbuffer.toString();
}
publicstaticStringurlEncodeUTF8(Stringsource){
Stringresult=source;
try{
result=java.net.URLEncoder.encode(source,"utf-8");
}catch(UnsupportedEncodingExceptione){
e.printStackTrace();
}
returnresult;
}
publicstaticStringhttpsRequestForStr(StringrequestUrl,StringrequestMethod,StringoutputStr){
Stringresult="";
StringBufferbuffer=newStringBuffer();
try{
//创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[]tm={newMyX509TrustManager()};
SSLContextsslContext=SSLContext.getInstance("SSL","SunJSSE");
sslContext.init(null,tm,newjava.security.SecureRandom());
//从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactoryssf=sslContext.getSocketFactory();
URLurl=newURL(requestUrl);
HttpsURLConnectionhttpUrlConn=(HttpsURLConnection)url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
//设置请求方式(GET/POST)
httpUrlConn.setRequestMethod(requestMethod);
if("GET".equalsIgnoreCase(requestMethod)){
httpUrlConn.connect();
}
//当有数据需要提交时
if(null!=outputStr){
OutputStreamoutputStream=httpUrlConn.getOutputStream();
//注意编码格式,防止中文乱码
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
//将返回的输入流转换成字符串
InputStreaminputStream=httpUrlConn.getInputStream();
InputStreamReaderinputStreamReader=newInputStreamReader(inputStream,"utf-8");
BufferedReaderbufferedReader=newBufferedReader(inputStreamReader);
Stringstr=null;
while((str=bufferedReader.readLine())!=null){
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
//释放资源
inputStream.close();
inputStream=null;
httpUrlConn.disconnect();
result=buffer.toString();
}catch(ConnectExceptionce){
ce.printStackTrace();
}catch(Exceptione){
e.printStackTrace();
}
returnresult;
}
}
2.HttpUtil.java
importjava.io.IOException;
importjava.util.ArrayList;
importjava.util.List;
importjava.util.Map;
importorg.apache.http.Consts;
importorg.apache.http.HttpEntity;
importorg.apache.http.NameValuePair;
importorg.apache.http.client.entity.UrlEncodedFormEntity;
importorg.apache.http.client.methods.CloseableHttpResponse;
importorg.apache.http.client.methods.HttpGet;
importorg.apache.http.client.methods.HttpPost;
importorg.apache.http.impl.client.CloseableHttpClient;
importorg.apache.http.impl.client.HttpClients;
importorg.apache.http.message.BasicNameValuePair;
importorg.apache.http.util.EntityUtils;
publicclassHttpUtil{
privatestaticfinalCloseableHttpClienthttpclient=HttpClients.createDefault();
/**
*发送HttpGet请求
*@paramurl
*@return
*/
publicstaticStringsendGet(Stringurl){
HttpGethttpget=newHttpGet(url);
CloseableHttpResponseresponse=null;
try{
response=httpclient.execute(httpget);
}catch(IOExceptione1){
e1.printStackTrace();
}
Stringresult=null;
try{
HttpEntityentity=response.getEntity();
if(entity!=null){
result=EntityUtils.toString(entity);
}
}catch(Exceptione){
e.printStackTrace();
}finally{
try{
response.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
returnresult;
}
/**
*发送HttpPost请求,参数为map
*@paramurl
*@parammap
*@return
*/
publicstaticStringsendPost(Stringurl,Mapmap){
Listformparams=newArrayList();
for(Map.Entryentry:map.entrySet()){
formparams.add(newBasicNameValuePair(entry.getKey(),entry.getValue()));
}
UrlEncodedFormEntityentity=newUrlEncodedFormEntity(formparams,Consts.UTF_8);
HttpPosthttppost=newHttpPost(url);
httppost.setEntity(entity);
CloseableHttpResponseresponse=null;
try{
response=httpclient.execute(httppost);
}catch(IOExceptione){
e.printStackTrace();
}
HttpEntityentity1=response.getEntity();
Stringresult=null;
try{
result=EntityUtils.toString(entity1);
}catch(Exceptione){
e.printStackTrace();
}
returnresult;
}
/**
*发送不带参数的HttpPost请求
*@paramurl
*@return
*/
publicstaticStringsendPost(Stringurl){
HttpPosthttppost=newHttpPost(url);
CloseableHttpResponseresponse=null;
try{
response=httpclient.execute(httppost);
}catch(IOExceptione){
e.printStackTrace();
}
HttpEntityentity=response.getEntity();
Stringresult=null;
try{
result=EntityUtils.toString(entity);
}catch(Exceptione){
e.printStackTrace();
}
returnresult;
}
}
jar包:
1.fastjson-1.2.44.jar
控制层代码:
1.获取ACCESS_TOKEN
Stringurl="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
+小程序的appid
+"&secret="
+小程序的Secret
Stringresult=HttpUtil.sendGet(url);
JSONObjectobject=JSON.parseObject(result);
StringAccess_Token=object.getString("access_token");
2.发送订阅消息
Templatetemplate=newTemplate();
template.setTemplate_id("填写小程序申请的订阅消息id");
template.setTouser("用户的openid");
template.setPage("pages/index/index");
Listparas=newArrayList();
paras.add(newTemplateParam("character_string2","000001"));
paras.add(newTemplateParam("amount1","888.88"));
paras.add(newTemplateParam("date3","2015年01月05日"));
paras.add(newTemplateParam("thing4","请进入小程序查1看"));
template.setTemplateParamList(paras);
StringrequestUrl="https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN";
requestUrl=requestUrl.replace("ACCESS_TOKEN",Access_Token);
System.out.println(template.toJSON());
net.sf.json.JSONObjectjsonResult=CommonUtil.httpsRequest(requestUrl,"POST",template.toJSON());
if(jsonResult!=null){
System.out.println(jsonResult);
interrorCode=jsonResult.getInt("errcode");
StringerrorMessage=jsonResult.getString("errmsg");
if(errorCode==0){
System.out.println("SendSuccess");
}else{
System.out.println("订阅消息发送失败:"+errorCode+","+errorMessage);
}
}
总结
1.本文阅读对象为初学者,所有各种工具类.jar包都粘出来了,直接复制即可使用
2.通过该功能的开发,发现小程序的通知类功能监管更加严格,必须用户授权才可以发订阅消息,同时用户可以更方便的取消订阅,所以建议开发者慎用此功能
到此这篇关于微信小程序订阅消息(java后端实现)开发的文章就介绍到这了,更多相关小程序订阅消息内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!