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

网友投稿 154 2023-07-02


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

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 验证方法

3.3 接收用户信息,并解密

/*

* ------------对用户回复的消息解密---------------

* 用户回复消息或者点击事件响应时,企业会收到回调消息,此消息是经过公众平台加密之后的密文以post形式发送给企业,密文格式请参考官方文档

* 假设企业收到公众平台的回调消息如下: POST /cgi-bin/wxpush?

* msg_signature=477715d11cdb4164915debcba66cb864d751f3e6

* tamp=1409659813&nonce=1372623149 HTTP/1.1 Host: qy.weixin.qq.com

* Content-Length: 613

* <![CDATA[wx5823bf96d3bd56c7]]>

* ><![CDATA[RypEvHKD8QQKFhvQ6QleEB4J58tiPdvo

* +rtK1I9qca6aM/wvqnLSV5zEPeusUiX5L5X/0lWfrf0QADHHhGd3QczcdCUpj911L3vg3W/

* sYYvuJTs3TUUkSUXxaccAS0qhxchrRYt66wiSpGLYL42aM6A8dTT

* +6k4aSknmPj48kzjs8qLjvd4Xgpue06DOdnLxAUHzM6

* +kDZ+HMZfJYuR+LtwGc2hgf5gsijff0ekUNXZiqATP7PF5mZxZ3Izoun1s4zG4LUMnvw2r

* +KqCKIw

* +3IQH03v+BCA9nMELNqbSf6tiWSrXJB3LAVGUcallcrw8V2t9EL4EhzJWrQUax5wLVMNS0

* +rUPA3k22Ncx4XXZS9o0MBH27Bo6BpNelZpS

* +/uh9KsNlY6bHCmJU9p8g7m3fVKn28H3KDYA5Pl

* /T8Z1ptDAVe0lXdQ2YoyyH2uyPIGHBZZIs2pDBS8R07+qN+E7Q==]]>

* <![CDATA[218]]>

*

* 企业收到post请求之后应该

* 1.解析出url上的参数,包括消息体签名(msg_signature),时间戳(timestamp)以及随机数字串(nonce)

* 2.验证消息体签名的正确性。

* 3.将post请求的数据进行xml解析,并将标签的内容进行解密,解密出来的明文即是用户回复消息的明文,明文格式请参考官方文档

* 第2,3步可以用公众平台提供的库函数DecryptMsg来实现。

*/

@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 =

// "<![CDATA[wx5823bf96d3bd56c7]]><![CDATA[RypEvHKD8QQKFhvQ6QleEB4J58tiPdvo+rtK1I9qca6aM/wvqnLSV5zEPeusUiX5L5X/0lWfrf0QADHHhGd3QczcdCUpj911L3vg3W/sYYvuJTs3TUUkSUXxaccAS0qhxchrRYt66wiSpGLYL42aM6A8dTT+6k4aSknmPj48kzJs8qLjvd4Xgpue06DOdnLxAUHzM6+kDZ+HMZfJYuR+LtwGc2hgf5gsijff0ekUNXZiqATP7PF5mZxZ3Izoun1s4zG4LUMnvw2r+KqCKIw+3IQH03v+BCA9nMELNqbSf6tiWSrXJB3LAVGUcallcrw8V2t9EL4EhzJWrQUax5wLVMNS0+rUPA3k22Ncx4XXZS9o0MBH27Bo6BpNelZpS+/uh9KsNlY6bHCmJU9p8g7m3fVKn28H3KDYA5Pl/T8Z1ptDAVe0lXdQ2YoyyH2uyPIGHBZZIs2pDBS8R07+qN+E7Q==]]><![CDATA[218]]>";

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("Chttp://ontent");

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

/**

* 此方法可以发送任意类型消息

*

* @param msgType

* text|image|voice|video|file|news

* @param touser

* 成员ID列表(消息接收者,多个接收者用‘|'分隔,最多支持1000个)。特殊情况:指定为@all,

* 则向关注该企业应用的全部成员发送

* @param toparty

* 部门ID列表,多个接收者用‘|'分隔,最多支持100个。当touser为@all时忽略本参数

* @param totag

* 标签ID列表,多个接收者用‘|'分隔。当touser为@all时忽略本参数

* @param content

* msgType=text时 ,文本消息内容

* @param mediaId

* msgType=image|voice|video时 ,对应消息信息ID(--------)

* @param title

* msgType=news|video时,消息标题

* @param description

* msgType=news|video时,消息描述

* @param url

* msgType=news时,消息链接

* @param picurl

* msgType=news时,图片路径

* @param safe

* 表示是否是保密消息,0表示否,1表示是,默认0

*/

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://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/*

5. 开发完成的全量代码

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


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:基于百度地图实现产品销售的单位位置查看功能设计与实现
下一篇:java中使用session监听实现同帐号登录限制、登录人数限制
相关文章

 发表评论

暂时没有评论,来抢沙发吧~