WeChatUtils.java 2.44 KB
package com.phxl.modules.wechat.utils;

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

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import com.alibaba.fastjson.JSONObject;
import com.phxl.common.util.Global;
import com.phxl.common.util.HTTPClient;
import com.phxl.common.utils.CacheUtils;
import com.phxl.modules.wechat.constants.WeChatConstants;

public class WeChatUtils implements ApplicationListener<ContextRefreshedEvent> {
	
	
	/**
	 * 校验微信认证
	 * @param timestamp
	 * @param nonce
	 * @return
	 * @throws NoSuchAlgorithmException
	 */
	public static final String checkWx(String timestamp,String nonce) throws NoSuchAlgorithmException {
		String token = Global.getConfig("token");
		String [] strs=new String[] {token,timestamp,nonce};
		Arrays.sort(strs);
		StringBuilder sb=new StringBuilder();
		for (String string : strs) {
			sb.append(string);
		}
		String str=sb.toString();
		MessageDigest md=MessageDigest.getInstance("SHA-1");
		md.update(str.getBytes());
		byte[] digest = md.digest();

        StringBuffer hexstr = new StringBuffer();
        String shaHex = "";
        for (int i = 0; i < digest.length; i++) {
            shaHex = Integer.toHexString(digest[i] & 0xFF);
            if (shaHex.length() < 2) {
                hexstr.append(0);
            }
            hexstr.append(shaHex);
        }
        return hexstr.toString();
	}
	
	//将accessToken缓存到cache中
	public static void getAccessToken() {
		String appid=Global.getConfig("appid");
		String appsecrent=Global.getConfig("appsecrent");
		String token_url=WeChatConstants.Access_Token_url.replace("APPID", appid).replace("APPSECRET", appsecrent);
		String sendHttpGet = HTTPClient.sendHttpGet(token_url);
		JSONObject jsonObject=JSONObject.parseObject(sendHttpGet);
		String access_token = jsonObject.getString(WeChatConstants.Access_Token);
		CacheUtils.put(WeChatConstants.Access_Token, access_token);
	}

	
	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		// TODO Auto-generated method stub
		if(event.getApplicationContext().getParent()!=null) {
			getAccessToken();
		}
	}

	
	public static String encode(String s) {  
        if (s == null) {  
            return null;  
        }
        return DigestUtils.md5Hex(s);
    }


	public static void ReGetOpenId()
	{


	}
}