上次说到Token(令牌会校验失败的问题)
现在正式上代码了,因为这个是要和服务器端做安全校验才能通过的:
上传填写的URL(服务器地址)是你指定接收服务器端的地址—填写好了之后写上请求过来的代码。
package com.xcx.action;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
@ParentPackage("struts-default")
@Namespace("/appletNews")
public class AppletNewsAction extends ActionSupport {
private static final long serialVersionUID = 1L;
protected HttpServletRequest request = ServletActionContext.getRequest();
protected HttpServletResponse response = ServletActionContext.getResponse();
private static final Log logger = LogFactory.getLog(AppletNewsAction.class);
@Autowired
@Qualifier("xcxBaseConfigCustomService")
private IXcxBaseConfigServiceCustom xcxBaseConfigServiceCustom;
@Autowired
@Qualifier("xcxXcxCustomService")
private IXcxXcxServiceCustom xcxXcxCustomService;
/**
* 校验Token令牌
* @return
*/
public String receiveMsg() {
String token = request.getParameter("token");
String echostr = request.getParameter("echostr");
String Applet_TOKEN = PropertiesUtils.getValue("xcx_token");
logger.info("receiveMsg token=" + token + "echostr=" + echostr + "---Applet_TOKEN=" + Applet_TOKEN);
// 时间戳
String timestamp = request.getParameter("timestamp");
String signature = request.getParameter("signature");
String nonce = request.getParameter("nonce");
logger.info("接收到参数:echostr=" + echostr + " signature=" + signature + " timestamp=" + timestamp + " nonce="
+ nonce);
if (StringUtil.isEmptyOrNullStr(timestamp) || StringUtil.isEmptyOrNullStr(nonce)) {
try {
response.getWriter().print("微信返回 signature echostr timestamp nonce 为空!");
ResponseUtils.renderJsonObject(response, ResponseResultUtil.returnFailResult(ResultBeanUtil.MSG_SUCCESS, "微信返回 signature echostr timestamp nonce 为空!"));
return null;
} catch (IOException e) {
e.printStackTrace();
}
}
String[] str = {Applet_TOKEN, timestamp, nonce};
logger.info("输出的字符串str=" + str.toString());
Arrays.sort(str); // 字典序排序
String tmpStr = this.ArrayToString(str);
tmpStr = this.SHA1Encode(tmpStr);
logger.info("加密后的数据tmpStr=" + tmpStr);
// 确认请求来至微信
if (echostr != null) {
response.setCharacterEncoding("UTF-8");
logger.info("加密后发送请求的数据echostr=" + echostr);
try {
response.getWriter().print(echostr);
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
// 数组转字符串
public String ArrayToString(String[] arr) {
StringBuffer bf = new StringBuffer();
for (int i = 0; i < arr.length; i++) {
bf.append(arr[i]);
}
return bf.toString();
}
// sha1加密
public String SHA1Encode(String sourceString) {
String resultString = null;
try {
resultString = new String(sourceString);
MessageDigest md = MessageDigest.getInstance("SHA-1");
resultString = byte2hexString(md.digest(resultString.getBytes()));
} catch (Exception ex) {
}
return resultString;
}
public final String byte2hexString(byte[] bytes) {
StringBuffer buf = new StringBuffer(bytes.length * 2);
for (int i = 0; i < bytes.length; i++) {
if (((int) bytes[i] & 0xff) < 0x10) {
buf.append("0");
}
buf.append(Long.toString((int) bytes[i] & 0xff, 16));
}
return buf.toString().toUpperCase();
}
/**
* 获取授权的Ticket
*
* @return
*/
public String receiveAuth() {
String Applet_TOKEN = PropertiesUtils.getValue("xcx_token");
String ENCODING_AESKEY = PropertiesUtils.getValue("xcx_encoding_aeskey");
String APPID = PropertiesUtils.getValue("xcx.appId");
logger.info("receiveAuth APPID=" + APPID + "------xcx_token=" + Applet_TOKEN + "-----------ENCODING_AESKEY=" + ENCODING_AESKEY);
String Appsecret = PropertiesUtils.getValue("xcx.secret");
String msgSignature = request.getParameter("msg_signature");
String timestamp = request.getParameter("timestamp");
logger.info("接收的明文秘钥EncodingAesKey=" + EncodingAesKey + "msgSignature:" + msgSignature + ",timestamp:" + timestamp + ",nonce:" + nonce);
try {
logger.info("进来啦AppletNewsAction receiveAuth");
BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
}
String encStr = sb.toString();
//解密推送信息
if (encStr != null) {
logger.info("进入解密推送判断=" + encStr);
Map<String, String> xmlMap = new HashMap<String, String>();
String resultXml = "";
try {
WXBizMsgCrypt pc = new WXBizMsgCrypt(Applet_TOKEN, ENCODING_AESKEY, APPID);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
StringReader sr = new StringReader(encStr);
InputSource is = new InputSource(sr);
Document document = db.parse(is);
Element root = document.getDocumentElement();
NodeList nodelist1 = root.getElementsByTagName("Encrypt");
String encrypt = nodelist1.item(0).getTextContent();
String format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
String fromXML = String.format(format, encrypt);
resultXml = pc.decryptMsg(msgSignature, timestamp, nonce, fromXML);
logger.info("返回的resultXml=" + resultXml);
xmlMap = XmlUtil.xml2Map(resultXml.toString());
logger.info("解析成Map=" + xmlMap);
XcxXcxCustom xcxXcxCustom = new XcxXcxCustom();
//取消授权
if (StringUtils.isNotBlank(xmlMap.get("xml.InfoType") + "") && "unauthorized".equals(xmlMap.get("xml.InfoType"))) {
String appid = xmlMap.get("xml.AuthorizerAppid");
xcxXcxCustom.setAppletId(appid);
xcxXcxCustom.setAuthorizationStates(XcxAutorzerStatus.UNAUTHORIZED.getStatus());
xcxXcxCustomService.updateXcxAutorzerStatus(xcxXcxCustom);
logger.info("wx_account Cancel authorization set status = 0 appid=" + appid);
}
//授权成功
if (StringUtils.isNotBlank(xmlMap.get("xml.InfoType") + "") && "authorized".equals(xmlMap.get("xml.InfoType"))) {
String appid = xmlMap.get("xml.AuthorizerAppid");
xcxXcxCustom.setAppletId(appid);
xcxXcxCustom.setAuthorizationStates(XcxAutorzerStatus.AUTHORIZED.getStatus());
xcxXcxCustomService.updateXcxAutorzerStatus(xcxXcxCustom);
logger.info("wx_account success authorization set status = 1 appid=" + appid);
}
//授权更新
if (StringUtils.isNotBlank(xmlMap.get("xml.InfoType") + "") && "updateauthorized".equals(xmlMap.get("xml.InfoType"))) {
String appid = xmlMap.get("xml.AuthorizerAppid");
xcxXcxCustom.setAppletId(appid);
xcxXcxCustom.setAuthorizationStates(XcxAutorzerStatus.UPDATEAUTHORIZED.getStatus());
xcxXcxCustomService.updateXcxAutorzerStatus(xcxXcxCustom);
logger.info("wx_account udpate authorization set status = 2 appid=" + appid);
}
String ticket = xmlMap.get("xml.ComponentVerifyTicket");
String appID = xmlMap.get("xml.AppId");
logger.info("ticket参数=" + ticket + "||" + "第三方平台appid=" + appID);
if (StringUtil.isNotNull(ticket)) {
//公众号的
SysRediesAppletUtil.setComponentVerifyTicket(appID, ticket);
logger.info("获取的小程序verify_Ticket" + ticket);
logger.info("写入到redies库中=" + "||" + appID + "||" + "ticket=" + ticket);
String appletId = SysRediesAppletUtil.getTicket(appID);
logger.info("存到redies中appletIdRedies=" + appletId);
}
if (resultXml != null) {
response.getWriter().println("success");
logger.info("打印成功---------------------scuccess-----------------------");
}
} catch (Exception e) {
logger.error("receiveAuth 异常了:e.getMessage()=" + e.getMessage());
e.printStackTrace();
} finally {
logger.error("receiveAuth finally");
}
logger.error("receiveAuth finally xmlMap=" + xmlMap + "||resultXml=" + resultXml);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
在此写的一个指定回调的URL这样就可以校验成功之后就会给你生成你自己指定的Token(令牌)和EncodingAESKey
(消息加密密钥)随机生成这样你离开发小程序不远了。成功了50%,那么具体还要做什么呢?请看(java实现小程序开发(三))
版权声明:未经本人允许不得转载。