關於微信分享自定義標題,說明,圖示基於PHP的功能實現

点碎的阳光發表於2024-10-17

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() {
                   // 分享成功的回撥
               }
           }; 
        // 呼叫分享設定函式
        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>

相關文章