package com.test.util;
/***
* V型知识库 www.vxzsk.com
*/
import java.util.UUID;
import java.util.Map;
import java.util.HashMap;
import java.util.Formatter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.io.UnsupportedEncodingException;
public class Sign {
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)
{
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);
}
public static void main(String[] args) {
String jsapi_ticket =JsapiTicketUtil.getJSApiTicket();
// 注意 URL 一定要动态获取,不能 hardcode
String url = "http://www.vxzsk.com/xx/x.do";//url是你请求的一个action或者controller地址,并且方法直接跳转到使用jsapi的jsp界面
Map<String, String> ret = sign(jsapi_ticket, url);
for (Map.Entry entry : ret.entrySet()) {
System.out.println(entry.getKey() + ", " + entry.getValue());
}
};
}
package com.test.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import net.sf.json.JSONObject;
import com.test.weixin.TestAcessToken;
/***
* @author V型知识库 www.vxzsk.com
*
*/
public class JsapiTicketUtil {
/***
* 模拟get请求
* @param url
* @param charset
* @param timeout
* @return
*/
public static String sendGet(String url, String charset, int timeout)
{
String result = "";
try
{
URL u = new URL(url);
try
{
URLConnection conn = u.openConnection();
conn.connect();
conn.setConnectTimeout(timeout);
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset));
String line="";
while ((line = in.readLine()) != null)
{
result = result + line;
}
in.close();
} catch (IOException e) {
return result;
}
}
catch (MalformedURLException e)
{
return result;
}
return result;
}
/***
* 获取acess_token
* 来源www.vxzsk.com
* @return
*/
public static String getAccessToken(){
String appid="你公众号基本设置里的应用id";//应用ID
String appSecret="你公众号基本设置里的应用密钥";//(应用密钥)
String url ="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+appSecret+"";
String backData=TestAcessToken.sendGet(url, "utf-8", 10000);
String accessToken = (String) JSONObject.fromObject(backData).get("access_token");
return accessToken;
}
/***
* 获取jsapiTicket
* 来源 www.vxzsk.com
* @return
*/
public static String getJSApiTicket(){
//获取token
String acess_token= JsapiTicketUtil.getAccessToken();
String urlStr = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+acess_token+"&type=jsapi";
String backData=TestAcessToken.sendGet(urlStr, "utf-8", 10000);
String ticket = (String) JSONObject.fromObject(backData).get("ticket");
return ticket;
}
public static void main(String[] args) {
String jsapiTicket = JsapiTicketUtil.getJSApiTicket();
System.out.println("调用微信jsapi的凭证票为:"+jsapiTicket);
}
}
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>微信jsapi测试-V型知识库</title>
<meta name="viewport" content="width=320.1,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no">
<script src="http://res.wx.qq.com/open/js/jweixin-1.1.0.js"> </script>
</head>
<body>
<center><h3>欢迎来到微信jsapi测试界面-V型知识库</h3></center>
<br>
<p>timestamp:${ timestamp}</p>
<p>nonceStr:${ nonceStr}</p>
<p>signature:${ signature}</p>
<p>appId:${ appId}</p>
<input type="button" value="upload" onclick="uploadImg();"/>
<input type="button" value="获取当前位置" onclick="getLocation();"/>
<br>
<script type="text/javascript">
wx.config({
debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: '${appId}', // 必填,公众号的唯一标识
timestamp: '${ timestamp}' , // 必填,生成签名的时间戳
nonceStr: '${ nonceStr}', // 必填,生成签名的随机串
signature: '${ signature}',// 必填,签名,见附录1
jsApiList: ['chooseImage','getLocation','openLocation'] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
});
wx.ready(function(){
alert("ready");
});
wx.error(function (res) {
alert("调用微信jsapi返回的状态:"+res.errMsg);
});
function uploadImg() {
wx.checkJsApi({
jsApiList: ['chooseImage','openLocation','getLocation'], // 需要检测的JS接口列表,所有JS接口列表见附录2,
success: function(res) {
// 以键值对的形式返回,可用的api值true,不可用为false
// 如:{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
alert(res);
wx.chooseImage({
count: 1, // 默认9
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function (res) {
var localIds = res.localIds; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
alert(localIds);
}
});
}
});
}
function getLocation() {
var latitude = "";
var longitude = "";
wx.getLocation({
type: 'gcj02', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'
success: function (res) {
latitude = res.latitude; // 纬度,浮点数,范围为90 ~ -90
longitude = res.longitude; // 经度,浮点数,范围为180 ~ -180。
var speed = res.speed; // 速度,以米/每秒计
var accuracy = res.accuracy; // 位置精度
wx.openLocation({
latitude: latitude, // 纬度,浮点数,范围为90 ~ -90
longitude: longitude, // 经度,浮点数,范围为180 ~ -180。
name: '你当前的位置', // 位置名
address: 'currentLocation', // 地址详情说明
scale: 26, // 地图缩放级别,整形值,范围从1~28。默认为最大
infoUrl: '' // 在查看位置界面底部显示的超链接,可点击跳转
});
}
});
}
</script>
</body>
</html>