WeChat Share Cards for Empire CMS: Thumbnails and Summaries for Chats and Moments

You need an Official Account, and your domain must be registered as a JS interface security domain under it, or none of this works.The share code below uses the current interfaces from WeChat's developer docs; the older ones most people online still use are on their way out. (Verified April 2020.)

Step 1: Put jssdk.php in your site root

<?php
class JSSDK {
  private $appId;
  private $appSecret;

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

  public function getSignPackage() {
    $jsapiTicket = $this->getJsApiTicket();

    // The URL must be read dynamically -- never hardcode it.
    $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();

    // These parameters must be sorted by key in ascending ASCII order
    $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 should be cached globally and refreshed; here we just write it to a file as an example
    $data = json_decode($this->get_php_file("jsapi_ticket.php"));
    if ($data->expire_time < time()) {
      $accessToken = $this->getAccessToken();
      // For a WeCom (enterprise) account, use this URL to get the ticket
      // $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;
        $this->set_php_file("jsapi_ticket.php", json_encode($data));
      }
    } else {
      $ticket = $data->jsapi_ticket;
    }

    return $ticket;
  }

  private function getAccessToken() {
    // access_token should be cached globally and refreshed; here we just write it to a file as an example
    $data = json_decode($this->get_php_file("access_token.php"));
    if ($data->expire_time < time()) {
      // For a WeCom (enterprise) account, use this URL to get the 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;
        $this->set_php_file("access_token.php", json_encode($data));
      }
    } 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);
    // Every WeChat API call goes over HTTPS to keep traffic between third-party servers and WeChat secure, so the two lines below must enable SSL verification.
    // If verification fails here during deployment, download a fresh CA bundle from http://curl.haxx.se/ca/cacert.pem
    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;
  }

  private function get_php_file($filename) {
    return trim(substr(file_get_contents($filename), 15));
  }
  private function set_php_file($filename, $content) {
    $fp = fopen($filename, "w");
    fwrite($fp, "<?php exit();?>" . $content);
    fclose($fp);
  }
}

Step 2: Register the JS security domain in your Official Account
Log in to the WeChat MP platform, then go to Account Settings -> Function Settings and fill in the "JS interface security domain."

Step 3: Add a template variable and paste in the code, with appid and appsecret set to your Official Account's values (place the template variable immediately before </body>):

<?
// Start of the WeChat share code
require '../../jssdk.php';
$appid = '******';
$appsecret = '******';
$jssdk = new JSSDK($appid,$appsecret);
$signPackage = $jssdk->GetSignPackage();
// End of the WeChat share code
?>

<script src="http://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
<script>
  // Note: every JS API call only works on the domain bound to your Official Account. Log in to the WeChat MP platform, then under Account Settings -> Function Settings register the "JS interface security domain".
  // If custom share content doesn't work on Android, download the latest WeChat build from the official site and install it over your current one: Android needs 6.0.2.58 or newer for custom sharing.
  // Full JS-SDK docs: http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html
  wx.config({
    debug: !1,
    appId: '<?php echo $signPackage["appId"];?>',
    timestamp: <?php echo $signPackage["timestamp"];?>,
    nonceStr: '<?php echo $signPackage["nonceStr"];?>',
    signature: '<?php echo $signPackage["signature"];?>',
    jsApiList: [
        "updateAppMessageShareData",
        "updateTimelineShareData",
        "onMenuShareWeibo",
        "onMenuShareQZone"
    ]
  });
  wx.ready(function () {
    // Call the API here
    wx.checkJsApi({
    jsApiList: ["updateAppMessageShareData",
        "updateTimelineShareData",
        "onMenuShareWeibo",
        "onMenuShareQZone"], // JS APIs to check; the full list is in appendix 2,
        success: function(res) {
            //alert(JSON.stringify(res));
            if(res.errMsg !='checkJsApi:ok'){
                alert('Please update your WeChat app');
                return;
            }
        }
    });
  // Sharing demo
// Custom share content for the "Share with a friend" button
    wx.updateAppMessageShareData({
    title: '<?=$navinfor[title]?>', // Share title
    desc: '<?=$navinfor[smalltext]?>', // Share description
    link: 'http://www.xxx.com<?=$navinfor[titleurl]?>', // Share link
    imgUrl: '<?=$navinfor[titlepic]?>', // Share icon
        success: function () {
          // Configured successfully
        }
    });

// Custom share content for the "Share to Moments" button
    wx.updateTimelineShareData({
    title: '<?=$navinfor[title]?>', // Share title
    link: 'http://www.xxx.com<?=$navinfor[titleurl]?>', // Share link
    imgUrl: '<?=$navinfor[titlepic]?>', // Share icon
        success: function () {
          // Configured successfully
        }
    });
  wx.onMenuShareWeibo({
    title: '<?=$navinfor[title]?>', // Share title
    desc: '<?=$navinfor[smalltext]?>', // Share description
    link: 'http://www.xxx.com<?=$navinfor[titleurl]?>', // Share link
    imgUrl: '<?=$navinfor[titlepic]?>', // Share icon
    success: function () {
       // Callback that runs after the user confirms the share
    },
    cancel: function () {
        // Callback that runs after the user cancels the share
    }
  });

});
</script>

Leave a Comment

Comments No Comments

Table of Contents