微信生成签名

/**
 * 微信授权access_token
 * @author wangcl
 *
 */
public class AccessToken {
    private String access_token;
    private int expires_in;
    private long expires_time;
    private String jsapi_ticket;
    
    public String getAccess_token() {
        return access_token;
    }
    
    public void setAccess_token(String access_token) {
        this.access_token = access_token;
    }
    
    public int getExpires_in() {
        return expires_in;
    }
    
    public void setExpires_in(int expires_in) {
        this.expires_in = expires_in;
    }
    
    public long getExpires_time() {
        return expires_time;
    }

    public void setExpires_time(long expires_time) {
        this.expires_time = expires_time;
    }

    public AccessToken( ) {
    }
    
    public AccessToken(String access_token, int expires_in,String jsapi_ticket) {
        this.access_token = access_token;
        this.expires_in = expires_in;
        this.expires_time = System.currentTimeMillis() / 1000;
        this.jsapi_ticket = jsapi_ticket;
    }
    
    public boolean isExpires() {
        if (access_token != null && expires_in > 0) {
            long currentTime = System.currentTimeMillis() / 1000;
            
            if (expires_in > (currentTime - expires_time + 30)) {
                return true;
            }
        }
        
        return false;
    }

    public String getJsapi_ticket() {
        return jsapi_ticket;
    }

    public void setJsapi_ticket(String jsapi_ticket) {
        this.jsapi_ticket = jsapi_ticket;
    }
    
}
//加密
public class MD5Util {

    private static String byteArrayToHexString(byte b[]) {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; i++)
            resultSb.append(byteToHexString(b[i]));

        return resultSb.toString();
    }

    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0)
            n += 256;
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }

    public static String MD5Encode(String origin, String charsetname) {
        String resultString = null;
        try {
            resultString = new String(origin);
            MessageDigest md = MessageDigest.getInstance("MD5");
            if (charsetname == null || "".equals(charsetname))
                resultString = byteArrayToHexString(md.digest(resultString
                        .getBytes()));
            else
                resultString = byteArrayToHexString(md.digest(resultString
                        .getBytes(charsetname)));
        } catch (Exception exception) {
        }
        return resultString;
    }

    private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

}
/*
'============================================================================
'api说明:
'createSHA1Sign创建签名SHA1
'getSha1()Sha1签名
'============================================================================
'*/
public class Sha1Util {

    public static String getNonceStr() {
        Random random = new Random();
        return MD5Util.MD5Encode(String.valueOf(random.nextInt(10000)), "UTF-8");
    }
    public static String getTimeStamp() {
        return String.valueOf(System.currentTimeMillis() / 1000);
    }
    
   //创建签名SHA1
    public static String createSHA1Sign(SortedMap signParams) throws Exception {
        StringBuffer sb = new StringBuffer();
        Set es = signParams.entrySet();
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            String v = (String) entry.getValue();
            sb.append(k + "=" + v + "&");
            //要采用URLENCODER的原始值!
        }
        String params = sb.substring(0, sb.lastIndexOf("&"));
//      System.out.println("sha1之前:" + params);
//      System.out.println("SHA1签名为:"+getSha1(params));
        return getSha1(params);
    }
    //Sha1签名
    public static String getSha1(String str) {
        if (str == null || str.length() == 0) {
            return null;
        }
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f' };

        try {
            MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
            mdTemp.update(str.getBytes("UTF-8"));

            byte[] md = mdTemp.digest();
            int j = md.length;
            char buf[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
                buf[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(buf);
        } catch (Exception e) {
            return null;
        }
    }
}
public class WxAuth {

    HttpServletRequest request;
    HttpServletResponse response;
    
    
    String openId, accessToken,nickname,headimgurl;
    String unionId, code = null;

    public WxAuth(HttpServletRequest request, HttpServletResponse response) {
        this.request = request;
        this.response = response;
    }

    public String wxAuth() {
        code = request.getParameter("code");
        String openId = request.getParameter("openid");
//      System.out.println("In wxAuth.............:code="+code);
        if (!CommonUtils.isEmptyString(code)) {
            if (getAccessToken(code)) {
//              System.out.println("In wxAuth.............:getAccesstoke:code="+code);
                if (!CommonUtils.isEmptyString(openId)) {
                    return openId;
                }
            }
        }
        reAuth();
        return null;
    }

    /**
     * 根据code获取accesstoken
     * @param code
     * @return
     */
    private boolean getAccessToken(String code) {
        openId = null;
        accessToken = null;
        unionId = null; // 不管如何先清空数据
        String accessUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + Consts.APPID + "&secret=" + Consts.APPSECRET + "&code=" + code + "&grant_type=authorization_code";
        JSONObject jsonObject = CommonUtils.httpsRequest(accessUrl, "GET", null);
        if (null != jsonObject) {
            try {
                openId = jsonObject.getString("openid");
                accessToken = jsonObject.getString("access_token");
                unionId = jsonObject.getString("unionid");
            } catch (Exception e) {
            }
        }
        if (!CommonUtils.isEmptyString(openId)) {
            request.getSession().setAttribute(Consts.SESSION_OPENID, openId);
            String UnionURL = "https://api.weixin.qq.com/sns/userinfo?lang=zh_CN&openid=" + openId + "&access_token=" + accessToken;
            JSONObject jsonObject2 = CommonUtils.httpsRequest(UnionURL, "GET", null);
//          System.out.println("In WxAuth.........:getUserInfo");
            if (null != jsonObject2) {
                try {
                    nickname = jsonObject2.getString("nickname");
                    headimgurl = jsonObject2.getString("headimgurl");
                    System.out.println("In WxAuth.........:getUserInfo: nickname = "+nickname+".....headimgurl = "+headimgurl);
                } catch (Exception e) {
                }
            }
            return true;
        }
        return false;
    }


    /**
     * 跳转微信授权
     */
    public void reAuth() {
        // 清空session,重新获取授权
        request.getSession().setAttribute(Consts.SESSION_OPENID, "");
        request.getSession().setAttribute("accesstoken", "");
        request.getSession().setAttribute("wxauth", 1);
        try {
            response.sendRedirect("./wxsq?reurl=" + CommonUtils.getFullURLWithParam(request));// 返回到配置文件中定义的路径
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
public class WeiXinEntity {

        // 获取access_token的接口地址(GET) 限200(次/天)
        public final static String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
        
        //微信模板消息发送
        public final static String template_url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
        // 获取jsapi_ticket_url的接口地址(GET) 限200(次/天)
        public final static String jsapi_ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";
        
        
        
        public static AccessToken accessToken;
        
        //微信模板消息发送
        public int sendTemplate(String jsonmsg){
            int result = -1;
            AccessToken token = getAccessToken();
            if (accessToken != null && accessToken.isExpires()) {
                // 拼装url
                String url = template_url.replace("ACCESS_TOKEN", token.getAccess_token());
                // 调用接口创建菜单
                JsonObject jsonObject = CommonUtils.httpRequest(url, "POST", jsonmsg);
                // 请求成功
                if (null != jsonObject) {
                    result = jsonObject.get("errcode").getAsInt();
                }
            }
            return result;
        }
        
        /**
         * 取得微信access_token
         * 
         * @return
         */
        public AccessToken getAccessToken() {
            if (accessToken != null && accessToken.isExpires()) {
                return this.accessToken;
            }
            String requestUrl = access_token_url.replace("APPID", Consts.APPID).replace("APPSECRET", Consts.APPSECRET);
            JsonObject jsonObject = CommonUtils.httpRequest(requestUrl, "GET", null);
            // 请求成功
            if (null != jsonObject) {
                try {
                    String access_token = jsonObject.get("access_token").getAsString();
                    String jsapi_ticketurl = jsapi_ticket_url.replace("ACCESS_TOKEN", access_token);
                    JsonObject tickObject = CommonUtils.httpRequest(jsapi_ticketurl, "GET", null);
                    String jsapi_ticke = tickObject.get("ticket").getAsString();
                    accessToken = new AccessToken(jsonObject.get("access_token").getAsString(), jsonObject.get("expires_in").getAsInt(),jsapi_ticke);
                } catch (Exception e) {
                    accessToken = null;
                }
            }
            return this.accessToken;
        }

        public String getJsTicket() {
            AccessToken token = getAccessToken();
            if (accessToken != null && accessToken.isExpires()) {
                return token.getJsapi_ticket();
            }
            return null;
        }
        
}
/**
     * 发送https请求
     * 
     * @param requestUrl 请求地址
     * @param requestMethod 请求方式(GET、POST)
     * @param outputStr 提交的数据
     * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
     */
    public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
        JSONObject jsonObject = null;
        try {
            // 创建SSLContext对象,并使用我们指定的信任管理器初始化
            TrustManager[] tm = { new MyX509TrustManager() };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(requestUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setSSLSocketFactory(ssf);
            
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            // 设置请求方式(GET/POST)
            conn.setRequestMethod(requestMethod);

            // 当outputStr不为null时向输出流写数据
            if (null != outputStr) {
                OutputStream outputStream = conn.getOutputStream();
                // 注意编码格式
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }

            // 从输入流读取返回内容
            InputStream inputStream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }

            // 释放资源
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            conn.disconnect();
            jsonObject = JSONObject.fromObject(buffer.toString());
        } catch (ConnectException ce) {
        } catch (Exception e) {
        }
        return jsonObject;
    }
    /**
     * 获取当前时间 yyyyMMddHHmmss
     * @return String
     */ 
    public static String getCurrTime() {
        Date now = new Date();
        SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String s = outFormat.format(now);
        return s;
    }

        /**
     * 取出一个指定长度大小的随机正整数.
     * 
     * @param length
     *            int 设定所取出随机数的长度。length小于11
     * @return int 返回生成的随机数。
     */
    public static int buildRandom(int length) {
        int num = 1;
        double random = Math.random();
        if (random < 0.1) {
            random = random + 0.1;
        }
        for (int i = 0; i < length; i++) {
            num = num * 10;
        }
        return (int) ((random * num));
    }

    /**
     * 发起https请求
     * 
     * @param requestUrl
     *            请求地址
     * @param requestMethod
     *            请求方式(GET、POST)
     * @param outputStr
     *            提交的数据
     * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
     */
    public static JsonObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
        JsonObject jsonObject = null;
        StringBuffer buffer = new StringBuffer();
        try {
            // 创建SSLContext对象
            TrustManager[] tm = { (TrustManager) new MyX509TrustManager() };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            URL url = new URL(requestUrl);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
            httpUrlConn.setSSLSocketFactory(ssf);
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置请求方式(GET/POST)
            httpUrlConn.setRequestMethod(requestMethod);
            if ("GET".equalsIgnoreCase(requestMethod))
                httpUrlConn.connect();
            // 当有数据需要提交时
            if (null != outputStr) {
                OutputStream outputStream = httpUrlConn.getOutputStream();
                // 编码格式
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }
            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
            JsonParser jp = new JsonParser();
            jsonObject = (JsonObject) jp.parse(buffer.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

你可能感兴趣的:(微信生成签名)