PHP微信JSSDK开发DEMO

<?php 
function getWxToken($appid, $appkey)
{
    $access_token = Config('access_token');
    if ($access_token) {
        return $access_token;
    }
    
    $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $appkey;
    $res = file_get_contents($url);
    $res = json_decode($res, true);
    if ($res && $res['access_token']) {
        Config('access_token', $res['access_token']);
        return $res['access_token'];
    }else{
        return '';
    }
}

function getWxJsToken($token)
{
    $jsapi_ticket = Config('jsapi_ticket');
    if ($jsapi_ticket) {
        return $jsapi_ticket;
    }
    $url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=' . $token;
    $res = file_get_contents($url);
    $res = json_decode($res, true);
    if ($res && $res['errcode'] == 0) {
        Config('jsapi_ticket', $res['ticket']);
        return $res['ticket'];
    }else{
        return '';
    }
}

function getSign($data)
{
    ksort($data);
    $str = [];
    foreach ($data as $key => $val) {
        $str[] = "$key=$val";
    }
    $sign = hash('sha1', implode('&', $str));
    
    return $sign;
}

function Config($key, $value = '', $expire = 7000)
{
    $file = 'wx_'.$key.'.txt';
    if ($value) {
        file_put_contents($file, json_encode([
            'value'  => $value,
            'expire' => time() + $expire,
        ]));
    }
    else {
        if (!is_file($file)){ 
            return '';
        }
        
        $data = file_get_contents($file);
        $data = json_decode($data, true);
        if ($data['expire'] >= time()){
            return $data['value'];
        }else{
            return '';
        }
    }
}

$appid  = '';
$appkey = '';

$token    = getWxToken($appid, $appkey);
$js_token = getWxJsToken($token);

$data = [
    'noncestr'     => sha1(time()) . mt_rand(100000, 999999),
    'timestamp'    => time(),
    'jsapi_ticket' => $js_token,
    'url'          => $_SERVER['HTTP_REFERER'] ?? ($_SERVER['REQUEST_SCHEME']."://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']),
];

$sign = getSign($data);
?>
<script src="https://res.wx.qq.com/open/js/jweixin-1.4.0.js"></script>
<script>
wx.config({
    debug: true,
    appId: '<?php echo $appid ?>',
    timestamp: <?php echo $data['timestamp']; ?>,
    nonceStr: '<?php echo $data['noncestr']; ?>',
    signature: '<?php echo $sign; ?>',
    jsApiList: ['onMenuShareTimeline','onMenuShareAppMessage','onMenuShareQQ','onMenuShareQZone']
});
</script>