栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

微信企业号验证/发送/接收消息

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

微信企业号验证/发送/接收消息

1. 内网映射

由于微信企业号回调模式的URL尽支持域名方式访问,估需要注册花生壳,做一个内网穿透(需要花16块钱,购买一个免费版,购买之后,第二天才能添加上域名)

2. 微信企业号

注册微信企业号:https://qy.weixin.qq.com/ (选择团队,团队不需要认证)

通讯录:新建组织 - > 关注成员

企业号 -> 应用中心 -> 新建应用 -> 消息型应用 -> 模式选择(回调模式) -> 开启微信消息转发,
回调模式说明:http://qydev.weixin.qq.com/wiki/index.PHP?title=%E5%9B%9E%E8%B0%83%E6%A8%A1%E5%BC%8F
回调模式加密解密代码:http://qydev.weixin.qq.com/wiki/index.php?title=%E5%8A%A0%E8%A7%A3%E5%AF%86%E5%BA%93%E4%B8%8B%E8%BD%BD%E4%B8%8E%E8%BF%94%E5%9B%9E%E7%A0%81

如图1:

自定义菜单: 开发应用的请求路径如图2:

设置 -> 功能设置 -> 权限管理 -> 新建管理组 -> 应用权限( Secret )

3. 利用Jersey开发web Service服务

3.1 在类中定义token, 随机密码43位,公司corpId, secret

3.2 验证方法

 
 
@GET 
@Path("station") 
public String verify() { 
String msgSignature = request.getParameter("msg_signature"); 
String timeStamp = request.getParameter("timestamp"); 
String nonce = request.getParameter("nonce"); 
System.out.println(timeStamp + " " + nonce); 
String echostr = request.getParameter("echostr"); 
String sEchoStr = null; 
try { 
sEchoStr = wxcpt.VerifyURL(msgSignature, timeStamp, nonce, echostr); 
} catch (Exception e) { 
e.printStackTrace();// 验证URL失败,错误原因请查看异常 
} 
return sEchoStr; 
}

3.3 接收用户信息,并解密

 
@POST 
@Path("station") 
public String receiveMsg(String reqData) { 
String msgSignature = request.getParameter("msg_signature"); 
String timeStamp = request.getParameter("timestamp"); 
String nonce = request.getParameter("nonce"); 
// post请求的密文数据 
// String sReqData = 
// ""; 
try { 
String sMsg = wxcpt.DecryptMsg(msgSignature, timeStamp, nonce, 
reqData); 
// 解析出明文xml标签的内容进行处理 
documentBuilderFactory dbf = documentBuilderFactory.newInstance(); 
documentBuilder db = dbf.newdocumentBuilder(); 
StringReader sr = new StringReader(sMsg); 
InputSource is = new InputSource(sr); 
document document = db.parse(is); 
Element root = document.getdocumentElement(); 
NodeList nodelist1 = root.getElementsByTagName("Content"); 
if (nodelist1.item(0) == null) 
return "ok"; 
String Content = nodelist1.item(0).getTextContent(); 
System.out.println("Content:" + Content); 
} catch (Exception e) { 
e.printStackTrace();// 解密失败,失败原因请查看异常 
} 
return "ok"; 
}

3.4 发送信息到微信

设置 -> 功能设置 -> 权限管理 -> 新建管理组; 获取secret

 
public void sendWeChatMsg(String msgType, String touser, String toparty, 
String totag, String content, String mediaId, String title, 
String description, String url, String picurl, String safe) { 
URL uRl; 
String ACCESS_TOKEN = getAccessToken(); 
// 拼接请求串 
String action = CREATE_SESSION_URL + ACCESS_TOKEN; 
// 封装发送消息请求json 
StringBuffer sb = new StringBuffer(); 
sb.append("{"); 
sb.append(""touser":" + """ + touser + "","); 
sb.append(""toparty":" + """ + toparty + "","); 
sb.append(""totag":" + """ + totag + "","); 
if (msgType.equals("text")) { 
sb.append(""msgtype":" + """ + msgType + "","); 
sb.append(""text":" + "{"); 
sb.append(""content":" + """ + content + """); 
sb.append("}"); 
} else if (msgType.equals("image")) { 
sb.append(""msgtype":" + """ + msgType + "","); 
sb.append(""image":" + "{"); 
sb.append(""media_id":" + """ + mediaId + """); 
sb.append("}"); 
} else if (msgType.equals("voice")) { 
sb.append(""msgtype":" + """ + msgType + "","); 
sb.append(""voice":" + "{"); 
sb.append(""media_id":" + """ + mediaId + """); 
sb.append("}"); 
} else if (msgType.equals("video")) { 
sb.append(""msgtype":" + """ + msgType + "","); 
sb.append(""video":" + "{"); 
sb.append(""media_id":" + """ + mediaId + "","); 
sb.append(""title":" + """ + title + "","); 
sb.append(""description":" + """ + description + """); 
sb.append("}"); 
} else if (msgType.equals("file")) { 
sb.append(""msgtype":" + """ + msgType + "","); 
sb.append(""file":" + "{"); 
sb.append(""media_id":" + """ + mediaId + """); 
sb.append("}"); 
} else if (msgType.equals("news")) { 
sb.append(""msgtype":" + """ + msgType + "","); 
sb.append(""news":" + "{"); 
sb.append(""articles":" + "["); 
sb.append("{"); 
sb.append(""title":" + """ + title + "","); 
sb.append(""description":" + """ + description + "","); 
sb.append(""url":" + """ + url + "","); 
sb.append(""picurl":" + """ + picurl + """); 
sb.append("}"); 
sb.append("]"); 
sb.append("}"); 
} 
sb.append(","safe":" + """ + safe + "","); 
sb.append(""agentid":" + """ + 1 + "","); 
sb.append(""debug":" + """ + "1" + """); 
sb.append("}"); 
String json = sb.toString(); 
try { 
uRl = new URL(action); 
HttpsURLConnection http = (HttpsURLConnection) uRl.openConnection(); 
http.setRequestMethod("POST"); 
http.setRequestProperty("Content-Type", 
"application/json;charset=UTF-8"); 
http.setDoOutput(true); 
http.setDoInput(true); 
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 
// 连接超时30秒 
System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 
// 读取超时30秒 
http.connect(); 
OutputStream os = http.getOutputStream(); 
os.write(json.getBytes("UTF-8"));// 传入参数 
InputStream is = http.getInputStream(); 
int size = is.available(); 
byte[] jsonBytes = new byte[size]; 
is.read(jsonBytes); 
String result = new String(jsonBytes, "UTF-8"); 
System.out.println("请求返回结果:" + result); 
os.flush(); 
os.close(); 
} catch (Exception e) { 
e.printStackTrace(); 
} 
} 
// 获取接口访问权限码 
public String getAccessToken() { 
HttpClient client = new HttpClient(); 
PostMethod post = new PostMethod(ACCESS_TOKEN_URL); 
post.releaseConnection(); 
post.setRequestHeader("Content-Type", 
"application/x-www-form-urlencoded;charset=UTF-8"); 
NamevaluePair[] param = { new NamevaluePair("corpid", corpId), 
new NamevaluePair("corpsecret", secret) }; 
// 设置策略,防止报cookie错误 
DefaultHttpParams.getDefaultParams().setParameter( 
"http.protocol.cookie-policy", 
cookiePolicy.BROWSER_COMPATIBILITY); 
// 给post设置参数 
post.setRequestBody(param); 
String result = ""; 
try { 
client.executeMethod(post); 
result = new String(post.getResponseBodyAsString().getBytes("gbk")); 
} catch (IOException e) { 
e.printStackTrace(); 
} 

// 将数据转换成json 
JSonObject jasonObject; 

jasonObject = JSONObject.fromObject(result); 
result = (String) jasonObject.get("access_token"); 

post.releaseConnection(); 
System.out.println(result); 
return result; 

} 
public static void main(String[] args) { 
StationResource weChat = new StationResource(); 
// weChat.sendWeChatMsgText("@all", "2", "", "信息中心通知", "0"); 
weChat.sendWeChatMsg("news", "@all", "", "", "测试senMsg", "", "测试的", 
"真的是测试的", "http://www.baidu.com", 
"http://file27.mafengwo.net/M00/B2/12/wKgB6lO0ahWAMhL8AAV1yBFJDJw20.jpeg", "0"); 
}

4. 开发完成。 需要将该类在webx.xml中添加到rest中管理

 
 
 
JAX-RS REST Servlet 
com.sun.jersey.spi.container.servlet.ServletContainer 
 
com.sun.jersey.config.property.packages 
com.base.pf.restful 
 
2 
 
 
JAX-RS REST Servlet 
/rest 
@Path("wx") 
public class StationResource { 
// http://hichinamobile.xicp.net/security/rest/wx 
// https://qy.weixin.qq.com 
private String token = "spm"; // 企业号 -> 应用中心 -> 新建应用 -> 消息型应用 
private String agentId = "1"; // 企业号 -> 应用中心 -> 点开应用中 -> 应用ID 
private String encodingAesKey = "nT6ZWTVFlyNXOhFOGGOZWdJpAgeFSV8ln5CNeYw7mwl"; // 企业号 -> 应用中心 -> 新建应用 -> 消息型应用 
private String corpId = "wxe49318eb604cf00b"; // 企业号 -> 设置 -> 企业号信息 -> 账号信息 
private String secret = "M-YFKmgl_kXBVEtginZH3RQWbz4xb6MFeQXXLk77mkpxZenFDYq-UgerxdUF8rel"; // 企业号 -> 设置 -> 功能设置 -> 权限管理中 
@Context 
HttpServletRequest request; 
@Context 
HttpServletResponse response; 
WXBizMsgCrypt wxcpt = null; 
public StationResource() { 
try { 
wxcpt = new WXBizMsgCrypt(token, encodingAesKey, corpId); 
} catch (AesException e) { 
e.printStackTrace(); 
} 
} 
// 获取访问权限码URL 
private final static String ACCESS_TOKEN_URL = "https://qyapi.weixin.qq.com/cgi-bin/gettoken"; 
// 创建会话请求URL 
private final static String CREATE_SESSION_URL = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="; 
// 获取接口访问权限码 
public String getAccessToken() { 
HttpClient client = new HttpClient(); 
PostMethod post = new PostMethod(ACCESS_TOKEN_URL); 
post.releaseConnection(); 
post.setRequestHeader("Content-Type", 
"application/x-www-form-urlencoded;charset=UTF-8"); 
NamevaluePair[] param = { new NamevaluePair("corpid", corpId), 
new NamevaluePair("corpsecret", secret) }; 
// 设置策略,防止报cookie错误 
DefaultHttpParams.getDefaultParams().setParameter( 
"http.protocol.cookie-policy", 
cookiePolicy.BROWSER_COMPATIBILITY); 
// 给post设置参数 
post.setRequestBody(param); 
String result = ""; 
try { 
client.executeMethod(post); 
result = new String(post.getResponseBodyAsString().getBytes("gbk")); 
} catch (IOException e) { 
e.printStackTrace(); 
} 
// 将数据转换成json 
JSonObject jasonObject; 
jasonObject = JSONObject.fromObject(result); 
result = (String) jasonObject.get("access_token"); 
post.releaseConnection(); 
System.out.println(result); 
return result; 
} 
 
 
@GET 
@Path("station") 
public String verify() { 
String msgSignature = request.getParameter("msg_signature"); 
String timeStamp = request.getParameter("timestamp"); 
String nonce = request.getParameter("nonce"); 
System.out.println(timeStamp + " " + nonce); 
String echostr = request.getParameter("echostr"); 
String sEchoStr = null; 
try { 
sEchoStr = wxcpt.VerifyURL(msgSignature, timeStamp, nonce, echostr); 
} catch (Exception e) { 
e.printStackTrace();// 验证URL失败,错误原因请查看异常 
} 
return sEchoStr; 
} 
 
@POST 
@Path("station") 
public String receiveMsg(String reqData) { 
String msgSignature = request.getParameter("msg_signature"); 
String timeStamp = request.getParameter("timestamp"); 
String nonce = request.getParameter("nonce"); 
// post请求的密文数据 
// String sReqData = 
// ""; 
try { 
String sMsg = wxcpt.DecryptMsg(msgSignature, timeStamp, nonce, 
reqData); 
// 解析出明文xml标签的内容进行处理 
documentBuilderFactory dbf = documentBuilderFactory.newInstance(); 
documentBuilder db = dbf.newdocumentBuilder(); 
StringReader sr = new StringReader(sMsg); 
InputSource is = new InputSource(sr); 
document document = db.parse(is); 
Element root = document.getdocumentElement(); 
NodeList nodelist1 = root.getElementsByTagName("Content"); 
if (nodelist1.item(0) == null) 
return "ok"; 
String Content = nodelist1.item(0).getTextContent(); 
System.out.println("Content:" + Content); 
} catch (Exception e) { 
e.printStackTrace();// 解密失败,失败原因请查看异常 
} 
return "ok"; 
} 
 
// @GET 
// @Path("send") 
public void sendMsg(String timeStamp, String nonce) { 
String sRespData = "134883186012345678901234561"; 
try { 
String sEncryptMsg = wxcpt.EncryptMsg(sRespData, timeStamp, nonce); 
System.out.println("after encrypt sEncrytMsg: " + sEncryptMsg); 
response.getWriter().print(sEncryptMsg); 
} catch (Exception e) { 
e.printStackTrace();// 加密失败 
} 
// return sRespData; 
} 
 
public void sendWeChatMsg(String msgType, String touser, String toparty, 
String totag, String content, String mediaId, String title, 
String description, String url, String picurl, String safe) { 
URL uRl; 
String ACCESS_TOKEN = getAccessToken(); 
// 拼接请求串 
String action = CREATE_SESSION_URL + ACCESS_TOKEN; 
// 封装发送消息请求json 
StringBuffer sb = new StringBuffer(); 
sb.append("{"); 
sb.append(""touser":" + """ + touser + "","); 
sb.append(""toparty":" + """ + toparty + "","); 
sb.append(""totag":" + """ + totag + "","); 
if (msgType.equals("text")) { 
sb.append(""msgtype":" + """ + msgType + "","); 
sb.append(""text":" + "{"); 
sb.append(""content":" + """ + content + """); 
sb.append("}"); 
} else if (msgType.equals("image")) { 
sb.append(""msgtype":" + """ + msgType + "","); 
sb.append(""image":" + "{"); 
sb.append(""media_id":" + """ + mediaId + """); 
sb.append("}"); 
} else if (msgType.equals("voice")) { 
sb.append(""msgtype":" + """ + msgType + "","); 
sb.append(""voice":" + "{"); 
sb.append(""media_id":" + """ + mediaId + """); 
sb.append("}"); 
} else if (msgType.equals("video")) { 
sb.append(""msgtype":" + """ + msgType + "","); 
sb.append(""video":" + "{"); 
sb.append(""media_id":" + """ + mediaId + "","); 
sb.append(""title":" + """ + title + "","); 
sb.append(""description":" + """ + description + """); 
sb.append("}"); 
} else if (msgType.equals("file")) { 
sb.append(""msgtype":" + """ + msgType + "","); 
sb.append(""file":" + "{"); 
sb.append(""media_id":" + """ + mediaId + """); 
sb.append("}"); 
} else if (msgType.equals("news")) { 
sb.append(""msgtype":" + """ + msgType + "","); 
sb.append(""news":" + "{"); 
sb.append(""articles":" + "["); 
sb.append("{"); 
sb.append(""title":" + """ + title + "","); 
sb.append(""description":" + """ + description + "","); 
sb.append(""url":" + """ + url + "","); 
sb.append(""picurl":" + """ + picurl + """); 
sb.append("}"); 
sb.append("]"); 
sb.append("}"); 
} 
sb.append(","safe":" + """ + safe + "","); 
sb.append(""agentid":" + """ + agentId + "","); 
sb.append(""debug":" + """ + "1" + """); 
sb.append("}"); 
String json = sb.toString(); 
try { 
uRl = new URL(action); 
HttpsURLConnection http = (HttpsURLConnection) uRl.openConnection(); 
http.setRequestMethod("POST"); 
http.setRequestProperty("Content-Type", 
"application/json;charset=UTF-8"); 
http.setDoOutput(true); 
http.setDoInput(true); 
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 
// 连接超时30秒 
System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 
// 读取超时30秒 
http.connect(); 
OutputStream os = http.getOutputStream(); 
os.write(json.getBytes("UTF-8"));// 传入参数 
InputStream is = http.getInputStream(); 
int size = is.available(); 
byte[] jsonBytes = new byte[size]; 
is.read(jsonBytes); 
String result = new String(jsonBytes, "UTF-8"); 
System.out.println("请求返回结果:" + result); 
os.flush(); 
os.close(); 
} catch (Exception e) { 
e.printStackTrace(); 
} 
} 
public static void main(String[] args) { 
StationResource weChat = new StationResource(); 
// weChat.sendWeChatMsgText("@all", "2", "", "信息中心通知", "0"); 
weChat.sendWeChatMsg("news", "@all", "", "", "测试senMsg", "", "测试的", 
"真的是测试的", "http://www.baidu.com", 
"http://file27.mafengwo.net/M00/B2/12/wKgB6lO0ahWAMhL8AAV1yBFJDJw20.jpeg", "0"); 
} 
}

以上所述是小编给大家介绍的微信企业号验证/发送/接收消息,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对考高分网网站的支持!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/148879.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号