微信开发——使用微信接口(获取地理位置)

生成微信签名(只要访问微信的接口,都需要生成签名验证来进行config)

a. 获取AccessToken

//定义静态常量存放获取AccessToken的URL public final static String GetPageAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=SECRET"; /** * 获取AccessToken **/ public Map<String, String> getAccessToken(String appid, String appsecret) { //使用传入的appid和appsecret,获取指定的URL String requestUrl = GetPageAccessTokenUrl.replace("APPID", appid).replace("SECRET", appsecret); //发送请求,获取AccessToken HttpClient client = null; Map<String, String> result = new HashMap<String, String>(); String accessToken = null; try { client = new DefaultHttpClient(); HttpGet httpget = new HttpGet(requestUrl); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String response = client.execute(httpget, responseHandler); JSONObject OpenidJSONO = JSONObject.parseObject(response); accessToken = String.valueOf(OpenidJSONO.get("access_token")); result.put("accessToken", accessToken); } catch (Exception e) { e.printStackTrace(); } finally { client.getConnectionManager().shutdown(); } return result; }

b. 获取JsApiTicket

//定义静态常量存放获取JsApiTicket的URL public final static String GetPageJsApiTicketUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi"; /* * 获取JsApiTicket **/ public Map<String, String> getJsapiTicket(String accessToken) { String requestUrl = GetPageJsApiTicketUrl.replace("ACCESS_TOKEN", accessToken); HttpClient client = null; Map<String, String> result = new HashMap<String, String>(); try { client = new DefaultHttpClient(); HttpGet httpget = new HttpGet(requestUrl); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String response = client.execute(httpget, responseHandler); JSONObject OpenidJSONO = JSONObject.parseObject(response); String errcode = String.valueOf(OpenidJSONO.get("errcode")); String errmsg = String.valueOf(OpenidJSONO.get("errmsg")); String ticket = String.valueOf(OpenidJSONO.get("ticket")); String expires_in = String.valueOf(OpenidJSONO.get("expires_in")); result.put("errcode", errcode); result.put("errmsg", errmsg); result.put("ticket", ticket); result.put("expires_in", expires_in); } catch (Exception e) { e.printStackTrace(); } finally { client.getConnectionManager().shutdown(); } return result; }

c. 获取随机字符串

public String getRandomStr(int length) { String base = "abcdefghijklmnopqrstuvwxyz0123456789"; int randomNum; char randomChar; Random random = new Random(); // StringBuffer类型的可以append增加字符 StringBuffer str = new StringBuffer(); for (int i = 0; i < length; i++) { // 可生成[0,n)之间的整数,获得随机位置 randomNum = random.nextInt(base.length()); // 获得随机位置对应的字符 randomChar = base.charAt(randomNum); // 组成一个随机字符串 str.append(randomChar); } return str.toString(); }

d. 获取时间戳

String timestamp = String.valueOf(System.currentTimeMillis() / 1000);

e. 按顺序拼接字符串

String str = "jsapi_ticket=" + jsapiTicket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=" + url;//将参数排序并拼接字符串

f. 使用SH1加密字符串

/** * SH1加密 */ private static final char[] HEX_DIGITS = {\'0\', \'1\', \'2\', \'3\', \'4\', \'5\', \'6\', \'7\', \'8\', \'9\', \'a\', \'b\', \'c\', \'d\', \'e\', \'f\'}; /** * Takes the raw bytes from the digest and formats them correct. * * @param bytes the raw bytes from the digest. * @return the formatted bytes. */ private static String getFormattedText(byte[] bytes) { int len = bytes.length; StringBuilder buf = new StringBuilder(len * 2); // 把密文转换成十六进制的字符串形式 for (int j = 0; j < len; j++) { buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]); buf.append(HEX_DIGITS[bytes[j] & 0x0f]); } return buf.toString(); } public String encode(String str) { if (str == null) { return null; } try { MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(str.getBytes()); return getFormattedText(messageDigest.digest()); } catch (Exception e) { throw new RuntimeException(e); } }

j. 返回数据

JSONObject jsonObject = new JSONObject(); jsonObject.put("appId", "APPID"); jsonObject.put("timestamp",timestamp); jsonObject.put("accessToken",accessToken); jsonObject.put("ticket",jsapiTicket); jsonObject.put("nonceStr",noncestr); jsonObject.put("signature",signature); return ResultUtil.successResult(jsonObject);

使用生成的签名访问微信API之前需要先进行wx.config校验
(企业微信签名正确但是验证不通过,说明没有进行安全域名验证,需要进入企业微信找到对应的应用进行安全域名验证)

wx.config({ debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来 appId: data.content.appId,// 必填,公众号的唯一标识 timestamp: data.content.timestamp,// 必填,生成签名的时间戳 nonceStr: data.content.nonceStr, // 必填,生成签名的随机串 signature: data.content.signature,// 必填,签名,见附录1 jsApiList: [\'getLocation\'] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2 }); wx.error(function (res) { console.log(res); }); wx.ready(function() { // config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。 console.log("wx.ready"); wxlocate(); });

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zgwjfz.html