关于微信分享自定义标题,说明,图标基于PHP的功能实现

1.首先先从微信公众平台获取AppIdAppSecret。不会的自行查询。

比如要访问的服务器目录是www.xxxx.com。那么在这个目录下可以创建一个目录WeChat,在WeChat下分别创建文件access_token.json、config.php、jsapi_ticket.json、weChatShare.js。

2.access_token.jsonjsapi_ticket.json为空文件就行,里面不要放任何东西,用来存获取到的内容。

3.config.php文件代码如下

<?php
$appId = "xxxxxxxxxxxx";//替换为你的公众号appId
$appSecret = "xxxxxxxxxxxxxxxxxxxxxxxxx";//替换为你的公众号appSecret
 
// 文件路径
$tokenFilePath = "accessToken.json";
$ticketFilePath = "jsapi_ticket.json";
 
function getFromServer($url) {
    $response = file_get_contents($url);
    return json_decode($response, true);
}
 
function getAccessToken($appId, $appSecret, $tokenFilePath) {
    if (file_exists($tokenFilePath)) {
        $data = json_decode(file_get_contents($tokenFilePath), true);
        if ($data['expire_time'] > time()) {
            return $data['access_token'];
        }
    }
    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appId&secret=$appSecret";
    $res = getFromServer($url);
    if ($res['access_token']) {
        $data = ['access_token' => $res['access_token'], 'expire_time' => time() + 7000];
        file_put_contents($tokenFilePath, json_encode($data));
        return $res['access_token'];
    }
    return null;
}
 
function getJsApiTicket($accessToken, $ticketFilePath) {
    if (file_exists($ticketFilePath)) {
        $data = json_decode(file_get_contents($ticketFilePath), true);
        if ($data['expire_time'] > time()) {
            return $data['ticket'];
        }
    }
    $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
    $res = getFromServer($url);
    if ($res['ticket']) {
        $data = ['ticket' => $res['ticket'], 'expire_time' => time() + 7000];
        file_put_contents($ticketFilePath, json_encode($data));
        return $res['ticket'];
    }
    return null;
}
 
function generateNonceStr($length = 16) {
    return bin2hex(random_bytes($length / 2));
}
 
function getSignature($ticket, $nonceStr, $timestamp, $url) {
    $string = "jsapi_ticket=$ticket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
    return sha1($string);
}
 
// 主逻辑
$accessToken = getAccessToken($appId, $appSecret, $tokenFilePath);
$ticket = getJsApiTicket($accessToken, $ticketFilePath);
$nonceStr = generateNonceStr();
$timestamp = time();
$url = $_GET['url'] ?? 'https://www.wechat.com/404/';//替换为你的引导页面,自动获取url失败时显示此链接,建议设置为引导页
 
$signature = getSignature($ticket, $nonceStr, $timestamp, $url);
 
// 返回配置信息给前端
header('Content-Type: application/json');
echo json_encode([
    'appId' => $appId,
    'timestamp' => $timestamp,
    'noncestr' => $nonceStr,
    'signature' => $signature,
    'url' => $url
]);
?>

4.weChatShare.js代码如下:

function setupWeChatShare(shareData) {
    document.addEventListener('DOMContentLoaded', function() {
        var url = window.location.href.split('#')[0];
        fetch(`/weChat/config.php?url=${encodeURIComponent(url)}`) //路径修改
            .then(response => response.json())
            .then(data => {
                wx.config({
                    debug: false,
                    appId: data.appId,
                    timestamp: data.timestamp,
                    nonceStr: data.noncestr,
                    signature: data.signature,
                    jsApiList: [
                        'updateAppMessageShareData',
                        'updateTimelineShareData',
                        'hideMenuItems',
                        'showMenuItems'
                    ]
                });
 shareData
                wx.ready(function() {
                    wx.hideMenuItems({
                        menuList: [
                            'menuItem:copyUrl',
                            'menuItem:share:weiboApp',
                            'menuItem:share:qq',
                            'menuItem:share:QZone',
                            'menuItem:openWithQQBrowser',
                            'menuItem:openWithSafari'
                        ]
                    });
                    wx.showMenuItems({
                        menuList: [
                            'menuItem:addContact',
                            'menuItem:profile'
                        ]
                    });
 
                    // 使用传入的shareData设置分享信息
                    wx.updateAppMessageShareData(shareData);
                    wx.updateTimelineShareData(shareData);
 
                    document.getElementById('closeWechatBtn').onclick = function() {
                        wx.closeWindow();
                    };
                });
            });
    });
}

5.比如在www.xxx.com的目录下有index.html,要想实现在微信内分享这个网页时出现自定义的内容。

5.1 index.html内容如下:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
        <title>XX</title>
        
        <link rel="stylesheet" href="./css/weuix.css">
        <link rel="bookmark" href="./img/favicon.ico" type="image/x-icon" />
        <link rel="stylesheet" href="css/foundation.css">
        <!--<link rel="stylesheet" href="css/app.css">-->
        <script src="https://hmoob.sweet20.top/zepto.min.js"></script>
        <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
        <script src="./../weChat/weChatShare.js"></script> <!--微信分享-->
    </head>
    <body>
         <script>
        // 定义分享数据
           var shareData = {
               title: '苗语基础语法拼读',
               desc: '苗语语法、读法、写法全面详细的拼读方式,点击即可听读音,让学习更简单。',
               link: window.location.href,
               imgUrl: 'https://image.sweet20.top/logo/hmoob1.png',
               success: function() {
                   console.log('分享成功')// 分享成功的回调
               }
cancel:function(){
console.log('分享失败')// 分享成功的回调
}
           }; 
        // 调用分享设置函数
        setupWeChatShare(shareData);
      </script>
     <!---下面这里就是网页的内容-->
    </body>
</html>

上面其中这两个是必须引用的,<script></script>中的内容就是你网页分享时想自定义的内容。

<script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
 <script src="./../weChat/weChatShare.js"></script> <!--微信分享-->
 <script>
        // 定义分享数据
           var shareData = {
               title: '苗语基础语法拼读',
               desc: '苗语语法、读法、写法全面详细的拼读方式,点击即可听读音,让学习更简单。',
               link: window.location.href,
               imgUrl: 'https://image.sweet20.top/logo/hmoob1.png',
               success: function() {
                   // 分享成功的回调
               }
           }; 
        // 调用分享设置函数
        setupWeChatShare(shareData);
      </script>

 

 

 

 

 

 

 

 

 

posted @ 2024-10-17 17:21  点碎的阳光  阅读(59)  评论(0编辑  收藏  举报