最近接到一個需求,要求實現從微信公眾號h5頁面跳轉到指定的小程序頁面。就查到微信開放標簽,但是使用起來真的是有點。。。。,分享下我的實現過程;
補充一點:所要跳轉的小程序必須要是正式版。
步驟一:綁定域名
登錄微信公眾平台進入“公眾號設置”的“功能設置”里填寫“JS接口安全域名”。
步驟二:引入JS文件
在需要調用JS接口的頁面引入如下JS文件:http://res.wx.qq.com/open/js/jweixin-1.6.0.js (支持https)
如需進一步提升服務穩定性,當上述資源不可訪問時,可改訪問:http://res2.wx.qq.com/open/js/jweixin-1.6.0.js (支持https)
備注:支持使用 AMD/CMD 標准模塊加載方法加載
(我用框架是Vue,如果是類似的框架在index.html標簽 引入即可)
步驟三:獲取簽名及wx.config參數所需的參數
以Vue框架為例,wx.config所需要的的參數有如下:
wx.config({ debug: true, // 開啟調試模式,調用的所有api的返回值會在客戶端alert出來,若要查看傳入的參數,可以在pc端打開,參數信息會通過log打出,僅在pc端時才會打印 appId: '', // 必填,公眾號的唯一標識 timestamp: , // 必填,生成簽名的時間戳 nonceStr: '', // 必填,生成簽名的隨機串 signature: '',// 必填,簽名 jsApiList: [], // 必填,需要使用的JS接口列表 openTagList: [] // 可選,需要使用的開放標簽列表,例如['wx-open-launch-app'] });
以上的除了jsApiList,openTagList,其他的內容都是由后端返回,調用接口直接使用就好。
created() { http({ method: 'POST', url: "xxxxxxx",// 請求接口的url
data: { url:window.location.href.split('#')[0] }, headers: { "Content-Type":"application/x-www-form-urlencoded;charset=UTF-8" } }).then(res => { console.log(wx) wx.config ({ appId:res.data.appId, timestamp:res.data.timestamp, nonceStr: res.data.noncestr, signature:res.data.signature , jsApiList: ["onMenuShareTimeline"], openTagList: ['wx-open-launch-weapp'] }); // 通過ready接口處理成功驗證 wx.ready(() => { var btn = document.getElementById('launch-btn'); btn.addEventListener('launch', function (e) { }); btn.addEventListener('error', function (e) { console.log('fail', e.detail); }); }); // 通過error接口處理失敗驗證 wx.error(function (res) { console.log(res) }); }).catch(err =>{ console.log(err); }); }
想要使用微信開放標簽的第一步是config得成功,不然后出現各種錯誤,
步驟四:使用標簽
HTML代碼如下:
<wx-open-launch-weapp id="launch-btn" username="gh_xxxxx" path="pages/index/index.html" > <script type="text/wxtag-template"> <div> <style> .btn{ outline: none; width: 300px; height: 45px; border: 1px solid rgba(240, 131, 0, 1); } </style> <button class="btn">立即跳轉</button> </div> </script> </wx-open-launch-weapp>
1.username:是所要跳轉的小程序的原始Id,不是appId
2.path:是所要跳轉的小程序的頁面,頁面路徑后面必須要加.html后綴。
微信開放標簽有最低的微信版本要求,以及最低的系統版本要求。
如果開發過程中出現以下情況的,要確認一下,微信版本要求為:7.0.12及以上。 系統版本要求為:iOS 10.3及以上、Android 5.0及以上。