返回
微信公众号跳转小程序
开发工具
2023-10-16 04:09:36
微信公众号跳转小程序,详细教程
准备工作
- 拥有一个微信公众号
- 拥有一个小程序
前端H5代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
</head>
<body>
<button id="jump">跳转小程序</button>
<script>
wx.config({
debug: false,
appId: '你的小程序AppId',
timestamp: timestamp,
nonceStr: nonceStr,
signature: signature
});
wx.ready(function () {
document.getElementById('jump').addEventListener('click', function () {
wx.miniProgram.navigateTo({
appId: '你的小程序AppId',
path: '页面路径',
extraData: {
foo: 'bar'
},
success(res) {
// 跳转成功
},
fail(err) {
// 跳转失败
}
});
});
});
</script>
</body>
</html>
后端PHP代码
<?php
// 获取微信公众号配置参数
$appid = '你的微信公众号AppId';
$secret = '你的微信公众号AppSecret';
// 获取access_token
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
$access_token = json_decode(file_get_contents($url), true)['access_token'];
// 获取跳转小程序所需参数
$url = "https://api.weixin.qq.com/cgi-bin/component/jsapi_ticket?access_token={$access_token}";
$ticket = json_decode(file_get_contents($url), true)['ticket'];
// 获取当前时间戳和随机字符串
$timestamp = time();
$nonceStr = uniqid();
// 生成签名
$string = "jsapi_ticket={$ticket}&noncestr={$nonceStr}×tamp={$timestamp}&url={$_SERVER['REQUEST_URI']}";
$signature = sha1($string);
// 返回给前端H5页面
echo json_encode([
'appId' => $appid,
'timestamp' => $timestamp,
'nonceStr' => $nonceStr,
'signature' => $signature
]);
使用方法
- 将前端H5代码保存为HTML文件,并将其上传到你的服务器。
- 将后端PHP代码保存为PHP文件,并将其上传到你的服务器。
- 在微信公众号中,将你的服务器地址设置为“业务域名”。
- 在微信公众号中,创建自定义菜单,并添加一个“跳转小程序”的菜单项。
- 在“跳转小程序”的菜单项中,填写你的H5页面的URL地址。
- 保存并发布菜单。
现在,当用户在微信公众号中点击“跳转小程序”的菜单项时,就会跳转到你的H5页面。在H5页面中,点击“跳转小程序”按钮,即可跳转到你的小程序。