需求:打开微信小程序,点击首页Banner,跳转到客服对话框,然后客服自动回复一张二维码;
第一步,配置服务器,开发者需要登录微信公众平台
在此页面的开发--开发设置--消息推送中进行相关配置,配置如下图:
数据格式我选择的是Json,消息加密方式由于没有敏感数据,所以选择的是 明文模式
此处配置,按照文档一步步配置即可;
第二步,配置好微信服务器后,Java代码中,第一步,校验配置URL的有效性(get请求)
···
@RequestMapping(value = "weChatToken", method = RequestMethod.GET)
public void weChatToken(HttpServletRequest request, HttpServletResponse response) {
boolean isGet = request.getMethod().toLowerCase().equals("get");
if (isGet) {
// 微信加密签名
String signature = request.getParameter("signature");
// 时间戳
String timestamp = request.getParameter("timestamp");
// 随机数
String nonce = request.getParameter("nonce");
// 随机字符串
String echostr = request.getParameter("echostr");
// 通过检验signature对请求进行校验,若校验成功则原样返回echostr,表示接入成功,否则接入失败
if (signature != null && WeChatUtil.checkSignature(signature, timestamp, nonce)) {
logger.debug("signature == " + signature);
try {
PrintWriter print = response.getWriter();
print.write(echostr);
print.flush();
} catch (IOException e) {
logger.error("微信消息接收和token验证异常", e);
}
}
}
}
···
WeChatUtils方法如下
package com.yiaitech.pandt.util;
import com.alibaba.fastjson.JSONObject;
import com.yiaitech.pandt.dto.ImageMessageResponseVo;
import com.yiaitech.pandt.dto.TextMessageResponseVo;
import lombok.extern.slf4j.Slf4j;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Formatter;
/**
* @author: hugh_lin
* @date: 2019/06/26 15:45
* @Description: 微信消息处理工具类
* @Modifed:
**/
@Slf4j
public class WeChatUtil {
//请求消息的类型------------------------------------------
/**
* 文本
*/
public static final String REQ_MESSAGE_TYPE_TEXT = "text";
/**
* 图片
*/
public static final String REQ_MESSAGE_TYPE_IMAGE = "image";
/**
* 语音
*/
public static final String REQ_MESSAGE_TYPE_VOICE = "voice";
/**
* 视频
*/
public static final String REQ_MESSAGE_TYPE_VIDEO = "video";
/**
* 小视频
*/
public static final String REQ_MESSAGE_TYPE_SHORTVIDEO = "shortvideo";
/**
* 地理位置
*/
public static final String REQ_MESSAGE_TYPE_LOCATION = "location";
/**
* 链接
*/
public static final String REQ_MESSAGE_TYPE_LINK = "link";
/**
* 事件推送
*/
public static final String REQ_MESSAGE_TYPE_EVENT = "event";
/**
* 事件类型--订阅
*/
public static final String EVENT_TYPE_SUBSCRIBE = "subscribe";
/**
* 取消订阅
*/
public static final String EVENT_TYPE_UNSUBSCRIBE = "unsubscribe";
/**
* 已关注用户扫描带参数二维码
*/
public static final String EVENT_TYPE_SCAN = "SCAN";
/**
* 上报地理位置
*/
public static final String EVENT_TYPE_LOCATION = "LOCATION";
/**
* 自定义菜单事件
*/
public static final String EVENT_TYPE_CLICK = "CLICK";
//响应消息类型
/**
* 文本
*/
public static final String RESP_MESSAGE_TYPE_TEXT = "text";
/**
* 图片
*/
public static final String RESP_MESSAGE_TYPE_IMAGE = "image";
/**
* 语音
*/
public static final String RESP_MESSAGE_TYPE_VOICE = "voice";
/**
* 视频
*/
public static final String RESP_MESSAGE_TYPE_VIDEO = "video";
/**
* 音乐
*/
public static final String RESP_MESSAGE_TYPE_MUSIC = "music";
/**
* 图文
*/
public static final String RESP_MESSAGE_TYPE_ARTICLE = "news";
//---------------------------------------------------------------------
/**
* 与测试账号接口配置信息中的Token要一致
* 测试token,微信公众号内可自行配置
*/
private static String token = "f8fbc22bbfc6b0a5ceac74e1b3b626b4";
/**
* 验证签名
*
* @param signature
* @param timestamp
* @param nonce
* @return
*/
public static boolean checkSignature(String signature, String timestamp, String nonce) {
String[] arr = new String[]{token, timestamp, nonce};
// 将token、timestamp、nonce三个参数进行字典序排序
Arrays.sort(arr);
StringBuilder content = new StringBuilder();
for (int i = 0; i < arr.length; i++) {
content.append(arr[i]);
}
MessageDigest md = null;
String tmpStr = null;
log.debug(content.toString());
try {
md = MessageDigest.getInstance("SHA-1");
// 将三个参数字符串拼接成一个字符串进行sha1加密
byte[] digest = md.digest(content.toString().getBytes());
tmpStr = byteToHex(digest);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
// 将sha1加密后的字符串可与signature对比,标识该请求来源于微信
return tmpStr != null ? tmpStr.equals(signature) : false;
}
/**
* 十六进制字节数组转为字符串
*
* @param hash
* @return
*/
private static String byteToHex(final byte[] hash) {
Formatter formatter = new Formatter();
for (byte b : hash) {
formatter.format("%02x", b);
}
String result = formatter.toString();
formatter.close();
return result;
}
/**
* 链接url下载图片
*
* @param urlList
* @param path
*/
public static void downloadPicture(String urlList, String path) {
URL url = null;
try {
url = new URL(urlList);
DataInputStream dataInputStream = new DataInputStream(url.openStream());
FileOutputStream fileOutputStream = new FileOutputStream(new File(path));
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = dataInputStream.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
fileOutputStream.write(output.toByteArray());
dataInputStream.close();
fileOutputStream.close();
} catch (Exception e) {
log.error("根据url下载图片异常", e);
}
}
/**
* @param requestUrl 微信上传临时素材的接口url
* @param file 要上传的文件
* @return String 上传成功后,微信服务器返回的消息
* @desc :微信上传素材的请求方法
*/
public static String httpRequest(String requestUrl, File file) {
StringBuffer buffer = new StringBuffer();
try {
//1.建立连接
URL url = new URL(requestUrl);
HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection(); //打开链接
//1.1输入输出设置
httpUrlConn.setDoInput(true);
httpUrlConn.setDoOutput(true);
httpUrlConn.setUseCaches(false); // post方式不能使用缓存
//1.2设置请求头信息
httpUrlConn.setRequestProperty("Connection", "Keep-Alive");
httpUrlConn.setRequestProperty("Charset", "UTF-8");
//1.3设置边界
String BOUNDARY = "----------" + System.currentTimeMillis();
httpUrlConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
// 请求正文信息
// 第一部分:
//2.将文件头输出到微信服务器
StringBuilder sb = new StringBuilder();
sb.append("--"); // 必须多两道线
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data;name=\"media\";filelength=\"" + file.length()
+ "\";filename=\"" + file.getName() + "\"\r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n");
byte[] head = sb.toString().getBytes("utf-8");
// 获得输出流
OutputStream outputStream = new DataOutputStream(httpUrlConn.getOutputStream());
// 将表头写入输出流中:输出表头
outputStream.write(head);
//3.将文件正文部分输出到微信服务器
// 把文件以流文件的方式 写入到微信服务器中
DataInputStream in = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
outputStream.write(bufferOut, 0, bytes);
}
in.close();
//4.将结尾部分输出到微信服务器
byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
outputStream.write(foot);
outputStream.flush();
outputStream.close();
//5.将微信服务器返回的输入流转换成字符串
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();
} catch (IOException e) {
System.out.println("发送POST请求出现异常!" + e);
e.printStackTrace();
}
//4.json字符串转对象:解析返回值,json反序列化
String result = buffer.toString().replaceAll("[\\\\]", "");
System.out.println("result:" + result);
JSONObject resultJSON = JSONObject.parseObject(result);
return resultJSON.getString("media_id");
}
}
URL地址验证没有问题后,接下来,就需要开始自动回复了,查看
微信客服消息自动回复API
可以看到,自动回复图片的请求参数中,有一个media_id和touser是需要用户上传的
media_id需要通过上传素材到微信服务器来得到
touser :是微信主动请求开发者在第一步配置的消息推送服务配置中配置的那个URL地址,请求方式是Post请求
首先来看看如何得到media_id,即上传素材到微信服务器
官方文档请查看微信上传临时素材API开发者也可以选择永久素材,这个由开发者自行选择,本文所提到的是上传临时素材中的上传图片
/**
* @param requestUrl 微信上传临时素材的接口url
* @param file 要上传的文件
* @return String 上传成功后,微信服务器返回的消息
* @desc :微信上传素材的请求方法
*/
public static String httpRequest(String requestUrl, File file) {
StringBuffer buffer = new StringBuffer();
try {
//1.建立连接
URL url = new URL(requestUrl);
HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection(); //打开链接
//1.1输入输出设置
httpUrlConn.setDoInput(true);
httpUrlConn.setDoOutput(true);
httpUrlConn.setUseCaches(false); // post方式不能使用缓存
//1.2设置请求头信息
httpUrlConn.setRequestProperty("Connection", "Keep-Alive");
httpUrlConn.setRequestProperty("Charset", "UTF-8");
//1.3设置边界
String BOUNDARY = "----------" + System.currentTimeMillis();
httpUrlConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
// 请求正文信息
// 第一部分:
//2.将文件头输出到微信服务器
StringBuilder sb = new StringBuilder();
sb.append("--"); // 必须多两道线
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data;name=\"media\";filelength=\"" + file.length()
+ "\";filename=\"" + file.getName() + "\"\r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n");
byte[] head = sb.toString().getBytes("utf-8");
// 获得输出流
OutputStream outputStream = new DataOutputStream(httpUrlConn.getOutputStream());
// 将表头写入输出流中:输出表头
outputStream.write(head);
//3.将文件正文部分输出到微信服务器
// 把文件以流文件的方式 写入到微信服务器中
DataInputStream in = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
outputStream.write(bufferOut, 0, bytes);
}
in.close();
//4.将结尾部分输出到微信服务器
byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
outputStream.write(foot);
outputStream.flush();
outputStream.close();
//5.将微信服务器返回的输入流转换成字符串
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();
} catch (IOException e) {
System.out.println("发送POST请求出现异常!" + e);
e.printStackTrace();
}
//4.json字符串转对象:解析返回值,json反序列化
String result = buffer.toString().replaceAll("[\\\\]", "");
System.out.println("result:" + result);
JSONObject resultJSON = JSONObject.parseObject(result);
return resultJSON.getString("media_id");
}
上述代码即可获取到自动回复中所提到的media_id
接来下,获取touser,也就是对方的openId
/**
* 微信公众号 -->
* 消息管理 -->
* 接收普通消息、接收事件推送、被动回复用户消息
*
* @param request
* @return
*/
@ResponseBody
@RequestMapping(value = "/weChatToken", method = RequestMethod.POST)
public String responseEvent(HttpServletRequest request) {
try {
// logger.info("获取到参数为:{}", msg);
// 获取到请求参数
String body = getParm(request);
// Map<String, String> requestMessageMap = XmlUtil.xmlToMap(body);
// logger.info("获取到参数为:{}", requestMessageMap.get("ToUserName"));
JSONObject jsonObject = JSONObject.parseObject(body);
String openId = jsonObject.getString("FromUserName");//这里查出来的就是OpenId;
// 判断请求参数中 MsgType的值或判断Event值
String returnMessage =
weChatMsgService.sendMessage(openId, WeChatUtil.REQ_MESSAGE_TYPE_IMAGE);
System.out.println("微信自动回复结果 +++++++》》》》》》》》》》》》" + returnMessage);
return "SUCCESS";
} catch (Exception e) {
logger.error("微信公众号自动回复异常", e);
}
return "SUCCESS";
}
打开微信客服对话框后,微信服务器会主动请求开发者服务URL,也就是刚刚上面所配置的URL,请求方式是post请求,请求参数中,我们可以拿到一个FromUserName,也就是对应的用户的openId,这样我们就拿到了自动回复的所有参数;
接来下,就是自动回复的代码了
@Override
public String sendMessage(String openId, String msgType) {
//先上传临时素材到微信服务
String result = autoReplay(openId, WeChatUtil.REQ_MESSAGE_TYPE_IMAGE);
return result;
}
/**
* 自动回复
*
* @param
* @return
*/
@Override
public String autoReplay(String openId, String type) {
//获取微信token
String accessToken = weiXinToken.getAccessToken();
// stringRedisTemplate.opsForValue().set(WECHAT_TOKEN, accessToken);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
File file = new File(IMAGE_PATH);
if (!file.exists() || !file.isFile()) {
return null;
}
StringBuilder sb = new StringBuilder();
sb.append(weixinImageUpload)
.append("access_token=")
.append(accessToken)
.append("&type=")
.append(type);
String mediaId = WeChatUtil.httpRequest(sb.toString(), file);
// stringRedisTemplate.opsForValue().set(PERPETUAL_MEDIA_ID, mediaId);
String url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + accessToken;
AutoReplayBean bean = new AutoReplayBean();
bean.setTouser(openId);
bean.setMsgtype("image");
AutoReplay autoReplay = new AutoReplay();
autoReplay.setMedia_id(mediaId);
bean.setImage(autoReplay);
String jsonString = JSONObject.toJSONString(bean);
ResponseEntity<String> response = restTemplate.postForEntity(url, jsonString, String.class);
System.out.println("sendMessage >>>>>>>" + response.getBody());
// 发送结果
return mediaId;
}
到此,微信自动回复图片就基本完成