美文网首页
微信外部网页按钮点击跳转至小程序

微信外部网页按钮点击跳转至小程序

作者: 量U移动广告归因 | 来源:发表于2021-06-19 22:59 被阅读0次
  • 上一篇介绍了微信内部页面按钮跳转至小程序,这一篇介绍在微信外部第三方浏览器打开的网页按钮怎么跳转到小程序
    官方的文档连接
主要原理是生成一个伪协议的小程序跳转链接,然后设置到<a>标签的 href 属性上,点击就能跳转过去了
<a href="weixin://dl/business/?t=xxxxxxxxxxx">点击跳转</a>
请求微信接口生成小程序链接
/**
 * @param string $appid     小程序AppID
 * @param string $appsecret 小程序AppSecret
 * @param string $path      小程序跳转路径 默认跳转到首页
 * @throws Exception
 * @return mixed
 */
function get_mini_link($appid,$appsecret,$path = 'pages/index/index'){
    //请求 access_token
    $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appsecret;
    $data = file_get_contents($url);
    $datas = json_decode($data, true);
    $access_token = $datas['access_token'];
    if(empty($access_token)){
        throw new Exception('access_token为空');
    }
    //请求小程序码
    $url = "https://api.weixin.qq.com/wxa/generatescheme?access_token=" . $access_token;
    //更多请求参数可以参考微信文档
    $post_data = [
        'jump_wxa' => [
                'path' => $path,    //跳转至小程序的页面
                'query' => ''       //跳转时携带的query参数,可以填写渠道号之类的标识来源
         ],
        'is_expire' => false        //false 永久有效  / true 到期失效
    ];
    $post_data = json_encode($post_data);
    //发送post请求
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    $result = curl_exec($ch);
    curl_close($ch);
    if(!empty($result)){
        $res = json_decode($result,true);
        if(isset($res['openlink']) && !empty($res['openlink'])){
            return $res['openlink'];
        }
    }
    throw new Exception('请求小程序失败');
}
//调用函数
$openlink = get_mini_link('wxxxxx', 'xxxxxxxxxxx');

将该openlink的值填写到页面<a>标签的 href 属性即可实现点击跳转

Tips

微信内部跳转的方法只能运用在微信内部,微信外部的跳转方法也只能运用在微信外部,如果都想实现跳转,可以将两种方法聚合,判断环境来调用不同的跳转代码即可

相关文章

网友评论

      本文标题:微信外部网页按钮点击跳转至小程序

      本文链接:https://www.haomeiwen.com/subject/pdqdyltx.html