H5网页微信分享自定义标题、描述、图标

前端 · 2021-01-05 ·

1.前期准备

  • 请确认公众号已经认证,只有认证的公众号才具有分享相关接口权限
  • 登录微信公众平台进入“公众号设置”的“功能设置”里填写“JS接口安全域名”。
  • 配置IP白名单,基本配置-公众号开发信息-IP白名单。

2.后端部署阶段

jssdk
├── index.php
├── config.php
├── jssdk.php
├── access_token.json
├── jsapi_ticket.json

以上后端文件(具体代码在 4.后端具体代码)用来返回给前端wx.config中必填信息

{
    "code":0,
    "data":{
        "debug":false,
        "appId":"appId",
        "timestamp":1609811779,
        "nonceStr":"hLHs0rrv7EnNrp0K",
        "signature":"ba893a44d8d62ec7f65a53bc3185ad7b838751cc",
        "jsApiList":[
            "onMenuShareTimeline",
            "onMenuShareAppMessage",
            "onMenuShareQQ",
            "onMenuShareWeibo",
            "hideMenuItems",
            "showMenuItems"
        ]
    },
    "msg":"ok"
}

3.前端调用阶段

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>
    <script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"> </script>
    <script src="https://lib.baomitu.com/jquery/1.12.4/jquery.min.js"> </script>
    <script>
        $.ajax({
            type: "get",
            url: "http://www.mla.xin/jssdk/index.php?url=" + encodeURI(location.href),
            dataType: "json",
            data: {},
            success: function (res) {
                wx.config({
                    debug: true, // 调试开启
                    appId: res.data.appId,
                    timestamp: res.data.timestamp,
                    nonceStr: res.data.nonceStr,
                    signature: res.data.signature,
                    jsApiList: res.data.jsApiList
                });
            },
            error: function (data) {
                alert("连接失败!");
            }
        });
        wx.ready(function () {
            var shareData = {
                title: "标题",
                desc: "描述",
                link: window.location.href,
                imgUrl: "图标"
            };
            wx.onMenuShareAppMessage(shareData);
            wx.onMenuShareTimeline(shareData);
            wx.onMenuShareQQ(shareData);
            wx.onMenuShareWeibo(shareData);
        });
    </script>
</head>

<body>

</body>

</html>

4.后端具体代码

jssdk文件夹中的代码

config.php

<?php
$appid = 'appid';
$appsecret = 'appsecret';

jssdk.php

<?php

class JSSDK {
    private $appId;
    private $appSecret;
    public function __construct($appId, $appSecret) {
        $this->appId = $appId;
        $this->appSecret = $appSecret;
    }

    public function getSignPackage($url) {
        $jsapiTicket = $this->getJsApiTicket();
        $timestamp = time();
        $nonceStr = $this->createNonceStr();
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

        $signature = sha1($string);

        $signPackage = array(
            "appId"     => $this->appId,
            "nonceStr"  => $nonceStr,
            "timestamp" => $timestamp,
            "url"       => $url,
            "signature" => $signature,
            "rawString" => $string
        );
        return $signPackage;
    }

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

    private function getJsApiTicket() {
        $file = 'jsapi_ticket.json';
        if(!file_exists($file)){
            file_put_contents($file, '');
        }
        $data = json_decode(file_get_contents($file));
        if (empty($data) || $data->expire_time < time()) {
            $accessToken = $this->getAccessToken();
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
            $res = json_decode($this->httpGet($url));
            $ticket = $res->ticket;
            if ($ticket) {
                $data = new stdClass();
                $data->expire_time = time() + 4000;
                $data->jsapi_ticket = $ticket;
                file_put_contents($file, json_encode($data));
            }
        } else {
            $ticket = $data->jsapi_ticket;
        }

        return $ticket;
    }

    private function getAccessToken() {
        $file = 'access_token.json';
        if(!file_exists($file)){
            file_put_contents($file, '');
        }
        $data = json_decode(file_get_contents($file));
        if (empty($data) || $data->expire_time < time()) {
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
            $res = json_decode($this->httpGet($url));
            $access_token = $res->access_token;
            if ($access_token) {
                $data = new stdClass();
                $data->expire_time = time() + 4000;
                $data->access_token = $access_token;
                file_put_contents($file, json_encode($data));
            }
        } else {
            $access_token = $data->access_token;
        }
        return $access_token;
    }

    private function httpGet($url) {
        return file_get_contents($url);
    }
}

index.php

<?php
include 'config.php';
include 'jssdk.php';
$jssdk = new JSSDK($appid, $appsecret);
$url = $_GET['url'];
$signPackage = $jssdk->getSignPackage($url);
$config =  array(
    'debug' => false,
    'appId' => $signPackage['appId'],
    'timestamp' => $signPackage['timestamp'],
    'nonceStr' => $signPackage['nonceStr'],
    'signature' => $signPackage['signature'],
    'jsApiList' => array(
        'onMenuShareTimeline',
        'onMenuShareAppMessage',
        'onMenuShareQQ',
        'onMenuShareWeibo',
        'hideMenuItems',
        'showMenuItems'
    )
);
echo json_encode(['code' => 0,'data' => $config ,'msg' => 'ok']);
exit;

access_token.json 空文件,用以保存 access_token

{
    "expire_time":1609816219,
    "access_token":""
}

jsapi_ticket.json 空文件,用以保存 jsapi_ticket

{
    "expire_time":1609816219,
    "jsapi_ticket":""
}
上一篇:
下一篇:
%