微信JS-SDK获取signature签名以及config配置

原文看:[url]http://1017401036.iteye.com/blog/2263358[/url]
微信js sdk invalid signature签名错误 问题解决。 [url]http://my.oschina.net/u/2308739/blog/371414[/url]
[color=red]微信JS-SDK说明文档 [/color][url]https://mp.weixin.qq.com/wiki/7/1c97470084b73f8e224fe6d9bab1625b.html[/url]
在线验证:[url]http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=jsapisign[/url]


package com.pandy.wx;


import net.sf.json.JSONObject;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

/**
* 微信JS-SDK获取signature签名以及config配置
* Created by pandy on 16-2-15.
*/
public class WeiXin {

/**
* 使用APPID和APPSecret获取access_token;
* @return
*/
public static String getAccessToken(String appId, String secret) {
String access_token = "";
String grant_type = "client_credential";//获取access_token填写client_credential
//String AppId = "wxe4721561eaa16da0";//第三方用户唯一凭证
//String secret = "6ea300c1f2586dafc5a894c361446e81";//第三方用户唯一凭证密钥,即appsecret
//这个url链接地址和参数皆不能变
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=" + grant_type + "&appid=" + appId + "&secret=" + secret;
System.out.println("AccessToken URL="+url);
try {
URL urlGet = new URL(url);
HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
http.setRequestMethod("GET"); // 必须是get方式请求
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
http.connect();
InputStream is = http.getInputStream();
int size = is.available();
byte[] jsonBytes = new byte[size];
is.read(jsonBytes);
String message = new String(jsonBytes, "UTF-8");
JSONObject demoJson = JSONObject.fromObject(message);
System.out.println("JSON字符串[getAccessToken]:" + demoJson);
access_token = demoJson.getString("access_token");
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return access_token;
}

/**
* 使用access_token获取jsapi_ticket ;
* jsapi_ticket
生成签名之前必须先了解一下jsapi_ticket,jsapi_ticket是公众号用于调用微信JS接口的临时票据。
正常情况下,jsapi_ticket的有效期为7200秒,通过access_token来获取。
由于获取jsapi_ticket的api调用次数非常有限,频繁刷新jsapi_ticket会导致api调用受限,影响自身业务,
开发者必须在自己的服务全局缓存jsapi_ticket 。
1、参考以下文档获取access_token(有效期7200秒,开发者必须在自己的服务全局缓存access_token):../15/54ce45d8d30b6bf6758f68d2e95bc627.html
2、用第一步拿到的access_token 采用http GET方式请求获得jsapi_ticket(有效期7200秒,开发者必须在自己的服务全局缓存jsapi_ticket):https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi
* @param access_token
* @return
*/
public static String getTicket(String access_token) {
String ticket = null;
String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + access_token + "&type=jsapi";//这个url链接和参数不能变
System.out.println("Ticket URL="+url);
try {
URL urlGet = new URL(url);
HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
http.setRequestMethod("GET"); // 必须是get方式请求
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
http.connect();
InputStream is = http.getInputStream();
int size = is.available();
byte[] jsonBytes = new byte[size];
is.read(jsonBytes);
String message = new String(jsonBytes, "UTF-8");
JSONObject demoJson = JSONObject.fromObject(message);
System.out.println("JSON字符串[getTicket]:" + demoJson);
ticket = demoJson.getString("ticket");
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return ticket;
}

public static String SHA1(String decript) {
try {
MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1");
digest.update(decript.getBytes());
byte messageDigest[] = digest.digest();
// Create Hex String
StringBuffer hexString = new StringBuffer();
// 字节数组转换为 十六进制 数
for (int i = 0; i < messageDigest.length; i++) {
String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
if (shaHex.length() < 2) {
hexString.append(0);
}
hexString.append(shaHex);
}
return hexString.toString();

} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}


public static void main(String[] args) {
//我自己的约订号
String appId = "appId";//第三方用户唯一凭证
String secret = "secret";//第三方用户唯一凭证密钥,即appsecret

//1、获取AccessToken
String accessToken = getAccessToken(appId,secret);

//2、获取Ticket
String jsapi_ticket = getTicket(accessToken);

//3、时间戳和随机字符串
String noncestr = UUID.randomUUID().toString().replace("-", "").substring(0, 16);//随机字符串
String timestamp = String.valueOf(System.currentTimeMillis() / 1000);//时间戳

System.out.println("accessToken:" + accessToken + "\njsapi_ticket[jsapi_ticket]:" + jsapi_ticket + "\n时间戳[timestamp]:" + timestamp + "\n随机字符串[noncestr]:" + noncestr);

//4、获取url
//String url = "http://www.luiyang.com/add.html";
String url = "http://www.zhendoc.com/zhenh5/pages/demo/201601/index.html";
/*根据JSSDK上面的规则进行计算,这里比较简单,我就手动写啦
String[] ArrTmp = {"jsapi_ticket","timestamp","nonce","url"};
Arrays.sort(ArrTmp);
StringBuffer sf = new StringBuffer();
for(int i=0;i sf.append(ArrTmp[i]);
}
*/

//用时间戳、随机数、jsapi_ticket和要访问的url按照签名算法拼接字符串;
//5、将参数排序并拼接字符串
String str = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + noncestr + "×tamp=" + timestamp + "&url=" + url;
System.out.println("★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★");
System.out.println("★ 参数:" + str);
System.out.println("★ jsapi_ticket:" + jsapi_ticket);
System.out.println("★ noncestr:" + noncestr);
System.out.println("★ timestamp:" + timestamp);
System.out.println("★ url:" + url);
//对第三步的字符串进行SHA1加密,得到签名。
//6、将字符串进行sha1加密
String signature = SHA1(str);
System.out.println("★ 签名[signature]:" + signature);
System.out.println("★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★");
StringBuffer sb=new StringBuffer();
sb.append("wx.config({\n" +
"\tdebug: true,\n" +
"\tappId:'"+appId+"',\n" +
"\ttimestamp: "+timestamp+",\n" +
"\tnonceStr: '"+noncestr+"',\n" +
"\tsignature: '"+signature+"',\n" +
"\tjsApiList: [\n" +
"\t\t'checkJsApi',\n" +
"\t\t'onMenuShareAppMessage',\n" +
"\t\t'onMenuShareTimeline'\n" +
"\t]\n" +
"});");
System.out.println(sb.toString());
System.out.println("★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★");
}
}

你可能感兴趣的:(Android&HTML5)