微信内H5 跳转小程序方法详解(laravel/php)

Song1991 次浏览0个评论2021年03月17日

一、必备条件:

  • 在微信内打开H5页面、其他浏览器可查看 静态网站 H5 跳小程序

  • 已认证的服务号注意服务号必须是已认证的,我因为这问题调试几个小时[无语]

  • 服务号绑定“JS接口安全域名”下的网页可使用此标签跳转任意合法合规的小程序;

  • 已认证的非个人主体的小程序云开发也可以查看 静态网站 H5 跳小程序

二、绑定安全域名

登录微信公众平台,进入公众号设置 -> 功能设置里设置js接口安全域名

js接口安全域名

三、IP白名单设置

登录微信公众平台,进入开发 -> 基本配置,在IP白名单内填写你服务器的IP。

四、PHP后端代码

其实使用Laravel/Guzzle使用只需10几行代码就能搞定,但是为了方便大家查看所以使用PHP


<?php

public function wechatApp()
{
    // 微信 JS 接口签名校验工具: https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=jsapisign
    $appid = 'AppID'; //填入服务号AppID
    $secret = 'AppSecret'; //填入服务号AppSecret

    // 获取access_token,注意使用过程中获取到access_token后保存起来,access_token有效期为2小时;多次调研access_token会报错
    $token_res = curlRequests("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}");
    $access_token = $token_res['access_token'];

    // 获取ticket
    $ticket_res = curlRequests("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$access_token}&type=jsapi");
    $ticket = $ticket_res['ticket'];

    // 时间戳
    $timestamp = time();
    // nonceStr为16位随机数即可
    $nonceStr = createNonceStr();
    // URL为调用JSSDK的页面地址,后面有参数也需要放进去
    $url = "https://host.com/test?id=1"; // 调用JSSDK的页面地址
    // sha1加密
    $str = "jsapi_ticket={$ticket}&noncestr={$nonceStr}&timestamp={$timestamp}&url={$url}";
    $sha_str = sha1($str);
    return ["appid"=>$appid,"timestamp"=>$timestamp,"nonceStr"=>$nonceStr,"signature"=>$signature]
}

function createNonceStr($length = 16)
{
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    $str = "";
    for ($i = 0; $i < $length; $i++) {
        $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
    }
    return $str;
}

function curlRequests($url, $data = null)
{
    // curl 初始化
    $curl = curl_init();
    // curl 设置
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    // 判断 $data get  or post
    if (!empty($data)) {
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    // 执行
    $res = curl_exec($curl);
    curl_close($curl);
    return json_decode($res, true);
}

五、H5前端代码

wx-open-launch-weapp内的usernamepath改为您的小程序原始号和path即可。

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name = "viewport" content = "width = device-width, initial-scale = 1.0, maximum-scale = 1.0, user-scalable = 0" />
    <title>微信浏览器跳转小程序</title>
    <style>
        .notice-msg{
            width: 100%;
            float: left;
            line-height: 30px;
            text-align: center;
            margin: 200px 0px 20px 0px;
            padding: 0px 15px;
            box-sizing: border-box;
            color: #666666;
            font-size: 15px;
        }
    </style>
    <link rel="stylesheet" href="https://res.wx.qq.com/open/libs/weui/2.4.1/weui.min.css"></link>
</head>
<body>
    <p class="notice-msg">点击下方按钮立即跳转小程序</p>
    <wx-open-launch-weapp id="launch-btn" username="gh_***" path="/pages/index/index" style="width: 100%;float: left;">
        <template>
            <div style="width: 250px; height: 50px; line-height: 50px; text-align: center; font-size: 15px; display: block; margin: 0 auto; border: none; border-radius: 4px; background-color: #07c160; color:#FFFFFF;">点击立即跳转小程序</div>
        </template>
    </wx-open-launch-weapp>

    <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<script>

    $(function () {
        wx.config({
            debug: false,
            appId: '<? echo $appid ?>', // 必填,公众号的唯一标识
            timestamp: '<? echo $timestamp ?>', // 必填,生成签名的时间戳
            nonceStr: '<? echo $nonceStr ?>', // 必填,生成签名的随机串
            signature: '<? echo $signature ?>',// 必填,签名
            jsApiList: ["chooseImage"],//必须要不调用小程序标签渲染不出来
            openTagList: ['wx-open-launch-weapp']//必须必须要不调用小程序标签渲染不出来
        });
        wx.ready(function () {
            console.log("ready");
        });

        wx.error(function (res) {
            console.log("res", res);
        });        

        var btn = document.getElementById('launch-btn');
        btn.addEventListener('launch', function (e) {
            console.log('success');
        });
        btn.addEventListener('error', function (e) {
            console.log('fail', e.detail);
        });
    });

</script>
</body>
</html>

文档地址:JS-SDK说明文档

更多相关好文

    当前暂无更多相关好文推荐...