微信js-sdk签名算法

<pre name="code" class="java">package Jssdk;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Formatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.alibaba.fastjson.JSONObject;

public class WxSign {
     /**
      * 签名算法 
       签名生成规则如下:
       参与签名的字段包括noncestr(随机字符串), 有效的jsapi_ticket, timestamp(时间戳), url(当前网页的URL,不包含#
       及其后面部分) 。对所有待签名参数按照字段名的ASCII 码从小到大排序(字典序)后,使用URL键值对的格式(即key1
       =value1&key2=value2…)拼接成字符串string1。这里需要注意的是所有参数名均为小写字符。对string1作sha1加密,
       字段名和字段值都采用原始值,不进行URL 转义。
      *  @author 进击的书生
      * @param args
      * 2015年6月22日
     * @throws Exception 
      */
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		
         String  jsapi_ticket=getJsTicket();
         String url = "www.cttyun.cn/elms/test1.html";
         Map<String,String> ret=sign(jsapi_ticket,url);
        
         for (Map.Entry entry : ret.entrySet()) {
             System.out.println(entry.getKey() + "======== " + entry.getValue());
         }
         //System.out.println("signature:  "+ret.get("signature") +  ": timestamp " +ret.get("timestamp"));
         System.out.println(createLinkString(ret));
         
	}
    public static  String getAccessToken() throws Exception{
		String result = Tool.getaccess_token();
		Map<String, Object> map = JSONObject.parseObject(result);
        return map.get("access_token").toString();
     }
    
    public static  String getJsTicket() throws Exception{
   	 String result=Tool.getjsticket(getAccessToken());
   	 Map<String,Object>map=JSONObject.parseObject(result);
   	 return map.get("ticket").toString();
    }
	
	/**
	 * 对所有待签名参数按照字段名的ASCII 码从小到大排序(字典序)后
	 * 把数组所有元素排序,并按照“参数=参数值”的模式用“&”字符拼接成字符串
	 *  @author 进击的书生
	 * @param params
	 * @return
	 * 2015年6月22日
	 */
	private static String createLinkString(Map<String, String> params) {
        List<String> keys=new ArrayList<String>(params.keySet());
        Collections.sort(keys);
        String prestr="";
        for(int i=0;i<keys.size();i++){
        	String key=keys.get(i);
        	String value=params.get(key);
        	if(i==keys.size()-1){
        		//拼接时,不包括最后一个&字符
        		prestr = prestr + key + "=" + value;
            } else {
                prestr = prestr + key + "=" + value + "&";
            }
        }
		return prestr;
	}



	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 + "×tamp=" + 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) {
			// TODO Auto-generated catch block
			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;
	}
	
    /**
     *  生成签名的时间戳
     *  @author 进击的书生
     * @return
     * 2015年6月22日
     */
	private static String create_timestamp() {
		return Long.toString(System.currentTimeMillis()/1000);
	}

	/**
	 *   生成签名的随机串
	 *  @author 进击的书生
	 * @return
	 * 2015年6月22日
	 */
	private static String create_nonce_str() {
		return UUID.randomUUID().toString();
	}
	

}


 
package Jssdk;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class Tool {
	
	public static CloseableHttpClient client=HttpClients.createDefault();
	static String access_token=null;
	public static String PostJsonInfo(String sendurl, String data) {
					System.out.println(data+"data"+sendurl+"sendurl");
					HttpPost post = new HttpPost(sendurl);
					StringEntity myEntity = new StringEntity(data,
					ContentType.APPLICATION_JSON);// 构造请求数据
					post.setEntity(myEntity);// 设置请求体
					String responseContent = null; // 响应内容
					CloseableHttpResponse response = null;
						try {
							response = client.execute(post);
							int s = response.getStatusLine().getStatusCode();
							System.out.println(response+"response-----");
							if (response.getStatusLine().getStatusCode() == 200) {
								HttpEntity entity = response.getEntity();
								System.out.println(entity+"entity");
								responseContent = EntityUtils.toString(entity, "UTF-8"); }
							} catch (ClientProtocolException e) {
								e.printStackTrace();
							} catch (IOException e) {
								e.printStackTrace();
							} finally {
									try {
										if (response != null)
											response.close();

									} catch (IOException e) {
										e.printStackTrace();
									} finally {
										try {
											if (client != null)
												client.close();
										} catch (IOException e) {
											e.printStackTrace();
										}
									}
							}
	return responseContent;
	}
			public static  String getinfo (String url){
				HttpPost get = new HttpPost(url);
						String responseContent = null; // 响应内容
						CloseableHttpResponse response = null;
							try {
								response = client.execute(get);
								int s = response.getStatusLine().getStatusCode();
								if (response.getStatusLine().getStatusCode() == 200) {
									HttpEntity entity = response.getEntity();
									responseContent = EntityUtils.toString(entity, "UTF-8"); }
								} catch (ClientProtocolException e) {
									e.printStackTrace();
								} catch (IOException e) {
									e.printStackTrace();
								} 
				return responseContent;}
			
			public static  String getaccess_token (){
				HttpPost get = new HttpPost("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx0f2e438693833b13&secret=d85510c742365dd09e1a7541d69c7585");
						String responseContent = null; // 响应内容
						CloseableHttpResponse response = null;
							try {
								response = client.execute(get);
								int s = response.getStatusLine().getStatusCode();
								if (response.getStatusLine().getStatusCode() == 200) {
									HttpEntity entity = response.getEntity();
									responseContent = EntityUtils.toString(entity, "UTF-8"); }
								} catch (ClientProtocolException e) {
									e.printStackTrace();
								} catch (IOException e) {
									e.printStackTrace();
								} 
				return responseContent;
			}
			
			public static  String getjsticket(String access_token){
				StringBuffer sb=new StringBuffer();
				sb.append("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=");
				sb.append(access_token);
				sb.append("&type=jsapi");
				HttpPost get = new HttpPost(sb.toString());
						String responseContent = null; // 响应内容
						CloseableHttpResponse response = null;
							try {
								response = client.execute(get);
								int s = response.getStatusLine().getStatusCode();
								if (response.getStatusLine().getStatusCode() == 200) {
									HttpEntity entity = response.getEntity();
									responseContent = EntityUtils.toString(entity, "UTF-8"); }
								} catch (ClientProtocolException e) {
									e.printStackTrace();
								} catch (IOException e) {
									e.printStackTrace();
								} 
				return responseContent;
			}
			
			
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值