知識
不管是網站,軟件還是小程序,都要直接或間接能為您產生價值,我們在追求其視覺表現(xiàn)的同時,更側重于功能的便捷,營銷的便利,運營的高效,讓網站成為營銷工具,讓軟件能切實提升企業(yè)內部管理水平和效率。優(yōu)秀的程序為后期升級提供便捷的支持!
h5頁面按鈕跳轉小程序
發(fā)表時間:2020-11-3
發(fā)布人:葵宇科技
瀏覽次數:65
h5頁面按鈕跳轉小程序
- 參考文檔
- 步驟一:綁定域名
- 步驟二:引入JS文件
- 步驟三:配置config信息
本人前端菜鳥,這個功能難了我好幾天,經過請教各方大佬和查看無數文檔最終寫出來了,現(xiàn)在把自己的步驟總結出來供大家觀看指導。
參考文檔
鏈接: https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_Open_Tag.html.
步驟一:綁定域名
登錄微信公眾平臺進入“公眾號設置”的“功能設置”里填寫“JS接口安全域名”。
注意:是“公眾號設置”,而不是“小程序設置”。
步驟二:引入JS文件
在要跳轉小程序的頁面中引入JS文件:http://res.wx.qq.com/open/js/jweixin-1.6.0.js (支持https)
步驟三:配置config信息
我在這一步卡了好久,剛開始不了解簽名,也不會生成,所以這一步寫的詳細一些。
參考文檔: https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html#62.
- 獲取access_token
參考文檔: https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_access_token.html.
注意: 其中appid和secret是公眾號的appid和secret,調用接口獲取到access_token。 - 獲取jsapi_ticket
將上一步獲取到的access_token作為參數調用接口get方式獲取jsapi_ticket。
接口路徑: https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi - 生成簽名
簽名生成規(guī)則如下:參與簽名的字段包括noncestr(隨機字符串), 有效的jsapi_ticket, timestamp(時間戳), url(當前網頁的URL,不包含#及其后面部分) 。對所有待簽名參數按照字段名的ASCII 碼從小到大排序(字典序)后,使用URL鍵值對的格式(即key1=value1&key2=value2…)拼接成字符串string1。這里需要注意的是所有參數名均為小寫字符。對string1作sha1加密,字段名和字段值都采用原始值,不進行URL 轉義。
以下是我用java寫的后臺生成簽名的代碼。
@Override
public Result<Object> getWxConfigInfo(String currentPageUrl) {
Result<Object> result = new Result<Object>();
HashMap<String, Object> header = null;
HashMap<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("grant_type", "client_credential"); //固定值
paramMap.put("appid", ""); //自己公眾號的appid
paramMap.put("secret", ""); //自己公眾號的secret
String url = "https://api.weixin.qq.com/cgi-bin/token"; //獲取access_token調用的接口
String httpGet = httpClientUtils.httpGet(url, paramMap, header);
// 字符串轉換為JSON
JSONObject jsonObject = JSON.parseObject(httpGet); // result數據源:JSON格式字符串
String accessToken = jsonObject.getString("access_token");
paramMap.put("access_token", accessToken);
paramMap.put("type", "jsapi");
url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket"; //獲取jsapi_ticket調用的接口
httpGet = httpClientUtils.httpGet(url, paramMap, header);
// 字符串轉換為JSON
jsonObject = JSON.parseObject(httpGet); // result數據源:JSON格式字符串
logger.info(httpGet);
// 獲取值
String ticket = jsonObject.getString("ticket");
if (ticket == null || "".equals(ticket)) {
result.setCode(4);
result.setMessage(httpGet);
return result;
}
Map<String, String> data = new HashMap<String, String>();
String noncestr = UUID.randomUUID().toString().replace("-", "").substring(0, 16); //隨機串
String timestamp = String.valueOf(System.currentTimeMillis() / 1000); //時間戳
data.put("noncestr", noncestr);
data.put("jsapi_ticket", ticket);
data.put("timestamp", timestamp);
data.put("url", currentPageUrl); //調用接口的頁面路徑,從前端傳到后端的
String str = "jsapi_ticket=" + ticket + "&noncestr=" + noncestr + "×tamp=" + timestamp + "&url="
+ currentPageUrl; //將參數排序并拼接字符串
// 生成簽名
String signature = sha1(str); //將字符串進行sha1加密
data.put("signature", signature);
data.put("appId", ""); 自己公眾號的appid
data.remove("jsapi_ticket");
result.setData(data);
return result;
}
/**
* 生成簽名.
*
* @param decript 待簽名數據
* @return 簽名
*/
public static String sha1(String decript) {
try {
MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1");
digest.update(decript.getBytes());
byte messageDigest[] = digest.digest();
// Create Hex String
StringBuffer hexString = new StringBuffer();
// 字節(jié)數組轉換為 十六進制 數
for (int i = 0; i < messageDigest.length; i++) {
String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
if (shaHex.length() < 2) {
hexString.append(0);
}
hexString.append(shaHex);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
注意事項:
- 簽名用的noncestr和timestamp必須與wx.config中的nonceStr和timestamp相同。
- 簽名用的url必須是調用JS接口頁面的完整URL。
- 出于安全考慮,開發(fā)者必須在服務器端實現(xiàn)簽名的邏輯。
如出現(xiàn)invalid signature 等錯誤詳見步驟三中第一個參考文檔里的附錄5常見錯誤及解決辦法。
這樣config需要的配置信息就得到了。下面是在前段取數據的代碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.6.0.js">
</script>
<script src="js/jquery-2.1.4.js"></script>
<script type="text/javascript">
$(function() {
$.post("后端要調用的接口路徑", {
currentPageUrl: window.location.href //當前頁面路徑
},
function(res) {
console.log(res);
wx.config({
debug: true, // 開啟調試模式,調用的所有api的返回值會在客戶端alert出來,若要查看傳入的參數,可以在pc端打開,參數信息會通過log打出,僅在pc端時才會打印。最終彈出{"errMsg":"config:ok"}表明配置成功,可以將此參數改為false
appId: res.data.appId, // 必填,公眾號的唯一標識
timestamp: res.data.timestamp, // 必填,生成簽名的時間戳
nonceStr: res.data.noncestr, // 必填,生成簽名的隨機串
signature: res.data.signature, // 必填,簽名
jsApiList: ['updateAppMessageShareData'], // 必填,需要使用的JS接口列表。這個參數我沒看懂,所以瞎填了一個
openTagList: ['wx-open-launch-weapp'] // 可選,跳轉小程序使用['wx-open-launch-weapp'],跳轉APP使用['wx-open-launch-app']
});
});
wx.ready(function () {
console.log("success");
});
wx.error(function (res) {
console.log("error");
});
});
</script>
<body>
//username 所需跳轉的小程序原始id,即小程序對應的以gh_開頭的id,path 所需跳轉的小程序內頁面路徑及參數,必須帶.html
<wx-open-launch-weapp id="launch-btn" username="gh_*******" path="pages/index/index.html">
<template>
<style>
.btn {
padding: 12px
}
</style>
<button class="btn">打開小程序</button>
</template>
</wx-open-launch-weapp>
<script>
var btn = document.getElementById('launch-btn');
btn.addEventListener('launch', function(e) {
console.log('success');
});
btn.addEventListener('error', function(e) {
console.log('fail', e.detail);
});
</script>
</body>
</html>
這樣就完成跳轉小程序的代碼了,可以開始測試了。
注意: 在開發(fā)工具中按鈕不會顯示,因為template默認是display:none的,必須在真機測試時按鈕才會顯示。
注意: 如果頁面中除了跳轉按鈕還有其他按鈕或者背景圖片什么的,這些標簽要寫在開放標簽wx-open-launch-weapp外,否則所有的功能都會是打開小程序