创建自定义菜单

  • 在com.webchat.util目录下创建SetTemplate类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package com.webchat.util;
import com.webchat.entity.button.*;
import net.sf.json.JSONObject;
import org.junit.Test;
import javax.net.ssl.HttpsURLConnection;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
public class SetTemplate {
//设置自定义菜单
@Test
public void setMenu(){
//创建菜单对象
Button btn = new Button();
//为菜单创建第一个一级菜单
btn.getButton().add(new ClickBut("一级点击","1"));
//为菜单创建第二个一级菜单
btn.getButton().add(new ViewBut("一级跳转","https://www.baidu.com"));
//创建有三个子菜单的一级菜单
SubButton sb = new SubButton("主菜单");
sb.getSub_button().add(new PhotoOrAlbumBut("传图","31"));
sb.getSub_button().add(new ClickBut("点击","32"));
sb.getSub_button().add(new ViewBut("网易新闻","http://news.163.com"));
//把有三个子菜单的一级菜单加入菜单
btn.getButton().add(sb);

//把菜单对象转换为Json
JSONObject jsonObject = JSONObject.fromObject(btn);
//准备url
String url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
url = url.replace("ACCESS_TOKEN",WxService.getOutToken());
//发送post请求,并接收微信服务器传过来的数据
String result = GetAndPost.post(url,jsonObject.toString());
System.out.println(result);
}
}

点击菜单的响应

  • 根据点击菜单事件的类型分别处理,在webservice类增加方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
private static BaseMessage dealEvent(Map<String,String> requestMap){
//用户发来的消息
String event = requestMap.get("Event");
switch (event) {
case "CLICK":
return dealClick(requestMap);

case "VIEW":
return dealView(requestMap);

default:

break;
}
return null;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//处理click事件的按钮菜单,推送消息
private static BaseMessage dealClick(Map<String,String> requestMap){
String key = requestMap.get("EventKey");
switch (key) {
//点击第一个菜单
case "1":
//处理点击第一个一级菜单
return new TextMessage(requestMap,"你刚刚点了第一个一级菜单");

case "32":
//处理点击第三个一级菜单的第二个子菜单
List<Article> articles = new ArrayList<>();
articles.add(new Article("饶唯甲的博客","主要发布一些关于java,python以及前端的学习笔记","https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1575645124939&di=394383e3fc4a237e4a22434e90848360&imgtype=0&src=http%3A%2F%2Fimg2.100bt.com%2Fupload%2Fttq%2F20131124%2F1385272062997_middle.jpg","http://raoweijiapng.github.io"));
return new NewsMessage(requestMap,articles);

default:
break;
}
return null;
}
1
2
3
4
5
//处理view事件的按钮菜单,推送消息
private static BaseMessage dealView(Map<String,String> requestMap){
System.out.println(requestMap);
return null;
}
  • 用百度的API进行图像识别为文字
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//进行图片识别
private static BaseMessage dealImageMessage(Map<String,String> requestMap){
String path = requestMap.get("PicUrl");
String transfer = BaiDuPhoto.transferPhoto(path);
JSONObject jsonObject = JSONObject.fromObject(transfer);
JSONArray jsonArray = jsonObject.getJSONArray("words_result");
System.out.println(jsonArray);

Iterator<JSONObject> it= jsonArray.iterator();
StringBuilder sb = new StringBuilder();
while (it.hasNext()){
JSONObject next = it.next();
System.out.println(next);
sb.append(next.getString("words"));
}
return new TextMessage(requestMap,sb.toString());
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
   package com.webchat.util;
import com.baidu.aip.ocr.AipOcr;
import org.json.JSONObject;

import java.util.HashMap;

//百度的图片翻译文字的API
public class BaiDuPhoto {

//设置APPID/AK/SK
public static final String APP_ID = "17960640";
public static final String API_KEY = "xA1od21hZ5WxkcTuVG6S3kQa";
public static final String SECRET_KEY = "6N0tUQKsGW4GNQ2V3jj3OzgsBjzFXUrd";

public static String transferPhoto(String path) {
// 初始化一个AipOcr
AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);

// 可选:设置网络连接参数
client.setConnectionTimeoutInMillis(2000);
client.setSocketTimeoutInMillis(60000);

// 可选:设置代理服务器地址, http和socket二选一,或者均不设置
//client.setHttpProxy("proxy_host", proxy_port); // 设置http代理
//client.setSocketProxy("proxy_host", proxy_port); // 设置socket代理

// 可选:设置log4j日志输出格式,若不设置,则使用默认配置
// 也可以直接通过jvm启动参数设置此环境变量
//System.setProperty("aip.log4j.conf", "path/to/your/log4j.properties");

// 调用接口,识别本地图片
//JSONObject res = client.basicGeneral(path, new HashMap<String, String>());
HashMap<String, String> options = new HashMap<String, String>();
options.put("language_type", "CHN_ENG");
options.put("detect_direction", "true");
options.put("detect_language", "true");
options.put("probability", "true");
//识别网络图片
JSONObject res = client.basicGeneralUrl(path, options);
System.out.println(res.toString());
return res.toString();
}
}

行业的设置和获取

  • 在com.webchat.util下的setTemplate类增加行业的设置方法
1
2
3
4
5
6
7
8
9
10
11
12
13
//设置行业消息
@Test
public void setIndustryMessage(){
String url = "https://api.weixin.qq.com/cgi-bin/template/api_set_industry?access_token=ACCESS_TOKEN";
url = url.replace("ACCESS_TOKEN",WxService.getOutToken());
String data = "{\n" +
" \"industry_id1\":\"2\",\n" +
" \"industry_id2\":\"4\"\n" +
"}";
//发送post请求,并接收微信服务器传过来的数据
String result = GetAndPost.post(url,data);
System.out.println(result);
}
  • 在com.webchat.util下的setTemplate类增加行业的获取方法
1
2
3
4
5
6
7
8
9
//获得自己的行业消息
@Test
public void getIndustryMessage(){
String url = "https://api.weixin.qq.com/cgi-bin/template/get_industry?access_token=ACCESS_TOKEN";
url = url.replace("ACCESS_TOKEN",WxService.getOutToken());
//发送post请求,并接收微信服务器传过来的数据
String result = GetAndPost.get(url);
System.out.println(result);
}

发送模板消息

  • 在com.webchat.util下的setTemplate类增加发送模板消息的方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
 //发送模板消息
@Test
public void setTemplateMessage(){
String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
url = url.replace("ACCESS_TOKEN",WxService.getOutToken());
String data = " {\n" +
" \"touser\":\"oN04-06h0y9BUvfC87XYPvuDzlKY\",\n" +
" \"template_id\":\"EKaBgMDlnBKdr3-dBTDKbe0A4KyvkA5Y9Q9qZMi4ecY\",\n" +
" \"data\":{\n" +
" \"first\": {\n" +
" \"value\":\"您有新的反馈消息了!\",\n" +
" \"color\":\"#173177\"\n" +
" },\n" +
" \"company\":{\n" +
" \"value\":\"IT甲鱼科技公司\",\n" +
" \"color\":\"#173177\"\n" +
" },\n" +
" \"time\": {\n" +
" \"value\":\"2014年9月22日\",\n" +
" \"color\":\"#173177\"\n" +
" },\n" +
" \"result\": {\n" +
" \"value\":\"面试通过\",\n" +
" \"color\":\"#173177\"\n" +
" },\n" +
" \"remark\":{\n" +
" \"value\":\"详情请和本公司人事专员联系!\",\n" +
" \"color\":\"#173177\"\n" +
" }\n" +
" }\n" +
" }";
//发送post请求,并接收微信服务器传过来的数据
String result = GetAndPost.post(url,data);
System.out.println(result);
}

新增临时素材

  • 在com.webchat.util下的setTemplate类增加上传临时素材的方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
//上传临时素材
@Test
public void testUploadElement(){
String path = "C:/Users/raowe/Pictures/Saved Pictures/13.jpg";
String result = uploadElement(path,"image");
System.out.println(result);
//xYC_CyyVc687iZEanhwbCze0NLslqemG_pBllp6D3SInpYRPyAx4CGsfxs2zvYOz
}

//上传临时素材的方法
public String uploadElement(String path,String type){
File file = new File(path);
//地址
String url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
url = url.replace("ACCESS_TOKEN",WxService.getOutToken()).replace("TYPE",type);
//
try {
URL urlObj = new URL(url);
//强转成https链接
HttpsURLConnection connection = (HttpsURLConnection) urlObj.openConnection();
//设置连接的信息
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
//设置请求头的信息
connection.setRequestProperty("Connection","Keep-Alive");
connection.setRequestProperty("Charset","utf8");
//数据的边界
String boundary = "-----"+System.currentTimeMillis();
connection.setRequestProperty("Content-Type","multipart/form-data;boundary="+boundary);
//获取输出流
OutputStream out = connection.getOutputStream();
//创建文件的输入流
InputStream is = new FileInputStream(file);
//准备数据
//第一部分:头部信息
StringBuilder sb = new StringBuilder();
sb.append("---");
sb.append(boundary);
sb.append("\r\n");
sb.append("Content-Disposition:from-data:name=\"media=\";filename=\""+file.getName()+"\"\r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n");
out.write(sb.toString().getBytes());
//第二部分:文件内容
byte[] b = new byte[1024];
int len;
while ((len=is.read(b)) != -1){
out.write(b,0,len);
}
//第三部分:尾部信息
String foot = "\r\n--"+boundary+"--\r\n";
out.write(foot.getBytes());
out.flush();
out.close();
//读取数据
InputStream is2 = connection.getInputStream();
StringBuilder resp = new StringBuilder();
while ((len=is2.read(b)) != -1){
resp.append(new String(b,0,len));
}
return resp.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

获取临时素材的信息

  • 在com.webchat.util下的setTemplate类增加获取临时素材的方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//获取临时素材
@Test
public void testGetElement(){
String url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
url = url.replace("ACCESS_TOKEN",WxService.getOutToken()).replace("MEDIA_ID","xYC_CyyVc687iZEanhwbCze0NLslqemG_pBllp6D3SInpYRPyAx4CGsfxs2zvYOz");
URL urlObj = null;
try {
urlObj = new URL(url);
//开连接
URLConnection conn = urlObj.openConnection();
Map<String, List<String>> map = conn.getHeaderFields();
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
System.out.println("Key : " + entry.getKey() +
" ,Value : " + entry.getValue());
}
} catch (Exception e) {
e.printStackTrace();
}
}