公司需要通过发送短信携带短链接,用户点击短链接跳转到小程序的某个页面,然后打开小程序该页面webviewh5页面,然后链接携带参数。
主要是用小程序的云开发,相关文档在这里:
云开发文档
1,用户点击短链接跳转小程序
之后就打开小程序了
就是这样一个过程
<template> <div class='open-mini-wrapper'> <div class="page full"> <div id="public-web-container" class="hidden"> <p class="">正在打开 “小程序”...</p> <a id="public-web-jump-button" href="javascript:" @click="openWeapp"> <van-button type='primary'>打开小程序</van-button> </a> </div> <div id="wechat-web-container" class="hidden" > <p class="">点击以下按钮打开 “小程序”</p> <wx-open-launch-weapp id="launch-btn" :username="originId" :path="path"> <script type="text/wxtag-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> </script> </wx-open-launch-weapp> </div> <div id="desktop-web-container" class="hidden"> <p class="">请在手机打开网页链接</p> </div> </div> </div> </template> <script> import {getQueryObject} from "@/utils"; export default { name: "OpenMini", data() { return { xxx: '', // 需要传的参数 path: '', // 跳转至小程序的路径 originId: '',//小程序原始ID resourceAppid: '', //小程序appid resourceEnv: '' //小程序云环境id } }, created() { this.xxx = getQueryObject().xxx const url = `https://xxx?xxx=${this.xxx}` this.path = 'pages/h5/h5?url=' + encodeURIComponent(url) this.$getWeChatParams(this.xxx, window.location.href); // 微信开发功能的配置方法,见底部 }, mounted() { this.init() }, methods: { // 准备 docReady(fn) { if (document.readyState === 'complete' || document.readyState === 'interactive') { fn() } else { document.addEventListener('DOMContentLoaded', fn); } }, init() { this.docReady(async () => { let ua = navigator.userAgent.toLowerCase() let isWXWork = ua.match(/wxwork/i) == 'wxwork' let isWeixin = !isWXWork && ua.match(/MicroMessenger/i) == 'micromessenger' // let isMobile = false let isDesktop = false if (navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|IEMobile)/i)) { // isMobile = true } else { isDesktop = true } if (isWeixin) { let containerEl = document.getElementById('wechat-web-container') containerEl.classList.remove('hidden') containerEl.classList.add('full', 'wechat-web-container') let 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) }) } else if (isDesktop) { // 在 pc 上则给提示引导到手机端打开 let containerEl = document.getElementById('desktop-web-container') containerEl.classList.remove('hidden') containerEl.classList.add('full', 'desktop-web-container') } else { let containerEl = document.getElementById('public-web-container') containerEl.classList.remove('hidden') containerEl.classList.add('full', 'public-web-container') let c = new cloud.Cloud({ // 必填,表示是未登录模式 identityless: true, // 资源方 AppID resourceAppid: this.resourceAppid, // 资源方环境 ID resourceEnv: this.resourceEnv, }) await c.init() window.c = c await this.openWeapp() } }) }, async openWeapp() { let c = window.c const res = await c.callFunction({ name: 'public', data: { action: 'getUrlScheme', option: { xxx: this.xxx, } }, }) location.href = res.result.openlink } } } </script> <style scoped lang='scss'> .open-mini-wrapper { .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>
上面代码就是打开小程序的代码,但是此时还没有效果,需要配置云函数功能
需要先在小程序后台开通云开发服务,此时会分配一个云环境cloudID
打开小程序开发者工具-》点击云开发,开通静态网站功能
在云开发控制台点击设置,
然后点击云函数配置自定义安全规则
public为云函数名字,规则如下
{ "*": { "invoke": "auth != null" }, "public": { "invoke": true } }
此时缺少云函数需要在代码新建云函数
新增文件夹起名叫cloud
再project.config.josn文件里增加配置
“cloudbaseRoot”: “cloud/”,
新增云函数起名public,然后同步云函数到服务器(微信小程序自己)
云函数index.js里代码写
// 云函数入口文件 const cloud = require('wx-server-sdk') cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境 // 云函数入口函数 exports.main = async (event, context) => { const wxContext = cloud.getWXContext() switch (event.action) { case 'getUrlScheme': { return getUrlScheme(event.option) } } return { event } } async function getUrlScheme(option) { let query = 'xxx=' + option.xxx + '&from=yunhanshu' // 需要携带的参数 const result = await cloud.openapi.urlscheme.generate({ jumpWxa: { path: 'pages/h5/h5', // <!-- replace --> query: query }, // 如果想不过期则置为 false,并可以存到数据库 isExpire: false, // 一分钟有效期 expireTime: parseInt(Date.now() / 1000 + 60), }) return { ...result, query } }
然后同步云函数
此时云函数部门已经开发完毕,剩下的是跳转到小程序指定页面路径,后的代码
h5.wxml部分很简单因为webview
<web-view class="lazyload" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-original="{{url}}"></web-view>
h5.js 只需要接受参数就可以了
// pages/webview/h5.js const { getOpenId, } = require('../../utils/userUtils') Page({ data: { url:'' }, onLoad(options) { // console.log(options, 'optionsaaa') if(options.from && options.from === 'yunhanshu') { const url = `https://xxx/#/?xxx=${options.xxx}` this.setData({ url: url }) }else { this.setData({ url:decodeURIComponent(options.url) }) } } })
该函数需要调后端接口配合使用,主要是获取signature等参数信息,网上有很多,自行搜索
const getWeChatParams = async function (agentID, path, isHidden = false) { if (agentID) { let result = await wxticket({agentID, path}) if (result.code === S_OK) { if (isHidden) { getHiddenWeChatShare(result.data) } else { getWeChatShare(result.data) } } } } const getWeChatShare = function (params) { let title = shareTitle; let desc = shareDesc weChat.config({ debug: false, appId: appId, timestamp: params.timestamp, nonceStr: params.nonceStr, signature: params.signature, jsApiList: ['hideMenuItems', 'onMenuShareAppMessage', 'onMenuShareTimeline'], openTagList:['wx-open-launch-weapp'], // 填入打开小程序的开放标签名 }); weChat.ready(function () { // 批量隐藏菜单项 weChat.hideMenuItems({ menuList: [ 'menuItem:readMode', // 阅读模式 'menuItem:share:qq', 'menuItem:share:weiboApp', 'menuItem:share:facebook', 'menuItem:share:QZone' ] }); // 监听“分享给朋友”,按钮点击、自定义分享内容及分享结果接口 weChat.onMenuShareAppMessage({ title: title, // 分享标题 desc: desc, // 分享描述 link: params.url, // 分享链接 imgUrl: `${urlDomain}/logo.png` // 分享图标 }); //监听“分享到朋友圈”按钮点击、自定义分享内容及分享结果接口 weChat.onMenuShareTimeline({ title: title, // 分享标题 desc: desc, // 分享描述 link: params.url, // 分享链接 imgUrl: `${urlDomain}/logo.png` // 分享图标 }) }); }
至此 整个开发流程就结束了,哈哈,是不是很简单。