H5打開小程序

H5打開小程序 分為普通瀏覽器-和微信瀏覽器

在這個之前必須要滿足

公眾號

  1. 已認證的服務號,服務號綁定“JS接口安全域名”下的網頁可使用此標簽跳轉任意合法合規的小程序。
  2. 已認證的非個人主體的小程序,使用小程序云開發的靜態網站托管綁定的域名下的網頁,可以使用此標簽跳轉任意合法合規的小程序。

普通瀏覽器
1、獲取小程序scheme碼,適用于短信、郵件、外部網頁等拉起小程序的業務場景。通過該接口,可以選擇生成到期失效和永久有效的小程序碼,目前僅針對國內非個人主體的小程序開放

H5打開小程序 普通瀏覽器

使用微信開放的urlscheme.generate生成小程序scheme碼 使用這個之前需要先獲取到接口調用憑證拿到access_token

常見錯誤

/* 普通瀏覽器--這個放在前端請求也是可以的-不過不建議 */

          const appid = '小程序appid';
            const secret = '小程序secret ';
          //獲取access_token
            const {data:{access_token}} = await axios.request({
                  url:`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${secret}`
            })
            
            //獲取scheme
            const {data:{openlink}} = await axios.post("https://api.weixin.qq.com/wxa/generatescheme?access_token="+access_token,{
                  "jump_wxa" : {
                        "path" : "/pages/index/index",
                        "query" : "dex=2"
                  }
            })

          //openlink就是scheme
            console.log(openlink);

          然后使用weixin://dl/business/?t= openlink
          直接使用location.href = 'weixin://dl/business/?t= openlink'
          或者創建一個a標簽,get事件也是可以的

微信公眾號 --這個就必須要服務器了

普通瀏覽器的相對公眾號還是比較簡單的,公眾號還要使用jssdk還要配置sdk-還要配置服務器,
官方文檔

配置好服務器的可以跳過直接看下面
1、先要配置-進入公眾號-開發-基本配置-服務器配置-啟用填好資料,
當然你也可以選擇明文模式
查看示例
2、保存的時候會請求校驗服務器-請求上面寫的URL

//加密模塊
import crypto from 'crypto';
//加密方法
function signFn(arr:Array<string>){
      const sha1  = crypto.createHash('sha1');//sha1
      var str=arr.sort().join('');
      sha1.update(encodeURI(str));//添加需要的加密數據
      return sha1.digest('hex');//加密,(hex表示16進制)
  }

//--[token,傳過來的時間戳,傳過來的隨機字符串]
var obj=['1839a5f3b7feba22a6e2a6ef1467d348',this.get('timestamp'),this.get('nonce')];
            //進行加密
            var sign=signFn(obj);
            console.log(this.get('signature'));
            //對比加密
            if(sign === this.get('signature')){
                  return this.body = this.get('echostr');
            }
            return this.body = 'error';

配置好之后就需要寫獲取jssdk然后配置jssdk

//服務器端代碼
import crypto from 'crypto';

const appid = '公眾號appid';
const secret = '公眾號secret';

//服務器當前時間
 const timestamp = parseInt(String(new Date().getTime()));
//隨機字符串
const nonceStr = 'Wm3WZYTPz0wzccnW';
//加密方式
const sha2  = crypto.createHash('sha1');//sha1
 
//獲取access_token
const {data:{access_token}} = await axios.request({
          url:"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret;
 })

//獲取api ticket
const {data:{ticket}} = await axios.request({
           url:"https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+access_token+"&type=jsapi"
})
   //需要當前驗證的頁面路徑
const reUrl = this.post('url');
            
if(reUrl)
{
  //加密方式依次為ticket 隨機字符串noncestr 時間戳timestamp 驗證的頁面url
      const content = `jsapi_ticket=${ticket}&noncestr=${nonceStr}&timestamp=${timestamp}&url=${url}`;
                  //加密
      const signature = sha2.update(content).digest('hex')
    //返回給前端
      return this.json({
             appid,
             timestamp,
             signature,
             nonceStr
         })
 }

//前端代碼 -js
安裝jssdk(npm install weixin-js-sdk --S) 或者直接[cnds](https://res.wx.qq.com/open/js/jweixin-1.6.0.js)
const get =  async function(){
              //請求上面寫好的接口
                const response = await fetch('jssdk路徑',{
                        method:"post",
                        headers: {
                              "Content-type": "application/x-www-form-urlencoded; charset=UTF-8",
                        },
                        body:`url=${location.href.split('#')[0]}`
                  })
                //返回的數據
                  const {data} = await response.json();
                  wx.config({
                        debug: false, // 開啟調試模式,調用的所有api的返回值會在客戶端alert出來,若要查看傳入的參數,可以在pc端打開,參數信息會通過log打出,僅在pc端時才會打印。
                        appId: data.appid, // 必填,公眾號的唯一標識
                        timestamp: data.timestamp, // 必填,生成簽名的時間戳
                        nonceStr: data.noncestr, // 必填,生成簽名的隨機串
                        signature: data.signature,// 必填,簽名
                        jsApiList: ['checkJsApi'], // 必填,需要使用的JS接口列表
                        openTagList: ['wx-open-launch-weapp'],   //這里一定要寫上wx-open-launch-weapp 不寫就不會出現
                  });
//走這個回調的時候說明注入成功了
wx.ready(function(){})  
//這里就肯定失敗了
wx.error(function(){})
            }
get();

//html代碼
//path小程序的頁面路徑-一定要加上.html
//這個只會在微信瀏覽器里面而且jssdk注入成功才會顯示
<wx-open-launch-weapp id="launch-btn" class="launch-weapp" username="小程序原始id  gh_開頭的" path="/pages/guide/main.html">
                  <script type="text/wxtag-template">
                                             //樣式,只能寫在這里面外面不生效
                        <style>.btn { padding: 12px }</style>
                        <button class="btn">打開小程序1</button>
                  </script>
            </wx-open-launch-weapp>

我總結了以下幾點不顯示的問題
1、個人賬號 -- 沒辦法
2、簽名錯誤 -- 校驗簽名 看看access_token 是否獲取成功 看看ticket是否獲取成功 失敗一個都會簽名錯誤 簽名請求一定要帶上url
3、域名錯誤 -- 沒有設置安全域名-在設置-公眾號設置-功能設置里面
4、IP白名單 -- 把服務器ip加入到 ip白名單里面即可
5、vue里面會報錯wx-open-launch-weapp 標簽未注冊 --
···· 1在main.js添加Vue.config.ignoredElements = ['wx-open-launch-weapp']
···· 手動拼接用v-html顯示

this.wxOpenWeApp = `
        <wx-open-launch-weapp id="launch-btn" class="launch-weapp" username="小程序原始id  gh_開頭的" path="${path}">
            <script type="text/wxtag-template">
                <style>
                    .close-btn{
                        border: none;
                        outline: none;
                        padding: 10px 20px;
                        line-height: 1;
                    }
                </style>
                <button class="close-btn">
                    打開小程序
                </button>
            <\/script>
        </wx-open-launch-weapp>`

老規矩,個人的不會顯示
必須是已認證的服務號

推薦一個移動端開發利器 vconsole

建議再開發環境使用--生成環境當然也可以使用-可以使用特定參數進入的方式 比如帶參debug=xx
使用方法也簡單 new Vconsole()
npm cdns 都可以
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容