html5网页链接分享到微信朋友圈带图标和摘要的完美解决方法

7309

html5网页链接分享到微信朋友,微信朋友圈,QQ,微博带图标和摘要

步骤一:

登录微信公众平台:https://mp.weixin.qq.com/

222.png

获取到appid,添加IP白名单(添加服务IP即可)

image.png

步骤二:绑定域名
先登录微信公众平台进入“公众号设置”的“功能设置”里填写“JS接口安全域名”。

image.png

步骤三:引入JS文件  

获取JS地址:https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html#3

在设置开发--->接口权限 查看是否已经获取到分享权限(需要验证公众号)

image.png


这里最重要的就是正确计算签名,签名算法微信官方也有说,用php进行签名算法的完成,以下代码是jssdk.php(这个代码主要就是进行签名的获取,获取签名之后才可以吧wx.config中的参数正确获得,才能拥有相对应的jssdk权限)


<?php
class JSSDK {
  private $appId;
  private $appSecret;
 
  public function __construct($appId, $appSecret) {
    $this->appId = $appId;
    $this->appSecret = $appSecret;
  }
 
  public function getSignPackage($signUrl = null) {
    $jsapiTicket = $this->getJsApiTicket();
 
    if ($signUrl) {
      $url = $signUrl;
    } else {
      $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
      $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    }
 
    $timestamp = time();
    $nonceStr = $this->createNonceStr();
 
    // 这里参数的顺序要按照 key 值 ASCII 码升序排序
    $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() {
    // jsapi_ticket 应该全局存储与更新,以下代码以写入到文件中做示例
    $data = json_decode(file_get_contents("./cache/jsapi_ticket.json"));
    if ($data->expire_time < time()) {
      $accessToken = $this->getAccessToken();
      // 如果是企业号用以下 URL 获取 ticket,但是具体操作中,企业号的url使用下面的也不是不可以
      // $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
 
      $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;
        $fp = fopen("./cache/jsapi_ticket.json", "w");
        fwrite($fp, json_encode($data));
        fclose($fp);
      }
    } else {
      $ticket = $data->jsapi_ticket;
    }
 
    return $ticket;
  }
 
  private function getAccessToken() {
    // access_token 应该全局存储与更新,以下代码以写入到文件中做示例
    $data = json_decode(file_get_contents("./cache/access_token.json"));
    if ($data->expire_time < time()) {
      // 如果是企业号用以下URL获取access_token
      // $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";
      $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;
        $fp = fopen("./cache/access_token.json", "w");
        fwrite($fp, json_encode($data));
        fclose($fp);
      }
    } else {
      $access_token = $data->access_token;
    }
    return $access_token;
  }
 
  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, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_URL, $url);
 
    $res = curl_exec($curl);
    curl_close($curl);
 
    return $res;
 
  }
}

除此之外要创建一个文件夹jsoncache,在文件夹中放三个文件,后两个文件用在jssdk.php代码之中用于存储值使用,

第一个文件内容为deny from all(apache 安全性设置),如果你是nginx就需要重新设置

333.png

下面是调用代码:

<?php
require_once './jssdk.php';
$jssdk = new JSSDK('appid', 'appsecret');
$wxconfig = $jssdk->getSignPackage();
?>

<script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
<script>
    if(isMobile()){
        wx.config({
            debug: false,
            appId: '<?php echo $wxconfig['appId']; ?>',
            timestamp: <?php echo $wxconfig["timestamp"]; ?>,
            nonceStr: '<?php echo $wxconfig["nonceStr"]; ?>',
            signature: '<?php echo $wxconfig["signature"]; ?>',
            jsApiList: [
                'onMenuShareTimeline',
                'onMenuShareAppMessage',
                'onMenuShareQQ',
                'onMenuShareWeibo'
                'updateAppMessageShareData'
            ]
        });
        wx.ready(function() {
            var shareTitle = '标题';
            var shareDesc = '描述';
            var shareLink = '地址';
            var shareImg = 'logo版';
            wx.updateAppMessageShareData({
                title: shareTitle,
                desc: shareDesc,
                link: shareLink,
                imgUrl: shareImg,
                success: function () {
                    // 设置成功
                }
            });
            // 分享给朋友事件绑定
            wx.onMenuShareAppMessage({
                title: shareTitle,
                desc: shareDesc,
                link: shareLink,
                imgUrl: shareImg
            });
            // 分享到朋友圈
            wx.onMenuShareTimeline({
                title: shareTitle,
                link: shareLink,
                imgUrl: shareImg
            });
                      // 分享到QQ
                          wx.onMenuShareQQ({
                            title: shareTitle,
                            desc: shareDesc,
                            link: shareLink,
                            imgUrl: shareImg
                          });
                     
                          // 分享到微博
                          wx.onMenuShareWeibo({
                            title: shareTitle,
                            desc: shareDesc,
                            link: shareLink,
                            imgUrl: shareImg
                          });

        });
    }


下载