乐趣区

关于小程序云开发:记录一次年前三天紧急上线一个小程序过程

背景

去年年末,离过年的工夫还剩几天,产品部的忽然跑过来问能不能年前做完而后上线一个小程序,利用过年的流量,引流一波。

工夫紧,工作急。并且公司还在开源节流,精简服务器。这个我的项目也就过年这段时间跑跑的,过后就是废除状态。综合种种,于是提出试试小程序的云开发。

小程序云开发劣势

无需搭建服务器,疾速构建小程序,免登录、免鉴权调用微信凋谢服务,按量计费, 还有内容治理(CMS), 小我的项目用云开发在适宜不过了。

这个我的项目除了失常的展现外,还用到以下性能

  1. 动态网站 H5 跳小程序任意页面
  2. 客服音讯主动回复
  3. 订阅音讯推送

以上联合小程序云开发不必后盾参加进来,前端也能很容易的实现起来。

先看看大家比较关心的费用问题

右边是费用,左边是拜访人数,
能够看到每天大略 800-1000 人数的拜访,费用也就几分钱,这还是在开明了内容治理(CMS)状况下的数据。所以对于费用这一块齐全能够打消这个顾虑

动态网站 H5 跳小程序任意页面

老规矩先看文档 https://developers.weixin.qq.com/miniprogram/dev/wxcloud/guide/staticstorage/jump-miniprogram.html
能力
能够在微信外部浏览器的 H5 跳转小程序,也能够在微信内部浏览器或其余局部 App(如企业微信、QQ 等)跳转微信小程序。
依据文档我这里改成了能够跳首页以及任意详情页面

H5 页面
<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('产生谬误' + e)
    }
  </script>
  <!-- weui 款式 -->
  <link rel="stylesheet" href="https://res.wx.qq.com/open/libs/weui/2.4.1/weui.min.css">
  </link>
  <!-- 调试用的挪动端 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>
  <!-- 云开发 Web SDK -->
  <script src="https://res.wx.qq.com/open/js/cloudbase/1.1.0/cloud.js"></script>
  <script>
    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);
    }
    let id = getQueryVariable('id') || ''
    function docReady(fn) {if (document.readyState === 'complete' || document.readyState === 'interactive') {fn()
      } else {document.addEventListener('DOMContentLoaded', fn);
      }
    }

    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) {var containerEl = document.getElementById('wechat-web-container')
        containerEl.classList.remove('hidden')
        containerEl.classList.add('full', 'wechat-web-container')
        var dom = document.getElementById('wxOpenInAPP') 
        let path ='/pages/index/index';
        if(id){path = '/pages/detail/index?id='+id}
        console.log('path',path)
        dom.innerHTML = '<wx-open-launch-weapp id="launch-btn"username="gh_adf5777ca9be"path="'+path+'"><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>'
   
        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, // 调试时可开启
          appId: '你的 appId', // <!-- replace -->
          timestamp: 0, // 必填,填任意数字即可
          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 -->
          // 资源方环境 ID
          resourceEnv: '你的环境 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',
          id: id
        },
      })
      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 -->
      <!-- 跳转小程序的凋谢标签。文档 https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_Open_Tag.html -->
      <div id="wxOpenInAPP" class="wexin-launch-btn">
      </div>
    </div>
    <div id="desktop-web-container" class="hidden">
      <p class=""> 请在手机关上网页链接 </p>
    </div>
  </div>
</body>

</html>
云函数
// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({env: 'id'})

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

  switch (event.action) {
    case 'getUrlScheme': {return getUrlScheme(event)
    }
  }

  return 'action not found'
}

async function getUrlScheme(event) {
  let path = '/pages/index/index'
  let query = ''
  if (event.id) {
    path = '/pages/detail/index'
    query = 'id=' + event.id
  }
  return cloud.openapi.urlscheme.generate({
    jumpWxa: {
      path: path, // <!-- replace -->
      query: query,
    },
    // 如果想不过期则置为 false,并能够存到数据库
    isExpire: false,
    // 一分钟有效期
    expireTime: parseInt(Date.now() / 1000 + 60),
  })
}

把云函数部署下来,动态 H5 页面上传到云开发的动态网站里

网站配置 里找到域名,就能够 H5 跳小程序了。

成果预览

这里放个官网的栗子
https://postpay-2g5hm2oxbbb721a4-1258211818.tcloudbaseapp.com/jump-mp.html

其余的下期再来肝

换工作?找面试题?来前端面试题库 wx 搜寻 进阶的大前端

退出移动版