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

How does java connect to Wechat JS-SDK?

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

In this article, the editor introduces in detail "how to access Wechat JS-SDK by java". The content is detailed, the steps are clear, and the details are handled properly. I hope this article "how to access Wechat JS-SDK by java" can help you solve your doubts. Let's follow the editor's ideas to learn new knowledge.

Step 1: bind the domain name

Log in to the Wechat public platform and enter the "function Settings" of "official account Settings" to fill in "JS API Security Domain name".

Note: after logging in, you can view the corresponding API permissions in the developer Center.

Step 2: introduce the JS file

Introduce the following JS file (https is supported) on the page that needs to call the JS API: http://res.wx.qq.com/open/js/jweixin-1.4.0.js

If you need to further improve the stability of the service, when the above resources are not accessible, you can visit http://res2.wx.qq.com/open/js/jweixin-1.4.0.js (https is supported).

Note: AMD/CMD standard module loading method is supported.

Step 3: configure wx.config ({debug: true, / / enable debug mode) by injecting permissions into the config API. The returned values of all api called will be displayed in the client alert. To view the passed parameters, you can open them on the PC side, and the parameter information will be typed out through log and printed only on the PC side. AppId:'', / / required, unique ID of official account timestamp:, / / required, timestamp for generating signature nonceStr:', / / required, random string for generating signature signature:', / / required, signature jsApiList: [] / / required, list of JS interfaces to be used}) When you complete the above three steps, you can use Wechat JS-SDK features, the above steps are simple to set up, that is, the config signature information acquisition is a bit troublesome, here mainly describes the next signature acquisition, permission signature algorithm in api has a simple description, here a simple description of the signature rules. The rules for generating signatures are as follows: the fields participating in the signature include noncestr (random string), valid jsapi_ticket, timestamp (timestamp), and url (the URL of the current web page, excluding # and its following parts). Noncestr can generate a random uuid, and the timestamp can directly obtain the current time. These implementations do not require any difficulty, and the next step is the acquisition of jsapi_ticket. Jsapi_ticket is a temporary ticket used by the official account to call the Wechat JS API. Normally, the jsapi_ticket is valid for 7200 seconds and is obtained through access_token. Access_token is generally set for global caching, which can continue to be used during the validity period of access_token. In this example, we implement global caching of access_token through singleton mode, which is only suitable for single-instance services. If it is multiple instances, please modify it to database or redies for global caching. When noncestr, jsapi_ticket, timestamp, url and other data are obtained, url splicing is performed according to noncestr=Wm3WZYTPz0wzccnW&jsapi_ticket=sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg×tamp=14145874577&url= http://mp.weixin.qq.com?params=value, and then the signature can be obtained by SHA1. Code example:

1. Accept the entity class of access_token, because the validity of access_token is 7200 seconds

1 import java.util.*; 2 3 public class Singleton {4 / / Map of cache accessToken, map contains an accessToken and cache timestamp 5 / / of course, it can also be separated into two attributes: 6 private Map map = new HashMap (); 7 8 private Singleton () {9} 10 11 private static Singleton single = null 12 13 / / static factory method 14 public static Singleton getInstance () {15 if (single = = null) {16 single = new Singleton (); 17} 18 return single;19} 20 21 public Map getMap () {22 return map;23} 24 25 public void setMap (Map map) {26 this.map = map 27} 28 29 public static Singleton getSingle () {30 return single;31} 32 33 public static void setSingle (Singleton single) {34 Singleton.single = single;35} 36}

Get the jsapi_ticket and generate the signature

Public class WxUtils {public static String appId = "Wechat official account appid"; public static String appSecret = "Wechat official account appSecret"; / / get the url public final static String js_api_ticket_url of access_token = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi"; / * get access_token * * @ return * / private static String getAccessToken () {String rel = ""; Singleton singleton = Singleton.getInstance (); Map map = singleton.getMap (); String time = map.get ("access_token_time"); String accessToken = map.get ("access_token"); Long nowDate = new Date (). GetTime () / / just set the expiration time of 30000000000 here. If (accessToken! = null & & time! = null & & nowDate-Long.parseLong (time))

< 7200 * 1000) { rel = accessToken; } else { String url = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", appId, appSecret); String result = HttpUtils.defaultGetMethod(url); if (StringUtils.isBlank(result)) { return null; } JsonObject responseJsonObject = GsonUtils.parseToJsonObj(result); map.put("access_token_time", nowDate + ""); map.put("access_token", GsonUtils.getString(responseJsonObject, "access_token")); rel = GsonUtils.getString(responseJsonObject, "access_token"); } return rel; } private static String getJsapiTicket(String accessToken) { String rel = ""; Singleton singleton = Singleton.getInstance(); Map map = singleton.getMap(); String js_api_ticketn_time = map.get("js_api_ticketn_time"); String ticket = map.get("ticket"); Long nowDate = new Date().getTime(); if (ticket != null && js_api_ticketn_time != null && nowDate - Long.parseLong(js_api_ticketn_time) < 7200 * 1000) { rel = ticket; } else { String url = js_api_ticket_url.replace("ACCESS_TOKEN", accessToken); String result = HttpUtils.defaultGetMethod(url); if (StringUtils.isBlank(result)) { return null; } JsonObject responseJsonObject = GsonUtils.parseToJsonObj(result); map.put("js_api_ticketn_time", nowDate + ""); map.put("ticket", GsonUtils.getString(responseJsonObject, "ticket")); rel = GsonUtils.getString(responseJsonObject, "ticket"); } return rel; } public static Map getConfig(String url) { String accessToken = getAccessToken(); String ticket = getJsapiTicket(accessToken); String nonceStr = create_nonce_str(); String timestamp = create_timestamp(); String string1 = "jsapi_ticket=" + ticket + "&noncestr=" + nonceStr + "×tamp=" + timestamp + "&url=" + url; Map map = new HashMap(); map.put("appId", appId); map.put("timestamp", timestamp); map.put("nonceStr", nonceStr); map.put("signature", SHA1.encode(string1)); return map; } private static String create_nonce_str() { return UUID.randomUUID().toString(); } private static String create_timestamp() { return Long.toString(System.currentTimeMillis() / 1000); }} SHA1签名 /* * 微信公众平台(JAVA) SDK * * Copyright (c) 2016, Ansitech Network Technology Co.,Ltd All rights reserved. * http://www.ansitech.com/weixin/sdk/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */import java.security.MessageDigest;/** * Title: SHA1算法 * * @author levi */public final class SHA1 { 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 static 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);}

Through the above method, we have prepared all the materials for accessing Wechat JS-SDK, so how to use it at the front end, we only need to request to the backend to obtain the relevant data of config. It is recommended to enable debug in debug mode for the first time. Successful access will pop up when debug debug mode is enabled.

1 $(function () {2 wxConfig ()) / / access Wechat jssdk 3}) 4 5 / / request the backend to obtain the information needed by wxconfig 6 function wxConfig () {7 $.ajax ({8 url:'/ pvmap-web/getData/wxConfig', 9 type: 'get',10 data: {url: _ window.location.href}, 11 dataType:' json' 12 success: function (data) {13 / / console.log (data) 14 if (data.data! = null | | data.data! = "") {15 wx.config ({16 debug: true, / / enable debug mode, and the return values of all api called will be displayed in the client alert. To view the parameters passed in, you can open them on the PC side, and the parameter information will be typed out through log and printed only on the PC side. 17 appId: data.data.appId, / / required, unique ID of official account 18 timestamp: data.data.timestamp, / / required, timestamp for generating signature 19 nonceStr: data.data.nonceStr, / / required, random string for generating signature 20 signature: data.data.signature,// required Signature 21 jsApiList: ['openLocation'] / / required, list of JS interfaces to be used 22}) 23} 24}, 25 erroe: function (e) {26 console.log (e) 27} 28}) 29} here, the article "how to connect java to Wechat JS-SDK" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it before you can understand it. If you want to know more about related articles, Welcome to the industry information channel.

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

Development

Wechat

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

12
Report