短信鏈接帶參數(shù)跳轉(zhuǎn)小程序

創(chuàng)建云函數(shù)

// 云函數(shù)入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函數(shù)入口函數(shù)
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  switch (event.action) {
    case 'getUrlScheme': {
      return getUrlScheme(event.id)  //event.id可以取到index.html傳來的id參數(shù)
    }
  }

  return 'action not found'
}

async function getUrlScheme(id) {
  return cloud.openapi.urlscheme.generate({
    jumpWxa: {
      path: '/page/activity_detail/index', // <!-- replace -->
      query: 'id='+id,
    },
    // 如果想不過期則置為 false,并可以存到數(shù)據(jù)庫
    isExpire: false,
    // 一分鐘有效期
    expireTime: parseInt(Date.now() / 1000 + 60),
  })
}

新建index.html

<html>
  <head>
    <title>打開小程序</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1">
    <script>
      window.onerror = e => {
        console.error(e)
        alert('發(fā)生錯誤' + e)
      }
    </script>
    <!-- weui 樣式 -->
    <link rel="stylesheet" ></link>
    <!-- 調(diào)試用的移動端 console -->
    <!-- <script src="https://cdn.jsdelivr.net/npm/eruda"></script> -->
    <!-- <script>eruda.init();</script> -->
    <!-- 公眾號 JSSDK -->
    <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
    <!-- 云開發(fā) Web SDK -->
    <script src="https://res.wx.qq.com/open/js/cloudbase/1.1.0/cloud.js"></script>
    <script>
      function docReady(fn) {
        if (document.readyState === 'complete' || document.readyState === 'interactive') {
          fn()
        } else {
          document.addEventListener('DOMContentLoaded', fn);
        }
      }

function getQueryString(name) {
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
    var r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return unescape(r[2]);
    }
    return null;
}

function getQueryVariable(variable)
{
       var query = window.location.search.substring(1);
       var vars = query.split("&");
       for (var i=0;i<vars.length;i++) {
               var pair = vars[i].split("=");
               if(pair[0] == variable){return pair[1];}
       }
       return(false);
} 
      docReady(async function() {
        var ua = navigator.userAgent.toLowerCase()
        var isWXWork = ua.match(/wxwork/i) == 'wxwork'
        var isWeixin = !isWXWork && ua.match(/micromessenger/i) == 'micromessenger'
        var isMobile = false
        var isDesktop = false
        if (navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|IEMobile)/i)) {
          isMobile = true
        } else {
          isDesktop = true
        }

        if (isWeixin) {
          // alert(getQueryString('id'))
          var urlId = getQueryString('id')
          var path = '/packageB/activity_detail/index?id='+urlId
          alert(path)
          document.getElementById('launch-btn').setAttribute('path', path)

          var containerEl = document.getElementById('wechat-web-container')
          containerEl.classList.remove('hidden')
          containerEl.classList.add('full', 'wechat-web-container')

          var launchBtn = document.getElementById('launch-btn')
          launchBtn.addEventListener('ready', function (e) {
            console.log('開放標簽 ready')
          })
          launchBtn.addEventListener('launch', function (e) {
            console.log('開放標簽 success')
          })
          launchBtn.addEventListener('error', function (e) {
            console.log('開放標簽 fail', e.detail)
          })

          wx.config({
            // debug: true, // 調(diào)試時可開啟
            appId: 'APPID', // <!-- replace -->
            timestamp: 0, // 必填,填任意數(shù)字即可
            nonceStr: 'nonceStr', // 必填,填任意非空字符串即可
            signature: 'signature', // 必填,填任意非空字符串即可
            jsApiList: ['chooseImage'], // 必填,隨意一個接口即可 
            openTagList:['wx-open-launch-weapp'], // 填入打開小程序的開放標簽名
          })
        } else if (isDesktop) {
          // 在 pc 上則給提示引導到手機端打開
          var containerEl = document.getElementById('desktop-web-container')
          containerEl.classList.remove('hidden')
          containerEl.classList.add('full', 'desktop-web-container')
        }  else {
          var containerEl = document.getElementById('public-web-container')
          containerEl.classList.remove('hidden')
          containerEl.classList.add('full', 'public-web-container')
          var c = new cloud.Cloud({
            // 必填,表示是未登錄模式
            identityless: true,
            // 資源方 AppID
            resourceAppid: '資源方 AppID', // <!-- replace -->
            // 資源方環(huán)境 ID
            resourceEnv: '資源方環(huán)境 ID', // <!-- replace -->
          })
          await c.init()
          window.c = c

          var buttonEl = document.getElementById('public-web-jump-button')
          var buttonLoadingEl = document.getElementById('public-web-jump-button-loading')
          try {
            await openWeapp(() => {
              buttonEl.classList.remove('weui-btn_loading')
              buttonLoadingEl.classList.add('hidden')
            })
          } catch (e) {
            buttonEl.classList.remove('weui-btn_loading')
            buttonLoadingEl.classList.add('hidden')
            throw e
          }
        }
      })

      async function openWeapp(onBeforeJump) {
        var c = window.c
        const res = await c.callFunction({
          name: 'public',
          data: {
            action: 'getUrlScheme',
            // path:'/page/activity_detail/index',
           id:getQueryVariable("id")
          },
        })
        alert(res.result.openlink)
        console.warn(res)
        if (onBeforeJump) {
          onBeforeJump()
        }
        location.href = res.result.openlink
      }
    </script>
    <style>
      .hidden {
        display: none;
      }

      .full {
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
      }

      .public-web-container {
        display: flex;
        flex-direction: column;
        align-items: center;
      }

      .public-web-container p {
        position: absolute;
        top: 40%;
      }

      .public-web-container a {
        position: absolute;
        bottom: 40%;
      }

      .wechat-web-container {
        display: flex;
        flex-direction: column;
        align-items: center;
      }

      .wechat-web-container p {
        position: absolute;
        top: 40%;
      }

      .wechat-web-container wx-open-launch-weapp {
        position: absolute;
        bottom: 40%;
        left: 0;
        right: 0;
        display: flex;
        flex-direction: column;
        align-items: center;
      }

      .desktop-web-container {
        display: flex;
        flex-direction: column;
        align-items: center;
      }

      .desktop-web-container p {
        position: absolute;
        top: 40%;
      }
    </style>
  </head>
  <body>
    <div class="page full">
      <div id="public-web-container" class="hidden">
        <p class="">正在打開 “小程序”...</p> <!-- replace -->
        <a id="public-web-jump-button" href="javascript:" class="weui-btn weui-btn_primary weui-btn_loading" onclick="openWeapp()">
          <span id="public-web-jump-button-loading" class="weui-primary-loading weui-primary-loading_transparent"><i class="weui-primary-loading__dot"></i></span>
          打開小程序
        </a>
      </div>
      <div id="wechat-web-container" class="hidden">
        <p class="">點擊以下按鈕打開 “小程序 ”</p> <!-- replace -->
        <!-- 跳轉(zhuǎn)小程序的開放標簽。文檔 https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_Open_Tag.html -->
        <wx-open-launch-weapp id="launch-btn" username="小程序原始ID" path="/page/activity/index"> <!-- replace   -->
          <template>
            <button style="width: 200px; height: 45px; text-align: center; font-size: 17px; display: block; margin: 0 auto; padding: 8px 24px; border: none; border-radius: 4px; background-color: #07c160; color:#fff;">打開小程序</button>
          </template>
        </wx-open-launch-weapp>
      </div>
      <div id="desktop-web-container" class="hidden">
        <p class="">請在手機打開網(wǎng)頁鏈接</p>
      </div>
    </div>
    <script>
//將小程序路徑動態(tài)給wx-open-launch-weapp標簽的path屬性
 document.getElementById("launch-btn").setAttribute("path","/page/activity_detail/index?id="+getQueryVariable("id"));     
</script>
  </body>
</html>
設置權限
云函數(shù)權限修改
{
  // * 為通配符,表示對所有函數(shù)適用
  "*": {
    // invoke 表示調(diào)用權限控制
    // auth 包含鑒權信息,如果是未登錄模式,則 auth == null
    "invoke": "auth != null"
  },
  // 函數(shù)名,該規(guī)則優(yōu)先級會高于通配符
  "public": {
    // 表示允許所有來源調(diào)用,包括未登錄用戶
    "invoke": true
  }
}
配置域名
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容