微信公众号跳转uniapp开发的app

最近公司做了一个app,功能挺简单就是发布内容可以给别人阅读查看。这个app用uniapp开发的,要求可以分享某篇文章到微信里,并且别人可以从微信打开直接跳到app的这个文章页面。

方案

使用微信官方的公众号跳转app功能

准备工作

  1. 一个认证过的服务号
  2. 微信开放平台创建好的应用(这一块也遇到了不少坑)

步骤

  1. 在微信开放平台------管理中心------公众号,绑定认证过的公众号,并且编辑跳转到的应用
  2. 在微信公众号管理后台,查看是否已经关联应用。进入设置与开发------功能设置,配置业务域名,js接口安全域名,网页授权域名。第二个应该不需要,不过为了以后方便不如一块配置好。

代码部分

  1. uniapp配置里的微信分享,填上微信开放平台里app的appId
  1. 在分享的页面里配置要跳转的页面地址(包含了生成微信accessToken的逻辑)
javascript 复制代码
//分享到好友
shareFunc(){
        let params = this.params.type+'/'+this.params.id;
        const that = this;
        uni.share({
                provider: "weixin",
                scene: "WXSceneSession",
                type: 0,
                title:this.params.title,
                imageUrl:this.params.img,
                href:'https://www.51facai.com/toapp.php?params='+params,
                summary:this.params.desc,
                success: function (res) {
                        that.$refs.popup.close()
                },
                fail: function (err) {
                        that.$refs.popup.close();
                }
        });
},
//分享给朋友圈
sharesFunc(){
        uni.share({
                provider: "weixin",
                scene: "WXSceneTimeline",
                type: 0,
                title:this.params.title,
                imageUrl:this.params.img,
                href:'https://www.51facai.com/toapp.php?params='+JSON.stringify(params),
                summary:this.params.desc,
                success: function (res) {
                        console.log("success:" + JSON.stringify(res));
                },
                fail: function (err) {
                        console.log("fail:" + JSON.stringify(err));
                }
        });
},
  1. 设置公众号中间页,以php举例
php 复制代码
<?php

// 微信 JS 接口签名校验工具: https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=jsapisign
$appid = '1111111111111';
$secret = '222222222222222';


// 获取token
$token_data = file_get_contents('./wechat_token.txt');
if (!empty($token_data)) {
    $token_data = json_decode($token_data, true);
}

$time  = time() - $token_data['time'];
if ($time > 3600) {
    $token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
    $token_res = https_request($token_url);
    $token_res = json_decode($token_res, true);
    $token = $token_res['access_token'];

    $data = array(
        'time' =>time(),
        'token' =>$token
    );
    $res = file_put_contents('./wechat_token.txt', json_encode($data));
    if ($res) {
        echo '更新 token 成功';
    }
} else {
    $token = $token_data['token'];
}


// 获取ticket
$ticket_data = file_get_contents('./wechat_ticket.txt');
if (!empty($ticket_data)) {
    $ticket_data = json_decode($ticket_data, true);
}

$time  = time() - $ticket_data['time'];
if ($time > 3600) {
    $ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$token}&type=jsapi";
    $ticket_res = https_request($ticket_url);
    $ticket_res = json_decode($ticket_res, true);
    $ticket = $ticket_res['ticket'];

    $data = array(
        'time'    =>time(),
        'ticket'  =>$ticket
    );
    $res = file_put_contents('./wechat_ticket.txt', json_encode($data));
    if ($res) {
        echo '更新 ticket 成功';
    }
} else {
    $ticket = $ticket_data['ticket'];
}


// 进行sha1签名
$timestamp = time();
$nonceStr = createNonceStr();

// 注意 URL 建议动态获取(也可以写死).
$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https://' : 'http://'; 
$url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; // 调用JSSDK的页面地址
// $url = $_SERVER['HTTP_REFERER']; // 前后端分离的, 获取请求地址(此值不准确时可以通过其他方式解决)

$str = "jsapi_ticket={$ticket}&noncestr={$nonceStr}&timestamp={$timestamp}&url={$url}";
$sha_str = sha1($str);


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;
}


/**
 * 模拟 http 请求
 * @param  String $url  请求网址
 * @param  Array  $data 数据
 */
function https_request($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 $res;
}

?>




<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, maximum-scale=1.0, minimum-scale=1.0">

  <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<style>
    body{
        display: flex;
        flex-direction: column;
        align-items: center;
        color: #999;
        padding: 200px 30px; 
    } 
    img{
        width: 100px;
        height: 100px;
    }
    .to-app{
        width: 100%;
        position: fixed;
        bottom: 0;
        height: 70px;
        background-color: #fff;
        box-shadow: 0 -1px 5px 0 rgba(0,0,0,0.1);
        display: flex;
        align-items: center; 
        margin-bottom:20px;
    }
    .to-app img{
        width: 50px;
        height: 50px;
        margin-right: 20px;
        margin-left: 20px;
    }
    .to-app button{
        background-color: #fff;
        border: 2px solid blueviolet;
        color:blueviolet;
        font-weight: 600;
        border-radius: 6px;
        padding: 4px 20px;
        margin-left: auto;
        margin-right: 20px;
        cursor: pointer;
    }
</style>
<script type="text/javascript" src="https://res2.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
<body> 
<img src="./logo.png"/>
        <h2>大佬基地</h2>
        <p>
            大佬基地是一款专注于IT行业的社交应用
        </p>
        <p>
            通过大佬基地资讯共享、参与活动可以结识更多的好友
        </p> 
        <div class="to-app"> 
            <img src="./logo.png"/>
            <span>大佬基地</span>
            <wx-open-launch-app
  id="launch-btn"
  appid="3333333333333333"
  extinfo="<?php echo $_GET['params'] ?>"
  style="margin-left: auto;
        margin-right: 20px;"
>

  <script type="text/wxtag-template"> 
    <style>
    button{
        background-color: #fff;
        border: 2px solid blueviolet;
        color:blueviolet;
        font-weight: 600;
        border-radius: 6px;
        padding: 6px 20px; 
        cursor: pointer;
    }
</style>
    <button>打开</button>
  </script>
</wx-open-launch-app>
           
        </div>  
  
<script>
 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>
    <script type="text/javascript">
        wx.config({
            debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
            appId: '<? echo $appid ?>', // 必填,公众号的唯一标识
            timestamp: <? echo $timestamp ?>, // 必填,生成签名的时间戳
                nonceStr: '<? echo $nonceStr ?>', // 必填,生成签名的随机串
                signature: '<? echo $sha_str ?>',// 必填,签名
            jsApiList: ['onMenuShareAppMessage'], // 必填,需要使用的JS接口列表
            openTagList: ['wx-open-launch-app'] // 可选,需要使用的开放标签列表
        });
        wx.ready(function(){
            console.log('接口配置成功');
        });
        function test(){
            console.log('ok啦');
            wx.scanQRCode({
                needResult: 1, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果,
                scanType: ["qrCode","barCode"], // 可以指定扫二维码还是一维码,默认二者都有
                success: function (res) {
                    var result = res.resultStr; // 当needResult 为 1 时,扫码返回的结果
                    console.log(result);
                }
            });
        }
  </script>
</body>
</html>

遇到的问题

  1. noPermission。。。什么什么的
    原因:没在公众号里开通跳转应用
  2. 华为手机上报毒不跳转,在模拟器上是可以跳的
    原因不晓得,更换包名就可以了,猜测是跟其它的包名相似了
相关推荐
Fan_web13 分钟前
jQuery——事件委托
开发语言·前端·javascript·css·jquery
安冬的码畜日常15 分钟前
【CSS in Depth 2 精译_044】第七章 响应式设计概述
前端·css·css3·html5·响应式设计·响应式
莹雨潇潇1 小时前
Docker 快速入门(Ubuntu版)
java·前端·docker·容器
Jiaberrr1 小时前
Element UI教程:如何将Radio单选框的圆框改为方框
前端·javascript·vue.js·ui·elementui
Tiffany_Ho2 小时前
【TypeScript】知识点梳理(三)
前端·typescript
安冬的码畜日常3 小时前
【D3.js in Action 3 精译_029】3.5 给 D3 条形图加注图表标签(上)
开发语言·前端·javascript·信息可视化·数据可视化·d3.js
小白学习日记4 小时前
【复习】HTML常用标签<table>
前端·html
丁总学Java4 小时前
微信小程序-npm支持-如何使用npm包
前端·微信小程序·npm·node.js
yanlele4 小时前
前瞻 - 盘点 ES2025 已经定稿的语法规范
前端·javascript·代码规范