-
生成微信簽名(只要訪問微信的接口,都需要生成簽名驗證來進行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 + "×tamp=" + 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(); });
-
訪問微信接口(獲取地理位置接口)
wx.getLocation({ debug: false, type: 'wgs84', // 默認為wgs84的gps坐標,如果要返回直接給openLocation用的火星坐標,可傳入'gcj02' success(res) { console.log("wx.getLocation"); var latitude = res.latitude; // 緯度,浮點數,范圍為90 ~ -90 var longitude = res.longitude; // 經度,浮點數,范圍為180 ~ -180。 var gpsPoint = new BMap.Point(longitude, latitude); BMap.Convertor.translate(gpsPoint, 0, initMap); //轉換坐標 }, fail(err){ console.log(err); } });