Backend Development 8 min read

Implementing WeChat Share Interface with PHP and JavaScript

This tutorial walks through registering a WeChat public account, configuring developer information and JS security domains, creating a PHP class to obtain the JS‑API signature, setting up PHP file configuration, and embedding the required JavaScript/HTML to enable custom share titles, descriptions, links, and images on WeChat.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Implementing WeChat Share Interface with PHP and JavaScript

When a project requires custom WeChat share titles, summaries, and images, you first need to register a WeChat public account and complete the authentication process; the account’s AppID and AppSecret are essential for the API calls.

In the WeChat public platform, navigate to Development → Basic Information to enable the developer mode and record the AppID and AppSecret. Then, under Settings → Development → JS Interface Security Domain , add the domain(s) from which your web pages will be served.

The core of the solution is a PHP class that retrieves the JS‑API ticket, generates a nonce string, builds the signature string, and returns a sign package containing appId , timestamp , nonceStr , url , and signature . The class also handles caching of access_token and jsapi_ticket in a JSON file.

class wechatClass {
    public $AppID;
    public $AppSecret;
    public $redirect_uri;
    public $DbSy;
    public $dump_url;
    public $scope;
    public function __construct() {
        parent::__construct();
        $this->AppID = "开发者密码(AppSecret)";
        $this->AppSecret = "开发者密码(AppSecret)";
    }
    public function getSignPackage() {
        $jsapiTicket = $this->getJsApiTicket();
        $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();
        $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;
    }
    public 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;
    }
    public function getJsApiTicket() {
        $data = json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT']."/static/yejuzhi/js/access_token.json"));
        if ($data->expire_time < time()) {
            $accessToken = $this->getAccessToken();
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&amp;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($_SERVER['DOCUMENT_ROOT']."/static/yejuzhi/js/access_token.json", "w");
                fwrite($fp, json_encode($data));
                fclose($fp);
            }
        } else {
            $ticket = $data->jsapi_ticket;
        }
        return $ticket;
    }
    public function getAccessToken() {
        $data = json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT']."/static/yejuzhi/js/access_token.json"));
        if ($data->expire_time < time()) {
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&amp;appid={$this->AppID}&amp;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($_SERVER['DOCUMENT_ROOT']."/static/yejuzhi/js/access_token.json", "w");
                fwrite($fp, json_encode($data));
                fclose($fp);
            }
        } else {
            $access_token = $data->access_token;
        }
        return $access_token;
    }
    public 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;
    }
}

In a ThinkPHP 5.1 project, instantiate the class and assign the sign package to the view:

$wx = new WeChatClass();
$sign = $wx->getSignPackage();
$this->assign('sign', $sign);

On the front end, include the WeChat JS SDK and configure wx.config with the values from the sign package, then call wx.updateAppMessageShareData (or wx.updateTimelineShareData ) to set the custom title, description, link, and image URL for sharing.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>微信分享接口制作</title>
</head>
<body>
<script src="http://res2.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
<script>
wx.config({
    debug: false,
    appId: '{$sign.appId}',
    timestamp: '{$sign.timestamp}',
    nonceStr: '{$sign.nonceStr}',
    signature: '{$sign.signature}',
    jsApiList: ["updateAppMessageShareData"]
});
wx.ready(function () {
    wx.updateAppMessageShareData({
        title: '您的标题',
        desc: '您的描述',
        link: '您的分享链接',
        imgUrl: '您的分享图标',
        success: function () {
            // 分享成功后可进行统计或提示
        }
    });
});
</script>
</body>
</html>

After deploying the PHP file and the HTML page on a server whose domain is listed in the JS security domain settings, the custom share content will appear when users share the page via WeChat.

backendJavaScriptphpAPIWeChatSharing
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.