Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The method of obtaining the starting and adjusting parameters of Front-end jssdk in Wechat Development

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "the method of obtaining front-end jssdk tuning parameters in Wechat development". In daily operation, I believe that many people have doubts about the method of obtaining front-end jssdk tuning parameters in Wechat development. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer your doubts about "the method of obtaining front-end jssdk tuning parameters in Wechat development". Next, please follow the editor to study!

When carrying out Wechat development, the Wechat development front end often needs to use some secret parameters to activate Wechat jssdk related services. It is not a good thing that these parameters are exposed. It is always necessary to call these jssdk parameters in the backend area. This is the code related to obtaining jssdk parameters in the development process.

Edit the jssdk parameter class @ Getter@Setter@ToStringpublic class JSSDKConfig {private Boolean debug; private String appId; private Long timest private String nonceStr; private String signature; private List jsApiList;}

2. Get the tool class of signature in jssdk

Parameter url is the current location.herf of front-end hoisting (Note: url cannot be transcoded)

Parameter appid.

The parameter jsapiTicket is Wechat jsapiticket ticket, which needs to be obtained separately.

Import java.security.MessageDigest;import java.util.*;public class JSSDKSignatureUtil {/ * get JSSDKConfig object * * @ 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 jsApiList = new ArrayList (); jssdkConfig.setJsApiList (jsApiList); return jssdkConfig } / * create SHA1 signature * l * * @ param jsapiTicket * @ param url * @ return * / private static String createSignature (String jsapiTicket, String url, String noncestr, Long timestamp) {SortedMap signParams = new TreeMap (); signParams.put ("noncestr", noncestr); signParams.put ("jsapi_ticket", jsapiTicket); signParams.put ("timestamp", timestamp) SignParams.put ("url", url); return createSignature (signParams);} / * * create SHA1 signature * * @ param params * @ return SHA1 signature * / private static String createSignature (SortedMap params) {return sha1Encrypt (sortParams (params)) Dictionary sort parameters by parameter name * * @ param params * @ return * / private static String sortParams (SortedMap 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 ("&");} / * encrypt strings using the SHA1 algorithm * * @ 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, 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 [knot +] = hexDigits [byte0 & 0xf];} return new String (buf);} catch (Exception e) {return null;}} / * generate timestamp * * @ return * / private static Long getTimeStamp () {return System.currentTimeMillis () / 1000 } / * generate a 6-bit random string * * @ 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; iTunes +) {int number = random.nextInt (base.length ()) Sb.append (base.charAt (number));} return sb.toString ();}} III. Get the jsapiTicket bill

The jsapiTicket parameter does not expire, so you can put it in the cache, including access_token (this parameter is refreshed at regular intervals, so it also needs to be cached), where appendParameterToUrl () is the splicing of the map parameter to the url.

Public String getJsapiTicket () {String jsapiTicket = redisService.get ("jsapi_ticket"); if (StringUtils.isBlank (jsapiTicket)) {try {Map 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 ("result when getting jsapi_ticket, json parsing failed");}} return jsapiTicket;}

AppendParameterToUrl ():

/ * join map to the back of 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);} IV. Get the access_token parameter

Get the access_token through appid and appSecret in Wechat public platform developer mode (note: pay attention to the parameter name when calling)

Public String getAccessToken () {String accessToken = (String) redisService.get ("access_token"); if (StringUtils.isBlank (accessToken)) {try {Map 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 ("result when getting access_token, json parsing failed");}} return accessToken;}

Add cache to access_token and add expiration time to key

/ * Save the value and set the expiration time * * @ 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) Log in to the official account of Wechat to configure

Add the IP address of the back-end server to the list.

Configure the domain name of the front-end page into the function settings of the official account setting.

At this point, on the "Wechat development to obtain the front-end jssdk tuning parameters of the method," the study is over, I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report