微信大众号获取openid(2)
微信公众号获取openid(2)
- 上一篇主要讲述了网页开发的一些流程和openid的获取,这篇讲述另一种微信用户openid的获取方式,在服务器响应微信发送的token验证接口里,微信每一次调用该接口(用户关注、取关等操作)都会发送xml信息,其中就包括openid(参数为FromUserName即openid),我们可以截取xml信息获取需要的用户openid。
- 响应微信token验证接口示例代码:
- /**
* 正确响应微信发送的token验证
* @param request
* @param response
* @return
*/
@RequestMapping(value="/tokenVerify")
@ResponseBody
public String tokenVerify(HttpServletRequest request,HttpServletResponse response){
try {
// 微信加密签名
String signature = request.getParameter("signature");
System.out.println("微信加密签名signature:-----------------------"+signature);
// 时间戳
String timestamp = request.getParameter("timestamp");
System.out.println("时间戳timestamp:-----------------------"+timestamp);
// 随机数
String nonce = request.getParameter("nonce");
System.out.println("随机数nonce:-----------------------"+nonce);
// 随机字符串
String echostr = request.getParameter("echostr");
System.out.println("随机字符串echostr:-----------------------"+echostr);
// 通过检验signature对请求进行校验,若校验成功则原样返回echostr,表示接入成功,否则接入失败
if (SignUtil.checkSignature(WEI_XIN_TOKEN, signature, timestamp, nonce)) {
//获取微信发送的xml数据,得到openid
InputStreamReader isr = new InputStreamReader(request.getInputStream(), "utf-8");
BufferedReader br = new BufferedReader(isr);
String s="";
StringBuffer sb = new StringBuffer();
while((s=br.readLine())!=null){
sb.append(s);
}
String xml = sb.toString();
ReceiveXmlEntity e = xmlToEntity(xml);//将xml数据转换为entity
System.out.println(e.toString());
//FromUserName即是要获取的openid,放入session
HttpSession session = request.getSession();
session.setAttribute("openId", e.getFromUserName());
return echostr;
}
} catch (Exception e) {
System.out.println("/weixin/login异常");
e.printStackTrace();
}
return "";
} - 微信请求校验工具类示例代码:
/* * 微信请求校验工具类
*/
public class SignUtil {
/**
* 验证签名
* @param signature
* @param timestamp
* @param nonce
* @return
*/
public static boolean checkSignature(String token, 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;
try {
md = MessageDigest.getInstance("SHA-1");
// 将三个参数字符串拼接成一个字符串进行sha1加密
byte[] digest = md.digest(content.toString().getBytes());
tmpStr = byteToStr(digest);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
content = null;
// 将sha1加密后的字符串可与signature对比,标识该请求来源于微信
return tmpStr != null ? tmpStr.equals(signature.toUpperCase()) : false;
}
/**
* 将字节数组转换为十六进制字符串
* @param byteArray
* @return
*/
private static String byteToStr(byte[] byteArray) {
String strDigest = "";
for (int i = 0; i < byteArray.length; i++) {
strDigest += byteToHexStr(byteArray[i]);
}
return strDigest;
}
/**
* 将字节转换为十六进制字符串
* @param mByte
* @return
*/
private static String byteToHexStr(byte mByte) {
char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
char[] tempArr = new char[2];
tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
tempArr[1] = Digit[mByte & 0X0F];
String s = new String(tempArr);
return s;
}
} - xmlToEntity方法示例代码:
* xml转换为entity
* @param strXml
* @return
*/
public ReceiveXmlEntity xmlToEntity(String strXml){
ReceiveXmlEntity msg=null;
try {
if(strXml.length()<=0||strXml==null){
return null;
}
Document document = DocumentHelper.parseText(strXml);
Element root = document.getRootElement();
Iterator<?> iter=root.elementIterator();
msg=new ReceiveXmlEntity();
Class c = Class.forName("modules.weixin.common.ReceiveXmlEntity");
msg = (ReceiveXmlEntity)c.newInstance();//创建这个实体的对象
while(iter.hasNext()){
Element ele = (Element)iter.next();
//获取set方法中的参数字段(实体类的属性)
Field field = c.getDeclaredField(ele.getName());
//获取set方法,field.getType())获取它的参数数据类型
Method method = c.getDeclaredMethod("set"+ele.getName(), field.getType());
//调用set方法
method.invoke(msg, ele.getText());
}
} catch (Exception e) {
System.out.println("xml 格式异常: "+ strXml);
e.printStackTrace();
}
return msg;
} - 接收微信xml信息转换实体,ReceiveXmlEntity示例代码:
*接收微信xml信息转换实体
*/
public class ReceiveXmlEntity {
private String ToUserName="";
private String FromUserName="";
private String CreateTime="";
private String MsgType="";
private String MsgId="";
private String Event="";
private String EventKey="";
private String Ticket="";
private String Latitude="";
private String Longitude="";
private String Precision="";
private String PicUrl="";
private String MediaId="";
private String Title="";
private String Description="";
private String Url="";
private String Location_X="";
private String Location_Y="";
private String Scale="";
private String Label="";
private String Content="";
private String Format="";
private String Recognition="";
private String MenuId="";
public String getToUserName() {
return ToUserName;
}
public void setToUserName(String toUserName) {
ToUserName = toUserName;
}
public String getFromUserName() {
return FromUserName;
}
public void setFromUserName(String fromUserName) {
FromUserName = fromUserName;
}
public String getCreateTime() {
return CreateTime;
}
public void setCreateTime(String createTime) {
CreateTime = createTime;
}
public String getMsgType() {
return MsgType;
}
public void setMsgType(String msgType) {
MsgType = msgType;
}
public String getMsgId() {
return MsgId;
}
public void setMsgId(String msgId) {
MsgId = msgId;
}
public String getEvent() {
return Event;
}
public void setEvent(String event) {
Event = event;
}
public String getEventKey() {
return EventKey;
}
public void setEventKey(String eventKey) {
EventKey = eventKey;
}
public String getTicket() {
return Ticket;
}
public void setTicket(String ticket) {
Ticket = ticket;
}
public String getLatitude() {
return Latitude;
}
public void setLatitude(String latitude) {
Latitude = latitude;
}
public String getLongitude() {
return Longitude;
}
public void setLongitude(String longitude) {
Longitude = longitude;
}
public String getPrecision() {
return Precision;
}
public void setPrecision(String precision) {
Precision = precision;
}
public String getPicUrl() {
return PicUrl;
}
public void setPicUrl(String picUrl) {
PicUrl = picUrl;
}
public String getMediaId() {
return MediaId;
}
public void setMediaId(String mediaId) {
MediaId = mediaId;
}
public String getTitle() {
return Title;
}
public void setTitle(String title) {
Title = title;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
public String getUrl() {
return Url;
}
public void setUrl(String url) {
Url = url;
}
public String getLocation_X() {
return Location_X;
}
public void setLocation_X(String location_X) {
Location_X = location_X;
}
public String getLocation_Y() {
return Location_Y;
}
public void setLocation_Y(String location_Y) {
Location_Y = location_Y;
}
public String getScale() {
return Scale;
}
public void setScale(String scale) {
Scale = scale;
}
public String getLabel() {
return Label;
}
public void setLabel(String label) {
Label = label;
}
public String getContent() {
return Content;
}
public void setContent(String content) {
Content = content;
}
public String getFormat() {
return Format;
}
public void setFormat(String format) {
Format = format;
}
public String getRecognition() {
return Recognition;
}
public void setRecognition(String recognition) {
Recognition = recognition;
}
public String getMenuId() {
return MenuId;
}
public void setMenuId(String menuId) {
MenuId = menuId;
}
@Override
public String toString() {
return "ReceiveXmlEntity [ToUserName=" + ToUserName + ", FromUserName=" + FromUserName + ", CreateTime="
+ CreateTime + ", MsgType=" + MsgType + ", MsgId=" + MsgId + ", Event=" + Event + ", EventKey="
+ EventKey + ", Ticket=" + Ticket + ", Latitude=" + Latitude + ", Longitude=" + Longitude
+ ", Precision=" + Precision + ", PicUrl=" + PicUrl + ", MediaId=" + MediaId + ", Title=" + Title
+ ", Description=" + Description + ", Url=" + Url + ", Location_X=" + Location_X + ", Location_Y="
+ Location_Y + ", Scale=" + Scale + ", Label=" + Label + ", Content=" + Content + ", Format=" + Format
+ ", Recognition=" + Recognition + ", getToUserName()=" + getToUserName() + ", getFromUserName()="
+ getFromUserName() + ", getCreateTime()=" + getCreateTime() + ", getMsgType()=" + getMsgType()
+ ", getMsgId()=" + getMsgId() + ", getEvent()=" + getEvent() + ", getEventKey()=" + getEventKey()
+ ", getTicket()=" + getTicket() + ", getLatitude()=" + getLatitude() + ", getLongitude()="
+ getLongitude() + ", getPrecision()=" + getPrecision() + ", getPicUrl()=" + getPicUrl()
+ ", getMediaId()=" + getMediaId() + ", getTitle()=" + getTitle() + ", getDescription()="
+ getDescription() + ", getUrl()=" + getUrl() + ", getLocation_X()=" + getLocation_X()
+ ", getLocation_Y()=" + getLocation_Y() + ", getScale()=" + getScale() + ", getLabel()=" + getLabel()
+ ", getContent()=" + getContent() + ", getFormat()=" + getFormat() + ", getRecognition()="
+ getRecognition() + ", getClass()=" + getClass() + ", hashCode()=" + hashCode() + ", toString()="
+ super.toString() + "]";
}
}