java微信签名,验证微信发送的signature,还有获取access_token和ticket

controller

@RequestMapping("/weixin")
    @ResponseBody
    public String  weixin(String signature,String timestamp 
            ,String nonce,String echostr) throws NoSuchAlgorithmException {
        String token="umaiw";
         String tmpStr=  getSHA1(token, timestamp, nonce);
        
   System.out.println("+++++++++++++++++++++tmpStr   "+tmpStr);
   System.out.println("---------------------signature   "+signature);
     
     if(tmpStr.equals(signature)){
         return echostr;
     }else{
         return null;
     }

 /**
     * 用SHA1算法生成安全签名
     * @param token 票据
     * @param timestamp 时间戳
     * @param nonce 随机字符串
     * @param encrypt 密文
     * @return 安全签名
     * @throws NoSuchAlgorithmException 
     * @throws AesException 
     */
    public  String getSHA1(String token, String timestamp, String nonce) throws NoSuchAlgorithmException  {
            String[] array = new String[] { token, timestamp, nonce };
            StringBuffer sb = new StringBuffer();
            // 字符串排序
            Arrays.sort(array);
            for (int i = 0; i < 3; i++) {
                sb.append(array[i]);
            }
            String str = sb.toString();
            // SHA1签名生成
            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();
    }

Sign.java

package com.util;

import java.util.UUID;
import java.util.Map;
import java.util.HashMap;
import java.util.Formatter;
import java.util.concurrent.TimeoutException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;  

import javax.servlet.http.HttpServletRequest;

import net.rubyeye.xmemcached.exception.MemcachedException;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component("Sign")
public class Sign {
    @Autowired
private    WeiXinRequest  weiXinRequest;
    
    @Test
    public Map<String, String>  test(HttpServletRequest requesturl) throws IOException, TimeoutException, InterruptedException, MemcachedException {
      String ticket=  weiXinRequest.getWeiXinTicket();
      
        // 注意 URL 一定要动态获取,不能 hardcode
        String url =  requesturl.getRequestURL().toString();
        Map<String, String> ret = sign(ticket, url);
        for (Map.Entry entry : ret.entrySet()) {
            System.out.println(entry.getKey() + ", " + entry.getValue());
        }
        ret.put("appId",weiXinRequest.appId );
       return ret;
    };

    public static Map<String, String> sign(String jsapi_ticket, String url) {
        Map<String, String> ret = new HashMap<String, String>();
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String string1;
        String signature = "";

        //注意这里参数名必须全部小写,且必须有序
        string1 = "jsapi_ticket=" + jsapi_ticket +
                  "&noncestr=" + nonce_str +
                  "&timestamp=" + timestamp +
                  "&url=" + url;
        System.out.println(string1);

        try
        {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }

        ret.put("url", url);
        ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);

        return ret;
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash)
        {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }
}

WeiXinRequest.java

package com.util;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeoutException;

import javax.servlet.http.HttpServletRequest;
import javax.xml.crypto.Data;

import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.exception.MemcachedException;

import org.activiti.engine.impl.util.json.JSONObject;
import org.activiti.engine.impl.util.json.JSONTokener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.model.CitySession;
@Component("WeiXinRequest")
public class WeiXinRequest {
    @Autowired
    private MemcachedClient memcachedClient;

      String appId = "你扫描后登陆进去的appid 不同人不一样哦";
    private  String appSecret="同上";
    public  String getWeiXinTicket() throws IOException, TimeoutException, InterruptedException, MemcachedException {
        String access_token="";
        String ticket="";
        Object  act=memcachedClient.get("access_token");
        Object  apiticket=memcachedClient.get("ticket");
        Object expires_in ;
        if(null==act){
            
        
        URL url = new URL(
                "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
                        + appId + "&secret=" + appSecret);
        JSONObject json = getConnection(url);

            access_token = (String) json.getString("access_token");
            expires_in=  json.get("expires_in");
            if (access_token == null) {
                return null;
            }
            memcachedClient.set("access_token", 2*60*60, access_token);
        }else{
            access_token=(String) act;
        }
        
        System.out.println("access_token is =====" + access_token);
        
        
        if(null==apiticket){
        URL url1=new URL("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+access_token+"&type=jsapi");
        JSONObject json1 = getConnection(url1);
        ticket=(String) json1.get("ticket");
    
        }else{
            ticket=(String) apiticket;
        }
        
        return ticket;
        // 断开连接

    }

    public  JSONObject getConnection(URL url) throws IOException {

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestMethod("GET");
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");

        connection.connect();
        JSONObject jsono = new JSONObject(new JSONTokener(
                new InputStreamReader(connection.getInputStream())));
        connection.disconnect();
        return jsono;
    }

}

js发送请求的controller

/*
     * json数据格式测试
     */
    @RequestMapping(value = "/house/index1")
    public ModelAndView index(HttpServletRequest request,
            HttpServletResponse response, ModelMap modelMap,
            HttpSession session) throws IOException, TimeoutException, InterruptedException, MemcachedException {
        Map<String, String> map=sign.test(request);
        modelMap.addAllAttributes(map);
        return new ModelAndView("/views/index/weixintest",modelMap);
    }


java微信签名,验证微信发送的signature,还有获取access_token和ticket

上一篇:内存泄露调试心得


下一篇:3DSMAX渲染美国秋天公园场景