WXUtils.java 2.2 KB
package com.framework.util;

import java.security.MessageDigest;
import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.binary.Hex;

import com.alibaba.fastjson.JSONObject;
import com.framework.vo.TokenInfo;

/**
 * 微信 工具类
 * 
 * @author dingoolu
 *
 */
public class WXUtils {

	/**
	 * 检查数据是否来自微信验证
	 * 
	 * @param request
	 * @return
	 */
	public static Boolean checkIsWx(HttpServletRequest request, String token) {
		try {
			String signature = request.getParameter("signature"); // 微信加密签名(token、timestamp、nonce。)
			String timestamp = request.getParameter("timestamp"); // 时间戳
			String nonce = request.getParameter("nonce"); // 随机数
			String echostr = request.getParameter("echostr"); // 随机字符串
			String[] params = new String[] {token, timestamp, nonce };
			Arrays.sort(params);
			// 将三个参数字符串拼接成一个字符串进行sha1加密
			String clearText = params[0] + params[1] + params[2];
			String algorithm = "SHA-1";
			String sign = new String(Hex.encodeHex(MessageDigest.getInstance(algorithm).digest(clearText.getBytes()), true));
			if (sign.equals(signature)) {
				return true;
			}
			return false;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * @param code
	 * @param appId
	 * @param secret
	 * @return
	 */
	public static TokenInfo getTokenInfo(String code, String appId, String secret) {
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appId + "&secret=" + secret + "&code=" + code
				+ "&grant_type=authorization_code";
		try {
			String result = HtmlUtils.getWebContent(url);
			System.out.println(result);
			JSONObject json = JSONObject.parseObject(result);
			TokenInfo info = new TokenInfo();
			info.setAccessToken(json.getString("access_token"));
			info.setOpenId(json.getString("openid"));
			info.setRefreshToken(json.getString("refresh_token"));
			System.out.println("openId:" + info.getOpenId());
			return info;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
}