Java通过微信公众号获取地理位置信息

1.绑定js的回调域名

		这个就不多说了,百度一大把  ,不会的去这儿  
		[微信官方文档](https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html)

2.js代码(看注释)

如果没有看过官方文档不建议看这个,看过文档的直接可以用这个使用了,结果还是比较精准的
js文件中要引入微信官方js

<script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
		//需要地址信息的时候运行此方法
		function start(){
			configWx();
		}
				
		function configWx() {
		//获取此页面的路径
		var thisPageUrl = location.href.split('#')[0];
		//使用ajax请求获取到微信验证的参数
				$.ajax({
				"url": "此处是你请求的后台的路径", 
				"data": "url="+thisPageUrl, 
				"dataType": "json", 
				"type": "GET",
				"success": function(data) {
					if(data != null){	
					//后台时用map的,所以此处直接接受data									
					configWeiXin(data.appId, data.timestamp, data.nonceStr,data.signature);
					}else{
						alert("连接服务器失败!")
					}
				}
			});				
		}
 
	function configWeiXin(appId, timestamp, nonceStr, signature) {
		wx.config({
			debug : true,// 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
			appId : appId,
			timestamp : timestamp,
			nonceStr : nonceStr,
			signature : signature,
			jsApiList : [ 'chooseImage', 'uploadImage', 'downloadImage',
					'previewImage', 'openLocation', 'getLocation',
					'scanQRCode', 'checkJsApi', 'onMenuShareTimeline',
					'onMenuShareAppMessage', 'onMenuShareQQ',
					'onMenuShareWeibo', 'onMenuShareQZone' ]
		});
		wx.getLocation({
			type : 'gcj02', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'
			success : function(res) {
				//使用微信内置地图查看位置接口
				wx.openLocation({
					latitude : res.latitude, // 纬度,浮点数,范围为90 ~ -90
					longitude : res.longitude, // 经度,浮点数,范围为180 ~ -180。
					name : '我的位置', // 位置名
					address : '测试地址', // 地址详情说明
					scale : 28, // 地图缩放级别,整形值,范围从1~28。默认为最大
					infoUrl : 'http://www.gongjuji.net' // 在查看位置界面底部显示的超链接,可点击跳转(测试好像不可用)
				});
			},
			cancel : function(res) {
				
			}
		});
	}	

java代码

	/**
	 * 获取页面需要的配置信息的参数
	 * 获取用户微信地理位置信息
	 * @param request
	 * @param url
	 * @return
	 */
	@ResponseBody
	@CrossOrigin
	@RequestMapping(value = "/getJsTicket")
	public Map<String, Object> getWeJsTicket(HttpServletRequest request, String url) {
		//1、获取AccessToken  
	    String accessToken = WxUtils.getAccessToken();
	    
	    //2、获取Ticket  
	    String jsapi_ticket = WxUtils.getTicket(accessToken);
	    
	    //3、时间戳和随机字符串  
	    String noncestr = UUID.randomUUID().toString().replace("-", "").substring(0, 16);//随机字符串  
	    String timestamp = String.valueOf(System.currentTimeMillis() / 1000);//时间戳  
	    
	    //5、将参数排序并拼接字符串  
	    String str = "jsapi_ticket="+jsapi_ticket+"&noncestr="+noncestr+"&timestamp="+timestamp+"&url="+url;  
		
	    //6、将字符串进行sha1加密  
	    String signature =WxUtils.SHA1(str); 
	    
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			// 获取微信signature
			map.put("appId", "你的appid");
			map.put("timestamp", timestamp);
			map.put("nonceStr", noncestr);
			map.put("signature", signature);
		} catch (Exception e) {
			//this.logger.error(e.getMessage());
		}
		return map;
	}
public class WxUtils {

	public static String getAccessToken() {  
	    String access_token = "";  
	    String grant_type = "client_credential";//获取access_token填写client_credential   
	    String AppId="你的公众号appid";//第三方用户唯一凭证  
	    String secret="你的公众号密匙";//第三方用户唯一凭证密钥,即appsecret   
	    //这个url链接地址和参数皆不能变  
	    String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type="+grant_type+"&appid="+AppId+"&secret="+secret;  
	       
	    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字符串:"+demoJson);  
	        access_token = demoJson.getString("access_token");  
	        is.close();  
	    } catch (Exception e) {  
	            e.printStackTrace();  
	    }  
	    return access_token;  
	}
	
	
	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链接和参数不能变  
	    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字符串:"+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 "";  
	}
}
  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值