本文小編為大家詳細(xì)介紹“java怎么接入微信JS-SDK”,內(nèi)容詳細(xì),步驟清晰,細(xì)節(jié)處理妥當(dāng),希望這篇“java怎么接入微信JS-SDK”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來(lái)學(xué)習(xí)新知識(shí)吧。
創(chuàng)新互聯(lián)公司專注于孝感網(wǎng)站建設(shè)服務(wù)及定制,我們擁有豐富的企業(yè)做網(wǎng)站經(jīng)驗(yàn)。 熱誠(chéng)為您提供孝感營(yíng)銷型網(wǎng)站建設(shè),孝感網(wǎng)站制作、孝感網(wǎng)頁(yè)設(shè)計(jì)、孝感網(wǎng)站官網(wǎng)定制、小程序定制開發(fā)服務(wù),打造孝感網(wǎng)絡(luò)公司原創(chuàng)品牌,更為您提供孝感網(wǎng)站排名全網(wǎng)營(yíng)銷落地服務(wù)。
先登錄微信公眾平臺(tái)進(jìn)入“公眾號(hào)設(shè)置”的“功能設(shè)置”里填寫“JS接口安全域名”。
備注:登錄后可在“開發(fā)者中心”查看對(duì)應(yīng)的接口權(quán)限。
在需要調(diào)用JS接口的頁(yè)面引入如下JS文件,(支持https):http://res.wx.qq.com/open/js/jweixin-1.4.0.js
如需進(jìn)一步提升服務(wù)穩(wěn)定性,當(dāng)上述資源不可訪問時(shí),可改訪問:http://res2.wx.qq.com/open/js/jweixin-1.4.0.js (支持https)。
備注:支持使用 AMD/CMD 標(biāo)準(zhǔn)模塊加載方法加載
wx.config({ debug: true, // 開啟調(diào)試模式,調(diào)用的所有api的返回值會(huì)在客戶端alert出來(lái),若要查看傳入的參數(shù),可以在pc端打開,參數(shù)信息會(huì)通過(guò)log打出,僅在pc端時(shí)才會(huì)打印。 appId: '', // 必填,公眾號(hào)的唯一標(biāo)識(shí) timestamp: , // 必填,生成簽名的時(shí)間戳 nonceStr: '', // 必填,生成簽名的隨機(jī)串 signature: '',// 必填,簽名 jsApiList: [] // 必填,需要使用的JS接口列表 });
1.承裝access_token的實(shí)體類,因?yàn)閍ccess_token的有效期是7200秒,
1 import java.util.*; 2 3 public class Singleton { 4 //緩存accessToken 的Map ,map中包含 一個(gè)accessToken 和 緩存的時(shí)間戳 5 //當(dāng)然也可以分開成兩個(gè)屬性咯 6 private Mapmap = new HashMap<>(); 7 8 private Singleton() { 9 } 10 11 private static Singleton single = null; 12 13 // 靜態(tài)工廠方法 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 }
獲取 jsapi_ticket以及生成簽名
public class WxUtils { public static String appId = "微信公眾號(hào)appid"; public static String appSecret = "微信公眾號(hào)appSecret "; //獲取access_token的url public final static String js_api_ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi"; /** * 獲取access_token * * @return */ private static String getAccessToken() { String rel = ""; Singleton singleton = Singleton.getInstance(); Mapmap = singleton.getMap(); String time = map.get("access_token_time"); String accessToken = map.get("access_token"); Long nowDate = new Date().getTime(); //這里設(shè)置過(guò)期時(shí)間 3000*1000就好了 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簽名
/* * 微信公眾平臺(tái)(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); // 把密文轉(zhuǎn)換成十六進(jìn)制的字符串形式 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); } } }
通過(guò)上面的方法,我們已經(jīng)準(zhǔn)備好了接入微信JS-SDK的所有材料,那么怎么在前端那邊使用,我們只需要請(qǐng)求到后臺(tái)獲取到config的相關(guān)數(shù)據(jù)就可以了。初次接入建議打開debug為調(diào)試模式,在debug調(diào)試模式打開的情況下接入成功會(huì)彈出成功提示。
1 $(function () { 2 wxConfig();//接入微信jssdk 3 }) 4 5 //請(qǐng)求后臺(tái)獲取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, // 開啟調(diào)試模式,調(diào)用的所有api的返回值會(huì)在客戶端alert出來(lái),若要查看傳入的參數(shù),可以在pc端打開,參數(shù)信息會(huì)通過(guò)log打出,僅在pc端時(shí)才會(huì)打印。 17 appId: data.data.appId, // 必填,公眾號(hào)的唯一標(biāo)識(shí) 18 timestamp: data.data.timestamp, // 必填,生成簽名的時(shí)間戳 19 nonceStr: data.data.nonceStr, // 必填,生成簽名的隨機(jī)串 20 signature: data.data.signature,// 必填,簽名 21 jsApiList: ['openLocation'] // 必填,需要使用的JS接口列表 22 }); 23 } 24 }, 25 erroe: function (e) { 26 console.log(e) 27 } 28 }) 29 }
讀到這里,這篇“java怎么接入微信JS-SDK”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識(shí)點(diǎn)還需要大家自己動(dòng)手實(shí)踐使用過(guò)才能領(lǐng)會(huì),如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。