微信中分享链接增加图标方法

首先这一定需要使用微信jssdk,但是在你使用了微信jssdk之后,依旧分享的链接不带图标和摘要,那就看看我踩的坑吧。

前端代码

我这里引入了jQuery(不用jQuery的写法的话可以不引入),然后这里就是必须引入最新的微信jssdk:https://res2.wx.qq.com/open/js/jweixin-1.6.0.js
最新的微信jssdk已经舍弃了之前的分享接口,最新的分享接口是:updateAppMessageShareData 和 updateTimelineShareData
前端代码如下:

<script src="https://res2.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
var url = location.href;
$.ajax({
	type: "get",
	url: "https://你的网址/wxjssdk.php?url=" + url,
	dataType: "json",
	success: function(res) {
		if (res.code === 200) {
			wx.config({
				debug: false,
				appId: res.data.appId,
				timestamp: res.data.timestamp,
				nonceStr: res.data.nonceStr,
				signature: res.data.signature,
				jsApiList: [
					'updateAppMessageShareData',
					'updateTimelineShareData'
				]
			});
			wx.ready(function() {
				wx.updateAppMessageShareData({
					title: res.data.title,
					desc: res.data.desc,
					link: res.data.link,
					imgUrl: res.data.imgUrl,
					success: function() {
						console.log('分享成功');
					}
				});
				wx.updateTimelineShareData({
					title: res.data.title,
					link: res.data.link,
					imgUrl: res.data.imgUrl,
					success: function() {
						console.log('分享成功');
					}
				})
			});
		}
	}
})
</script>

后端代码

前端需要ajax请求后端进行签名和获取token,请求的后端https://你的网址/wxjssdk.php文件代码如下:

<?php
/**
 * 微信JsSDK
 * Class JsSDK
 */
class JsSDK {
    private $appId;
    private $appSecret;
    private $url;

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

    /**
     * 签名
     * @return array
     */
    public function getSignPackage() {
        $jsapiTicket = $this->getJsApiTicket();
        $url = $this->url;
        $timestamp = time();
        $nonceStr = $this->createNonceStr();
        $string = "jsapi_ticket=" . $jsapiTicket . "&noncestr=" . $nonceStr . "&timestamp=" . $timestamp . "&url=" . $url;
        $signature = sha1($string);
        return [
            "appId"     => $this->appId,
            "nonceStr"  => $nonceStr,
            "timestamp" => $timestamp,
            "url"       => $url,
            "signature" => $signature,
            "rawString" => $string
        ];
    }

    /**
     * 创建字符串
     * @param int $length
     * @return string
     */
    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;
    }

    /**
     * 获取JsApiTicket
     * @return mixed
     */
    private function getJsApiTicket() {
        $data = json_decode($this->get_php_file("jsapi_ticket.php"));
        if ($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->expire_time = time() + 7000;
                $data->jsapi_ticket = $ticket;
                $this->set_php_file("jsapi_ticket.php", json_encode($data));
            }
        } else {
            $ticket = $data->jsapi_ticket;
        }
        return $ticket;
    }

    /**
     * 获取AccessToken
     * @return mixed
     */
    private function getAccessToken() {
        $data = json_decode($this->get_php_file("access_token.php"));
        if ($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->expire_time = time() + 7000;
                $data->access_token = $access_token;
                $this->set_php_file("access_token.php", json_encode($data));
            }
        } else {
            $access_token = $data->access_token;
        }
        return $access_token;
    }

    /**
     * GET CURL请求
     * @param $url
     * @return bool|string
     */
    private function httpGet($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }

    /**
     * 读取文件
     * @param $filename
     * @return string
     */
    private function get_php_file($filename) {
        return trim(substr(file_get_contents($filename), 15));
    }

    /**
     * 写入文件
     * @param $filename
     * @param $content
     */
    private function set_php_file($filename, $content) {
        $fp = fopen($filename, "w");
        fwrite($fp, "<?php exit();?>" . $content);
        fclose($fp);
    }
}

$url = $_GET['url'];
$JsSDK = new JSSDK("替换成你的公众号appId", "替换成你的公众号appSecret", $url);
$signPackage = $JsSDK->GetSignPackage();

$result = [
    'code' => 200,
    'msg' => 'success',
    'data' => [
        'appId' => $signPackage["appId"],
        'timestamp' => $signPackage["timestamp"],
        'nonceStr' => $signPackage["nonceStr"],
        'signature' => $signPackage["signature"],
        'title' => '替换成分享的链接标题',
        'desc' => '替换成分享的链接描述',
        'link' => $url,
        'imgUrl' => 'https://你的网址/share.png'
    ]
];

header('content-type:application/json');
echo json_encode($result);exit;

因为这里的 access_token 和 jsapi_ticket 都是存储在文件中,所以这里你需要创建两个文件,代码如下:

// access_token.php 文件
<?php exit();?>
{"access_token":"","expire_time":0}
// jsapi_ticket.php 文件
<?php exit();?>
{"jsapi_ticket":"","expire_time":0}

当然你也可以把 access_token 和 jsapi_ticket 存储在数据库中。

填坑

如果依然无法实现,那么注意以下几点:

  1. 确保服务器IP增加到了IP白名单中。
  2. 确保开发者ID(AppID)和开发者密码(AppSecret)正确,开发者密码(AppSecret)复制的时候可能会复制失败,需要手动复制
  3. 确保分享的网页域名已经增加到JS接口安全域名
  4. 由于微信内置浏览器有缓存,建议更换手机或刷新微信内浏览器缓存后再次查看效果,微信内浏览器清理缓存方法如下:在微信中打开链接debugmm.qq.com/?forcex5=true 然后关闭,再打开debugtbs.qq.com 和 debugx5.qq.com 来清理微信浏览器缓存。
  5. 如果实在不行建议使用 微信开发者工具 下载地址:https://developers.weixin.qq.com/miniprogram/dev/devtools/download.html 在开发者工具中调试,记着一定要开启jssdk中的debug