微信生成簽名

/**
 * 微信授權(quán)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創(chuàng)建簽名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);
    }
    
   //創(chuàng)建簽名SHA1
    public static String createSHA1Sign(SortedMap<String, String> 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;
    }

    /**
     * 根據(jù)code獲取accesstoken
     * @param code
     * @return
     */
    private boolean getAccessToken(String code) {
        openId = null;
        accessToken = null;
        unionId = null; // 不管如何先清空數(shù)據(jù)
        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;
    }


    /**
     * 跳轉(zhuǎn)微信授權(quán)
     */
    public void reAuth() {
        // 清空session椭懊,重新獲取授權(quán)
        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";
        
        //微信模板消息發(fā)送
        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;
        
        //微信模板消息發(fā)送
        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());
                // 調(diào)用接口創(chuàng)建菜單
                JsonObject jsonObject = CommonUtils.httpRequest(url, "POST", jsonmsg);
                // 請(qǐng)求成功
                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);
            // 請(qǐng)求成功
            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;
        }
        
}
/**
     * 發(fā)送https請(qǐng)求
     * 
     * @param requestUrl 請(qǐng)求地址
     * @param requestMethod 請(qǐng)求方式(GET谣光、POST)
     * @param outputStr 提交的數(shù)據(jù)
     * @return JSONObject(通過JSONObject.get(key)的方式獲取json對(duì)象的屬性值)
     */
    public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
        JSONObject jsonObject = null;
        try {
            // 創(chuàng)建SSLContext對(duì)象证九,并使用我們指定的信任管理器初始化
            TrustManager[] tm = { new MyX509TrustManager() };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 從上述SSLContext對(duì)象中得到SSLSocketFactory對(duì)象
            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);
            // 設(shè)置請(qǐng)求方式(GET/POST)
            conn.setRequestMethod(requestMethod);

            // 當(dāng)outputStr不為null時(shí)向輸出流寫數(shù)據(jù)
            if (null != outputStr) {
                OutputStream outputStream = conn.getOutputStream();
                // 注意編碼格式
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }

            // 從輸入流讀取返回內(nèi)容
            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;
    }
    /**
     * 獲取當(dāng)前時(shí)間 yyyyMMddHHmmss
     * @return String
     */ 
    public static String getCurrTime() {
        Date now = new Date();
        SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String s = outFormat.format(now);
        return s;
    }

        /**
     * 取出一個(gè)指定長(zhǎng)度大小的隨機(jī)正整數(shù).
     * 
     * @param length
     *            int 設(shè)定所取出隨機(jī)數(shù)的長(zhǎng)度。length小于11
     * @return int 返回生成的隨機(jī)數(shù)啡莉。
     */
    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));
    }

    /**
     * 發(fā)起https請(qǐng)求
     * 
     * @param requestUrl
     *            請(qǐng)求地址
     * @param requestMethod
     *            請(qǐng)求方式(GET局骤、POST)
     * @param outputStr
     *            提交的數(shù)據(jù)
     * @return JSONObject(通過JSONObject.get(key)的方式獲取json對(duì)象的屬性值)
     */
    public static JsonObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
        JsonObject jsonObject = null;
        StringBuffer buffer = new StringBuffer();
        try {
            // 創(chuàng)建SSLContext對(duì)象
            TrustManager[] tm = { (TrustManager) new MyX509TrustManager() };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 從上述SSLContext對(duì)象中得到SSLSocketFactory對(duì)象
            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);
            // 設(shè)置請(qǐng)求方式(GET/POST)
            httpUrlConn.setRequestMethod(requestMethod);
            if ("GET".equalsIgnoreCase(requestMethod))
                httpUrlConn.connect();
            // 當(dāng)有數(shù)據(jù)需要提交時(shí)
            if (null != outputStr) {
                OutputStream outputStream = httpUrlConn.getOutputStream();
                // 編碼格式
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }
            // 將返回的輸入流轉(zhuǎn)換成字符串
            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;
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市搓彻,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖好唯,帶你破解...
    沈念sama閱讀 210,978評(píng)論 6 490
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件竭沫,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡骑篙,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 89,954評(píng)論 2 384
  • 文/潘曉璐 我一進(jìn)店門森书,熙熙樓的掌柜王于貴愁眉苦臉地迎上來靶端,“玉大人,你說我怎么就攤上這事凛膏⊙蠲” “怎么了?”我有些...
    開封第一講書人閱讀 156,623評(píng)論 0 345
  • 文/不壞的土叔 我叫張陵猖毫,是天一觀的道長(zhǎng)台谍。 經(jīng)常有香客問我,道長(zhǎng)吁断,這世上最難降的妖魔是什么趁蕊? 我笑而不...
    開封第一講書人閱讀 56,324評(píng)論 1 282
  • 正文 為了忘掉前任,我火速辦了婚禮仔役,結(jié)果婚禮上掷伙,老公的妹妹穿的比我還像新娘。我一直安慰自己又兵,他們只是感情好任柜,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,390評(píng)論 5 384
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著沛厨,像睡著了一般宙地。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上逆皮,一...
    開封第一講書人閱讀 49,741評(píng)論 1 289
  • 那天宅粥,我揣著相機(jī)與錄音,去河邊找鬼页屠。 笑死粹胯,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的辰企。 我是一名探鬼主播风纠,決...
    沈念sama閱讀 38,892評(píng)論 3 405
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼牢贸!你這毒婦竟也來了竹观?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,655評(píng)論 0 266
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎臭增,沒想到半個(gè)月后懂酱,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,104評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡誊抛,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,451評(píng)論 2 325
  • 正文 我和宋清朗相戀三年列牺,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片拗窃。...
    茶點(diǎn)故事閱讀 38,569評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡瞎领,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出随夸,到底是詐尸還是另有隱情九默,我是刑警寧澤,帶...
    沈念sama閱讀 34,254評(píng)論 4 328
  • 正文 年R本政府宣布宾毒,位于F島的核電站驼修,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏诈铛。R本人自食惡果不足惜乙各,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,834評(píng)論 3 312
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望癌瘾。 院中可真熱鬧觅丰,春花似錦、人聲如沸妨退。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,725評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽咬荷。三九已至冠句,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間幸乒,已是汗流浹背懦底。 一陣腳步聲響...
    開封第一講書人閱讀 31,950評(píng)論 1 264
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留罕扎,地道東北人聚唐。 一個(gè)月前我還...
    沈念sama閱讀 46,260評(píng)論 2 360
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像腔召,于是被迫代替她去往敵國(guó)和親杆查。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,446評(píng)論 2 348

推薦閱讀更多精彩內(nèi)容