php实现微信公众号分享朋友和朋友圈

微信公众号中实现分享到朋友和朋友圈的自定义文案功能,通常需要使用微信JS-SDK。微信JS-SDK提供了丰富的接口,可以方便地实现分享功能。以下是详细的步骤和代码示例:

步骤概述

  1. 引入微信JS-SDK
  2. 配置JS接口安全域名
  3. 获取access_token
  4. 获取jsapi_ticket
  5. 生成签名
  6. 配置JS-SDK
  7. 实现分享功能

详细步骤

1. 引入微信JS-SDK

在HTML文件中引入微信JS-SDK。

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>微信分享示例</title>
    <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
</head>
<body>
    <!-- 页面内容 -->
</body>
</html>

2. 配置JS接口安全域名

在微信公众平台的“开发” -> “基本配置”中,配置JS接口安全域名。

3. 获取access_token

access_token是公众号的全局唯一接口调用凭据,公众号调用各接口时都需使用access_token。通过AppIDAppSecret获取access_token

<?php
function getAccessToken($appId, $appSecret) {
    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appId}&secret={$appSecret}";
    $response = file_get_contents($url);
    $result = json_decode($response, true);
    return $result['access_token'];
}

$appId = 'YOUR_APP_ID'; // 替换为您的AppID
$appSecret = 'YOUR_APP_SECRET'; // 替换为您的AppSecret
$accessToken = getAccessToken($appId, $appSecret);
?>

4. 获取jsapi_ticket

jsapi_ticket是公众号用于调用微信JS接口的临时票据。

<?php
function getJsApiTicket($accessToken) {
    $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$accessToken}&type=jsapi";
    $response = file_get_contents($url);
    $result = json_decode($response, true);
    return $result['ticket'];
}

$jsApiTicket = getJsApiTicket($accessToken);
?>

5. 生成签名

生成签名的过程包括以下几个步骤:

  • 获取当前页面的完整URL(不包含#及其后面部分)
  • 对URL进行排序并拼接参数
  • 使用SHA1算法生成签名
<?php
function createSignature($jsApiTicket, $noncestr, $timestamp, $url) {
    $string = "jsapi_ticket={$jsApiTicket}&noncestr={$noncestr}&timestamp={$timestamp}&url={$url}";
    return sha1($string);
}

$noncestr = md5(uniqid(rand(), true));
$timestamp = time();
$currentUrl = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; // 获取当前页面的完整URL
$signature = createSignature($jsApiTicket, $noncestr, $timestamp, $currentUrl);
?>

6. 配置JS-SDK

在页面中配置JS-SDK,并注入权限验证配置。

<script>
wx.config({
    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
    appId: '<?php echo $appId; ?>', // 必填,公众号的唯一标识
    timestamp: <?php echo $timestamp; ?>, // 必填,生成签名的时间戳
    nonceStr: '<?php echo $noncestr; ?>', // 必填,生成签名的随机串
    signature: '<?php echo $signature; ?>',// 必填,签名
    jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData'] // 必填,需要使用的JS接口列表
});

wx.ready(function(){
    // 分享给朋友
    wx.updateAppMessageShareData({ 
        title: '分享标题', // 分享标题
        desc: '分享描述', // 分享描述
        link: 'http://example.com', // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        imgUrl: 'http://example.com/icon.jpg', // 分享图标
        success: function () {
            // 设置成功
        }
    });

    // 分享到朋友圈
    wx.updateTimelineShareData({ 
        title: '分享标题', // 分享标题
        link: 'http://example.com', // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        imgUrl: 'http://example.com/icon.jpg', // 分享图标
        success: function () {
            // 设置成功
        }
    });
});

wx.error(function(res){
    console.log('微信JS-SDK配置失败:', res);
});
</script>

完整示例

以下是一个完整的PHP和HTML示例,展示了如何实现微信分享功能。

<?php
function getAccessToken($appId, $appSecret) {
    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appId}&secret={$appSecret}";
    $response = file_get_contents($url);
    $result = json_decode($response, true);
    return $result['access_token'];
}

function getJsApiTicket($accessToken) {
    $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$accessToken}&type=jsapi";
    $response = file_get_contents($url);
    $result = json_decode($response, true);
    return $result['ticket'];
}

function createSignature($jsApiTicket, $noncestr, $timestamp, $url) {
    $string = "jsapi_ticket={$jsApiTicket}&noncestr={$noncestr}&timestamp={$timestamp}&url={$url}";
    return sha1($string);
}

$appId = 'YOUR_APP_ID'; // 替换为您的AppID
$appSecret = 'YOUR_APP_SECRET'; // 替换为您的AppSecret
$accessToken = getAccessToken($appId, $appSecret);
$jsApiTicket = getJsApiTicket($accessToken);
$noncestr = md5(uniqid(rand(), true));
$timestamp = time();
$currentUrl = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; // 获取当前页面的完整URL
$signature = createSignature($jsApiTicket, $noncestr, $timestamp, $currentUrl);
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>微信分享示例</title>
    <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
    <script>
    wx.config({
        debug: false,
        appId: '<?php echo $appId; ?>',
        timestamp: <?php echo $timestamp; ?>,
        nonceStr: '<?php echo $noncestr; ?>',
        signature: '<?php echo $signature; ?>',
        jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData']
    });

    wx.ready(function(){
        wx.updateAppMessageShareData({ 
            title: '分享标题',
            desc: '分享描述',
            link: 'http://example.com',
            imgUrl: 'http://example.com/icon.jpg',
            success: function () {
                // 设置成功
            }
        });

        wx.updateTimelineShareData({ 
            title: '分享标题',
            link: 'http://example.com',
            imgUrl: 'http://example.com/icon.jpg',
            success: function () {
                // 设置成功
            }
        });
    });

    wx.error(function(res){
        console.log('微信JS-SDK配置失败:', res);
    });
    </script>
</head>
<body>
    <h1>微信分享示例</h1>
    <p>点击右上角菜单,选择“分享到朋友圈”或“发送给朋友”。</p>
</body>
</html>

注意事项

  1. 域名配置

    • 确保在微信公众平台中配置的JS接口安全域名与实际访问的域名一致,并且域名需要备案。
  2. 签名生成

    • 确保生成签名时使用的URL是完整的页面URL,不包含#及其后面的部分。
  3. 缓存

    • access_tokenjsapi_ticket都有有效期,建议进行缓存以减少不必要的请求。
  4. 调试

    • 开启debug模式可以帮助调试,但在生产环境中应关闭。

通过以上步骤,您可以在微信公众号中实现分享到朋友和朋友圈的自定义文案功能。如果有任何问题或需要进一步的帮助,请随时提问。

0 条评论

还没有人发表评论

发表评论 取消回复

记住我的信息,方便下次评论
有人回复时邮件通知我