微信公众号H5跳转小程序

1,122 阅读1分钟

1.下载微信的sdk包  我这里使用npm下载,相信大家不陌生  npm i weixin-js-sdk

2.引入sdk包,我这里选择局部引入,因为只有一个页面需使用,大家根据实际开发情况引入

const wx = require('weixin-js-sdk');

准备工作总算完成啦!接下来到了关键步骤

3.配置sdk,在method钩子函数中写一个wxConfig方法,向后端请求需携带url参数获取对应的配置信息,如下代码

wxConfig() {
    console.log(wx) // 打印wx对象
    let paramData = {url: window.location.href.split("#")[0]}
    this.$ajax.post("/api/jssdk", paramData).then(res => {
    	if(res.code == 0) {
    		console.log('-------------------jssdk--------------')
    		console.log(res)
    		wx.config({
    			debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
    			appId: res.data.appId, // 必填,公众号的唯一标识
    			timestamp: res.data.timestamp, // 必填,生成签名的时间戳
    			nonceStr: res.data.nonceStr, // 必填,生成签名的随机串
    			signature: res.data.signature, // 必填,签名
    			jsApiList: ['onMenuShareAppMessage'], // 必填,需要使用的JS接口列表
    			openTagList: ['wx-open-launch-weapp'] // 可选,需要使用的开放标签列表,例如['wx-open-launch-app']
    		})
    	} else {
    		uni.showToast({
    			title: res.msg,
    			icon: 'none',
    			duration: 3000
    		});
    	}
    }).catch(err => {
    	console.log(err)
    });		
},

4.页面一加载就需要配置sdk,所以在onLoad钩子函数中调用wxConfig这个方法,如下代码

this.wxConfig();

5.在template模板中写上以下代码即可(username:原始appid path:小程序的页面路径, 成功执行回调@launch失败执行回调@error 这两个方法定义在method钩子函数中)

以下代码即可(username:原始appid path:小程序的页面路径 pages前面不需要加反斜杠, 成功执行回调@launch 失败执行回调@error ,)

<wx-open-launch-weapp  id="launch-btn"  username="gh_***"  path="pages/index/index.html"  @error="handleErrorFn"  @launch="handleLaunchFn"  class="kefu-box"> <!-- vue中需要使用script标签代替template插槽 html中使用template --> <script type="text/wxtag-template">   <image src="http://img.puliuwang.com/l_a3.png" mode="scaleToFill"></image> </script></wx-open-launch-weapp>