您好,登錄后才能下訂單哦!
這篇文章主要介紹“微信開(kāi)發(fā)中獲取前端jssdk啟調(diào)參數(shù)的方法”,在日常操作中,相信很多人在微信開(kāi)發(fā)中獲取前端jssdk啟調(diào)參數(shù)的方法問(wèn)題上存在疑惑,小編查閱了各式資料,整理出簡(jiǎn)單好用的操作方法,希望對(duì)大家解答”微信開(kāi)發(fā)中獲取前端jssdk啟調(diào)參數(shù)的方法”的疑惑有所幫助!接下來(lái),請(qǐng)跟著小編一起來(lái)學(xué)習(xí)吧!
在進(jìn)行微信開(kāi)發(fā)時(shí),微信開(kāi)發(fā)前端要啟調(diào)微信jssdk相關(guān)服務(wù)常常需要使用一些秘密的參數(shù),這些參數(shù)暴露在外不是一件好事情,素以需要后端區(qū)調(diào)取這些jssdk參數(shù),這是我在開(kāi)發(fā)過(guò)程中和獲取jssdk參數(shù)開(kāi)發(fā)相關(guān)的code。
@Getter @Setter @ToString public class JSSDKConfig { private Boolean debug; private String appId; private Long timestamp; private String nonceStr; private String signature; private List<String> jsApiList; }
二、獲取jssdk中signature的工具類(lèi)
參數(shù)url是前端起吊當(dāng)前l(fā)ocation.herf(注意:url不能轉(zhuǎn)碼)
參數(shù)appid......
參數(shù)jsapiTicket是微信jsapiticket票據(jù),需要另外獲得。
import java.security.MessageDigest; import java.util.*; public class JSSDKSignatureUtil { /** * 獲取JSSDKConfig對(duì)象 * * @param url * @param appid * @param jsapiTicket * @return */ public static JSSDKConfig createJSSDKConfig(String url, String appid, String jsapiTicket) { String noncestr = getRandomStr(); Long timestamp = getTimeStamp(); JSSDKConfig jssdkConfig = new JSSDKConfig(); jssdkConfig.setDebug(false); jssdkConfig.setAppId(appid); jssdkConfig.setTimestamp(timestamp); jssdkConfig.setNonceStr(noncestr); jssdkConfig.setSignature(createSignature(jsapiTicket, url, noncestr, timestamp)); List<String> jsApiList = new ArrayList<>(); jssdkConfig.setJsApiList(jsApiList); return jssdkConfig; } /** * 創(chuàng)建SHA1簽名 * l * * @param jsapiTicket * @param url * @return */ private static String createSignature(String jsapiTicket, String url, String noncestr, Long timestamp) { SortedMap<String, Object> signParams = new TreeMap<String, Object>(); signParams.put("noncestr", noncestr); signParams.put("jsapi_ticket", jsapiTicket); signParams.put("timestamp", timestamp); signParams.put("url", url); return createSignature(signParams); } /** * 創(chuàng)建SHA1簽名 * * @param params * @return SHA1簽名 */ private static String createSignature(SortedMap<String, Object> params) { return sha1Encrypt(sortParams(params)); } /** * 根據(jù)參數(shù)名稱(chēng)對(duì)參數(shù)進(jìn)行字典排序 * * @param params * @return */ private static String sortParams(SortedMap<String, Object> params) { StringBuffer sb = new StringBuffer(); for (String key : params.keySet()) { sb.append(key).append("=").append(params.get(key)).append("&"); } return sb.substring(0, sb.lastIndexOf("&")); } /** * 使用SHA1算法對(duì)字符串進(jìn)行加密 * * @param str * @return */ private static String sha1Encrypt(String str) { if (str == null || str.length() == 0) { return null; } char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; try { MessageDigest mdTemp = MessageDigest.getInstance("SHA1"); mdTemp.update(str.getBytes("UTF-8")); byte[] md = mdTemp.digest(); int j = md.length; char buf[] = new char[j * 2]; int k = 0; for (int i = 0; i < j; i++) { byte byte0 = md[i]; buf[k++] = hexDigits[byte0 >>> 4 & 0xf]; buf[k++] = hexDigits[byte0 & 0xf]; } return new String(buf); } catch (Exception e) { return null; } } /** * 生成時(shí)間戳 * * @return */ private static Long getTimeStamp() { return System.currentTimeMillis() / 1000; } /** * 生成6位隨機(jī)字符串 * * @return */ private static String getRandomStr() { int length = 6; String base = "abcdefghijklmnopqrstuvwxyz0123456789"; Random random = new Random(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < length; i++) { int number = random.nextInt(base.length()); sb.append(base.charAt(number)); } return sb.toString(); } }
jsapiTicket參數(shù)不會(huì)過(guò)期,所以可以放入緩存中 參數(shù)包括access_token(該參數(shù)隔一段時(shí)間刷新,所以要也需要放入緩存) 其中appendParameterToUrl()是將map參數(shù)拼接到url后
public String getJsapiTicket() { String jsapiTicket = redisService.get("jsapi_ticket"); if (StringUtils.isBlank(jsapiTicket)) { try { Map<String, String> map = new HashMap<>(2); map.put("access_token", this.getAccessToken()); map.put("type", "jsapi"); String result = restTemplate.getForObject(this.appendParameterToUrl(weiXinConfig.jsapiTicketUrl, map), String.class); jsapiTicket = JsonUtils.parse(result, new String[]{"ticket"}); Integer expires = JsonUtils.parseInteger(result, new String[]{"expires_in"}); this.saveValueToRedisAndSetexpiresIn("jsapi_ticket", jsapiTicket, expires); } catch (IOException e) { e.printStackTrace(); log.error(Arrays.toString(e.getStackTrace())); throw new RuntimeException("獲取jsapi_ticket時(shí)的結(jié)果,json解析失敗"); } } return jsapiTicket; }
appendParameterToUrl():
/** * 將map拼接到url后面 * * @param url * @param map * @return */ private String appendParameterToUrl(String url, Map map) { StringBuilder sb = new StringBuilder(url); sb.append("?"); for (Object o : map.keySet()) { sb.append(o.toString()).append("=").append(map.get(o).toString()).append("&"); } return sb.toString().substring(0, sb.length() - 1); }
通過(guò)微信公眾平臺(tái)開(kāi)發(fā)者模式中的,appid和appSecret來(lái)獲access_token(注意:注意調(diào)用時(shí)的參數(shù)名稱(chēng))
public String getAccessToken() { String accessToken = (String) redisService.get("access_token"); if (StringUtils.isBlank(accessToken)) { try { Map<String, String> map = new HashMap<>(3); map.put("grant_type", "client_credential"); map.put("appid", weiXinConfig.appid); map.put("secret", weiXinConfig.appsecret); String accessTokenResult = restTemplate.getForObject(this.appendParameterToUrl(weiXinConfig.accessTokenUrl, map), String.class); accessToken = JsonUtils.parse(accessTokenResult, new Object[]{"access_token"}); Integer expiresIn = JsonUtils.parseInteger(accessTokenResult, new Object[]{"expires_in"}); this.saveValueToRedisAndSetexpiresIn("access_token", accessToken, expiresIn); } catch (IOException e) { e.printStackTrace(); log.error(Arrays.toString(e.getStackTrace())); throw new RuntimeException("獲取access_token時(shí)的結(jié)果,json解析失敗"); } } return accessToken; }
并給access_token添加緩存,并給key加上過(guò)期時(shí)間
/** * 將value保存起來(lái),并且設(shè)置過(guò)期時(shí)間 * * @param key * @param value * @param expiresIn */ private void saveValueToRedisAndSetexpiresIn(String key, String value, Integer expiresIn) { if (StringUtils.isNotBlank(key) && expiresIn != null) { redisService.set(key, value); redisService.expire(key, expiresIn); } }
將后端服務(wù)器的IP地址添加報(bào)名單。
將前端頁(yè)面的域名配置到該公眾號(hào)設(shè)置的功能設(shè)置中。
到此,關(guān)于“微信開(kāi)發(fā)中獲取前端jssdk啟調(diào)參數(shù)的方法”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)?lái)更多實(shí)用的文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。