欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

微信小程序订阅消息(java后端实现)开发

程序员文章站 2022-07-06 18:11:16
订阅消息说明订阅消息是微信近期新出的一个能力,用来代替原有的模板消息(原有的模板消息即将下线)订阅消息的功能较模板消息有所提升,"7天"的限制取消,同时有"一次性"和"永久"订阅.(功能上是这样说的,...

订阅消息说明

订阅消息是微信近期新出的一个能力,用来代替原有的模板消息(原有的模板消息即将下线)

订阅消息的功能较模板消息有所提升,"7天"的限制取消,同时有"一次性"和"永久"订阅.(功能上是这样说的,但是实际开发时发现"永久"订阅还是对小程序的服务类目有要求的,客户的小程序只支持"一次性"订阅)

官方通道:
小程序前端:点击进入
小程序服务端:点击进入

开发思路

用户在小程序内触发按钮或进行支付操作时前端调用订阅消息授权框,默认一次授权只能发送一次订阅消息
如果用户勾选"下次自动授权",下次将不再弹出授权框->点击按钮直接拥有一次发送订阅消息的机会,此处不需要模板消息的"formid",较之前更简单
经过测试,如果在小程序上多次点击触发授权的按钮,发送订阅消息的机会可以累加!!!
(如,1分钟内点击了10次按钮,后面将拥有10次发送订阅消息的机会,什么时候发都可以)

代码实现(仅java后端)

实体类部分

1.templateparam.java

public class templateparam { 

private string key; 
private string value; 

public templateparam(string key,string value){ 
 this.key=key; 
 this.value=value; 
} 
public string getvalue() { 
 return value; 
} 
public void setvalue(string value) { 
 this.value = value; 
}
public string getkey() {
 return key;
}
public void setkey(string key) {
 this.key = key;
} 
 
}

2.template.java

import java.util.list;

public class template { 
 
private string touser; 
private string template_id; 
private string page;
private list<templateparam> templateparamlist; 


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 tojson() { 
 stringbuffer buffer = new stringbuffer(); 
 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\":{"); 
 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\"},", param.getkey(), param.getvalue())); 
  }else{ 
   buffer.append(string.format("\"%s\": {\"value\":\"%s\"}", param.getkey(), param.getvalue())); 
  } 
 } 
 buffer.append("}"); 
 buffer.append("}"); 
 return buffer.tostring(); 
 } 

public list<templateparam> gettemplateparamlist() { 
 return templateparamlist; 
} 

public void settemplateparamlist(list<templateparam> templateparamlist) { 
 this.templateparamlist = templateparamlist; 
} 
}

工具类部分

1.commonutil.java

import java.io.bufferedreader; 
import java.io.inputstream; 
import java.io.inputstreamreader; 
import java.io.outputstream; 
import java.io.unsupportedencodingexception; 
import java.net.connectexception; 
import java.net.httpurlconnection; 
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 commonutil { 
 
public static jsonobject httpsrequest(string requesturl, string requestmethod, string outputstr) { 
  
 jsonobject jsonobject = null; 
 stringbuffer buffer = new stringbuffer(); 
 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 httpurlconn = (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) { 
   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 = jsonobject.fromobject(buffer.tostring()); 
 } catch (connectexception ce) { 
  ce.printstacktrace(); 
 } catch (exception e) { 
  e.printstacktrace(); 
 } 
 return jsonobject; 
} 
 
public static string httprequest(string requesturl, string requestmethod, string outputstr) { 
  
  
 stringbuffer buffer = new stringbuffer(); 
 try { 
  

  url url = new url(requesturl); 
  httpurlconnection httpurlconn = (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) { 
   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 = jsonobject.fromobject(buffer.tostring()); 
 } catch (connectexception ce) { 
  ce.printstacktrace(); 
 } catch (exception e) { 
  e.printstacktrace(); 
 } 
 return buffer.tostring(); 
} 
public static string urlencodeutf8(string source){ 
 string result = source; 
 try { 
  result = java.net.urlencoder.encode(source,"utf-8"); 
 } catch (unsupportedencodingexception e) { 
  e.printstacktrace(); 
 } 
 return result; 
} 
 
public static string httpsrequestforstr(string requesturl, string requestmethod, string outputstr) { 
  
 string result=""; 
 stringbuffer buffer = new stringbuffer(); 
 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 httpurlconn = (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) { 
   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(); 
  result=buffer.tostring(); 
 } catch (connectexception ce) { 
  ce.printstacktrace(); 
 } catch (exception e) { 
  e.printstacktrace(); 
 } 
 return result; 
} 
 
}

2.httputil.java

import java.io.ioexception;
import java.util.arraylist;
import java.util.list;
import java.util.map;
import org.apache.http.consts;
import org.apache.http.httpentity;
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.impl.client.closeablehttpclient;
import org.apache.http.impl.client.httpclients;
import org.apache.http.message.basicnamevaluepair;
import org.apache.http.util.entityutils;

public class httputil {

private static final closeablehttpclient httpclient = httpclients.createdefault();

/**
 * 发送httpget请求
 * @param url
 * @return
 */
public static string sendget(string url) {

 httpget httpget = new httpget(url);
 closeablehttpresponse response = null;
 try {
  response = httpclient.execute(httpget);
 } catch (ioexception e1) {
  e1.printstacktrace();
 }
 string result = null;
 try {
  httpentity entity = response.getentity();
  if (entity != null) {
   result = entityutils.tostring(entity);
  }
 } catch (exception e) {
  e.printstacktrace();
 } finally {
  try {
   response.close();
  } catch (ioexception e) {
   e.printstacktrace();
  }
 }
 return result;
}

/**
 * 发送httppost请求,参数为map
 * @param url
 * @param map
 * @return
 */
public static string sendpost(string url, map<string, string> map) {
 list<namevaluepair> formparams = new arraylist<namevaluepair>();
 for (map.entry<string, string> entry : map.entryset()) {
  formparams.add(new basicnamevaluepair(entry.getkey(), entry.getvalue()));
 }
 urlencodedformentity entity = new urlencodedformentity(formparams, consts.utf_8);
 httppost httppost = new httppost(url);
 httppost.setentity(entity);
 closeablehttpresponse response = null;
 try {
  response = httpclient.execute(httppost);
 } catch (ioexception e) {
  e.printstacktrace();
 }
 httpentity entity1 = response.getentity();
 string result = null;
 try {
  result = entityutils.tostring(entity1);
 } catch (exception e) {
  e.printstacktrace();
 }
 return result;
}

/**
 * 发送不带参数的httppost请求
 * @param url
 * @return
 */
public static string sendpost(string url) {
 httppost httppost = new httppost(url);
 closeablehttpresponse response = null;
 try {
  response = httpclient.execute(httppost);
 } catch (ioexception e) {
  e.printstacktrace();
 }
 httpentity entity = response.getentity();
 string result = null;
 try {
  result = entityutils.tostring(entity);
 } catch (exception e) {
  e.printstacktrace();
 }
 return result;
}
 
}

jar包:

1.fastjson-1.2.44.jar

控制层代码:

1.获取access_token

string url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
 + 小程序的appid
 + "&secret="
 + 小程序的secret
 string result = httputil.sendget(url);
 jsonobject object=json.parseobject(result);
 string access_token = object.getstring("access_token");

2.发送订阅消息

 template template=new template(); 
 template.settemplate_id("填写小程序申请的订阅消息id"); 
 template.settouser("用户的openid");
 template.setpage("pages/index/index");
 list<templateparam> paras=new arraylist<templateparam>(); 
 paras.add(new templateparam("character_string2","000001")); 
 paras.add(new templateparam("amount1","888.88")); 
 paras.add(new templateparam("date3","2015年01月05日")); 
 paras.add(new templateparam("thing4","请进入小程序查1看")); 
 template.settemplateparamlist(paras); 
  string requesturl="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.jsonobject jsonresult=commonutil.httpsrequest(requesturl, "post", template.tojson()); 
  if(jsonresult!=null){ 
  system.out.println(jsonresult);
   int errorcode=jsonresult.getint("errcode"); 
   string errormessage=jsonresult.getstring("errmsg"); 
   if(errorcode==0){ 
    system.out.println("send success");
   }else{ 
    system.out.println("订阅消息发送失败:"+errorcode+","+errormessage); 
   } 
  } 

总结

1.本文阅读对象为初学者,所有各种工具类.jar包都粘出来了,直接复制即可使用
2.通过该功能的开发,发现小程序的通知类功能监管更加严格,必须用户授权才可以发订阅消息,同时用户可以更方便的取消订阅,所以建议开发者慎用此功能

到此这篇关于微信小程序订阅消息(java后端实现)开发的文章就介绍到这了,更多相关小程序订阅消息内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!