一,代码实现(后端)
①定义实体类
package com.saic.fin.system.sendInfo;
import lombok.Data;
import java.util.Map;
@Data
public class WxMsgVo {
private String touser;//用户openId
private String template_id;//模版id
private Map<String , TemplateData> data;//推送文字
private String page="pages/index/index";//跳转路径 ,默认跳转到小程序首页
}
package com.saic.fin.system.sendInfo;
public class TemplateData {
private String value;
public TemplateData(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
②定义HttpUtil类(Get请求)
package com.saic.fin.system.util;
import com.alibaba.fastjson.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class HttpUtil {
public static final String APPID = "";//小程序APPID(小程序ID)
public static final String APPSECRET = "";//小程序APPSECRET(小程序秘钥)
public static JSONObject doGetJson(String URL) throws IOException {
JSONObject jsonObject = null;
HttpURLConnection conn = null;
InputStream is = null;
BufferedReader br = null;
StringBuilder result = new StringBuilder();
try {
//创建远程url连接对象
URL url = new URL(URL);
//通过远程url连接对象打开一个连接,强转成HTTPURLConnection类
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
//设置连接超时时间和读取超时时间
conn.setConnectTimeout(15000);
conn.setReadTimeout(60000);
conn.setRequestProperty("Accept", "application/json");
//发送请求
conn.connect();
//通过conn取得输入流,并使用Reader读取
if (200 == conn.getResponseCode()) {
is = conn.getInputStream();
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String line;
while ((line = br.readLine()) != null) {
result.append(line);
System.out.println(line);
}
} else {
System.out.println("ResponseCode is an error code:" + conn.getResponseCode());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
if (is != null) {
is.close();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
conn.disconnect();
}
jsonObject = JSONObject.parseObject(result.toString());
return jsonObject;
}
}
③验证token过期时间
package com.saic.fin.system.OfficialAccounts;
import lombok.Data;
@Data
public class AccessToken {
private String accessToken;
//过期时间 当前系统时间+微信传来的过期时间
private Long expiresTime;
public AccessToken(String accessToken, String expiresIn) {
this.accessToken = accessToken;
this.expiresTime = System.currentTimeMillis()+Integer.parseInt(expiresIn)*1000;
}
/**
* 判断token是否过期
* @return
*/
public boolean isExpired(){
return System.currentTimeMillis()>expiresTime;
}
}
④小程序发送消息
package com.saic.fin.system.sendInfo;
import com.alibaba.fastjson.JSONObject;
import com.saic.fin.system.OfficialAccounts.AccessToken;
import com.saic.fin.system.util.AuthUtil;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;
/**
* 发送小程序订阅消息
*/
public class SendWxMessage {
public static final String APP_ACCESS_TOKEN_URL= "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+HttpUtil.APPID+"&secret="+HttpUtil.APPSECRET;
private static AccessToken at;
public static String push(String openid) {
RestTemplate restTemplate = new RestTemplate();
String accessToken = getToken();
//这里简单起见我们每次都获取最新的access_token(时间开发中,应该在access_token快过期时再重新获取)
String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken;
//拼接推送的模版
WxMsgVo wxMsgVo = new WxMsgVo();
wxMsgVo.setTouser(openid);//用户的openid(要发送给那个用户)
wxMsgVo.setTemplate_id("CFeSWarQLMPyPjwmiy6AV4eB-IZcipu48V8bFLkBzTU");//订阅消息模板id
wxMsgVo.setPage("pages/index/index");
Map<String, TemplateData> m = new HashMap<>(3);
m.put("thing1", new TemplateData("课程"));
m.put("thing6", new TemplateData("大学"));
m.put("thing7", new TemplateData("一节"));
wxMsgVo.setData(m);
ResponseEntity<String> responseEntity =
restTemplate.postForEntity(url, wxMsgVo, String.class);
return responseEntity.getBody();
}
public static String getToken(){
if (at == null || at.isExpired()){
getAccessToken();
}
return at.getAccessToken();
}
/**
* 获取token
*/
private static void getAccessToken() {
//发送请求获取token
JSONObject token = null;
try {
token = AuthUtil.doGetJson(APP_ACCESS_TOKEN_URL);
} catch (Exception e) {
e.printStackTrace();
}
JSONObject jsonObject = token;
String accessToken = (String) jsonObject.get("access_token");
Integer expiresIn = (Integer) jsonObject.get("expires_in");
//创建token对象,并存储
at = new AccessToken(accessToken,String.valueOf(expiresIn));
}
}
AuthUtil工具类
package com.saic.fin.system.util;
import com.alibaba.fastjson.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* 微信授权登录调用Util
*/
public class AuthUtil {
public static final String APPID = "xxxxxx";//小程序APPID(小程序ID)
public static final String APPSECRET = "xxxxxxxxxxx";//小程序APPSECRET(小程序秘钥)
public static JSONObject doGetJson(String URL) throws IOException {
JSONObject jsonObject = null;
HttpURLConnection conn = null;
InputStream is = null;
BufferedReader br = null;
StringBuilder result = new StringBuilder();
try {
//创建远程url连接对象
URL url = new URL(URL);
//通过远程url连接对象打开一个连接,强转成HTTPURLConnection类
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
//设置连接超时时间和读取超时时间
conn.setConnectTimeout(15000);
conn.setReadTimeout(60000);
conn.setRequestProperty("Accept", "application/json");
//发送请求
conn.connect();
//通过conn取得输入流,并使用Reader读取
if (200 == conn.getResponseCode()) {
is = conn.getInputStream();
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String line;
while ((line = br.readLine()) != null) {
result.append(line);
System.out.println(line);
}
} else {
System.out.println("ResponseCode is an error code:" + conn.getResponseCode());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
if (is != null) {
is.close();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
conn.disconnect();
}
jsonObject = JSONObject.parseObject(result.toString());
return jsonObject;
}
}