- 需要准备的工具和材料:微信开发者工具、非个人主体并且已认证的(微信认证)小程序
- 第一步:开通云开发
- 微信开发者工具——云开发 ,根据指引开通云开发
- 开通成功后,点概览页,右侧生成一个环境id,后面H5页会用到
c.设置云开发权限:云开发控制台——设置——权限设置,打开“未登录用户访问权限”
- 第二步:配置H5静态网页:
- 进入云开发控制台点——更多——静态网站,开通静态网站
- 改写H5静态页index.html,如下图所示,静态页的内容参考文档https://developers.weixin.qq.com/miniprogram/dev/wxcloud/guide/staticstorage/jump-miniprogram.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('发生错误' + 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 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 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) { console.log('点击成功liftCode',liftCode); var c = window.c const res = await c.callFunction({ name: 'public', data: { action: 'getUrlScheme', query:'liftCode=' + liftCode //配置链接参数 }, }) // console.warn(res) if (onBeforeJump) { onBeforeJump() } location.href = res.result.openlink } //获取链接参数值 let liftCode = ''; function getQueryString(name){ let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)') console.log('reg=',reg); let r = window.location.search.substr(1).match(reg); console.log('r=',r); if(r != null){ return unescape(r[2]) } return null } liftCode = getQueryString('liftCode') </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 --> <wx-open-launch-weapp id="launch-btn" username="小程序原始账号 ID(gh_ 开头的)" path="要跳转到的页面路径"> <!-- 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="">请在手机打开网页链接</p> </div> </div> </body> </html>
3.上传H5静态页
- 第二步:上传云函数
说明:若小程序已经是使用云开发服务,就可直接使用云函数了;若不是,需要创建云开发小程序用来上传云函数
- 创建云开发小程序,如图所示
- 云开发小程序开发成功后,可以看到cloudfunctions和miniprogram两个目录,其中我们需要cloudfunctions目录来创建和上传云函数
a.设置云开发环境:鼠标右键点击cloundfunctions目录,设置当前环境
b.创建云函数,官方云函数示例代码下载:https://res.wx.qq.com/op_res/4gUvxyfsT9OaDBWFG_jP-xtGK84CoO_4rQXZpaJhyje-vy3amU1xLctcpyqfyn3D5rgCRBR3EpR5sLO_WSP8eQ
c.将下载后的cloundfunctions目录中的public文件夹复制到云开发小程序cloundfunctions目录下
- 编辑public/index.js文件,将getUrlScheme函数中的path替换成要调取小程序的页面路径
// 云函数入口文件 const cloud = require('wx-server-sdk') cloud.init() // 云函数入口函数 exports.main = async (event, context) => { const wxContext = cloud.getWXContext() switch (event.action) { case 'getUrlScheme': { return getUrlScheme(event.query) } } return 'action not found' } async function getUrlScheme(query) { console.log('云函数接收参数 query:',query); return cloud.openapi.urlscheme.generate({ jumpWxa: { path: 'pages/index/main', // <!-- replace --> query: query,//参数 }, // 如果想不过期则置为 false,并可以存到数据库 isExpire: false, // 一分钟有效期 expireTime: parseInt(Date.now() / 1000 + 60), }) }
- 按照依赖:右击public目录,选择“载内建终端中打开”,然后输入nmp install命令并执行
- 上传部署云函数:右击pubic目录选择“上传并部署:云端安装依赖(不上传node_modules)”,部署后,打开云开发控制台——云函数,就可以看到部署的云函数了
- 修改云函数权限:云开发控制台——云开发——云开发权限,自定义安全规则,点击右侧的修改
第四步:获取微信短信链接
String urlLink = "https://api.weixin.qq.com/wxa/generate_urllink?access_token=" + accessToken; Map<String,String> map = new HashMap<String,String>(); HttpClientResult result = HttpClientUtils.doJSONPost(urlLink, JSON.toJSONString(map)); Map<String, Object> content = result.getMapBody(); JSONObject jsonObject = JSONObject.parseObject(result.getContent()); String url_link = jsonObject.get("url_link").toString(); String errcode = jsonObject.get("errcode").toString(); String errmsg = jsonObject.get("errmsg").toString();
第五步:配置短链接参数
1.短链接参数:
// 需传的参数 name=weChat,age=18
const cqValue = encodeURIComponent('name=weChat&age=18') // name%3DweChat%26age%3D18
https://wxaurl.cn/*TICKET*?cq=name%3DweChat%26age%3D18
2.小程序页获取参数
// 取参
onLoad(options) {
const { name, age } = options
console.log('name >>>>>>>>', name)
console.log('age >>>>>>>>', age)
}
第六步:开通阿里云短信服务,并申请相应的短信模板,具体参考阿里云官网文档:https://help.aliyun.com/zh/sms/?spm=a2c4g.11186623.0.0.77b941eduYcWPA
第七步:测试验证