写在前面:
微信内置网页实现分享接口权限仅用于微信认证订阅号和服务号使用,个人认证订阅号无法使用,详情请查阅微信公众号开发者文档。
目录结构:
//目录结构
-- weChat //一级目录
-- config.php
-- accessToken.json
-- jsapi_ticket.json
-- js //分装分享接口目录【注:分装目录可以根据自己需求分装基础接口】
-- weChatShare.js
-- Share //分享目录demo
-- shareDemo.html
config.php
<?php
$appId = "******************";//替换为你的公众号appId
$appSecret = "**************";//替换为你的公众号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×tamp=$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
]);
?>
accessToken.json 【创建空文件即可,json格式如下】
{"access_token":"80_lrzI3lpUjcTLokkG8mprUCaM50cLWLPhPonfFf0avY7hijisILsRjHeJrfPNramFboY_LgBf9rn3i_VDkObKwDuxchStrgsVj2Ecn6tmzH97uScW1gdBCBHAdcUWSPiAAAOKH","expire_time":1716123437}
jsapi_ticket.json 【创建空文件即可,json格式如下】
{"ticket":"O3SMpm8bG7kJnF36aXbe8zEUh5yLTcW4HWPKFv2leA1AYiW0GL1VG2vm6YAEpZQDVvw3dIoNoUbOsxTlhvBZFQ","expire_time":1716123437}
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'
]
});
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();
};
});
});
});
}
shareDemo.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>微信内置网页实现分享接口(PHP代码实例)</title>
<meta name="description" content="微信内置网页实现分享接口(PHP代码实例)">
<script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
<script src="./../js/weChatShare.js"></script> //二级目录,js/weChatShare.js根据文件目录不同进行设置
</head>
<body>
<h1>微信内置网页实现分享接口(PHP代码实例)</h1>
<script>
// 定义分享数据
var shareData = {
title: '这是一个自定义分享页面',
desc: '自定义分享描述,若显示,分享成功!',
link: window.location.href,
imgUrl: 'https://res.wx.qq.com/mpres/zh_CN/htmledition/comm_htmledition/images/icon/login/mp_service_new6e7662.png',
success: function() {
// 分享成功的回调
}
};
// 调用分享设置函数
setupWeChatShare(shareData);
</script>
</body>
</html>
以上为完整版分享代码,请在微信公众号内关键字回复打开,请勿直接访问分享页面链接,否则分享失败,请参考微信官方开发文档进行调试。