写一个完整的jssdk.php 用于使用微信自定义分享,并将它插入到html当中写一个demo
时间: 2023-02-06 13:16:48 浏览: 69
好的,这是一个用于使用微信自定义分享的完整的 jssdk.php 文件:
```php
<?php
// 微信 JSSDK
// 定义项目根目录
define('ROOT_PATH', dirname(__FILE__));
// 定义微信 AppID 和 AppSecret
define('APPID', '你的 AppID');
define('APPSECRET', '你的 AppSecret');
// 加载 composer 第三方依赖库
require ROOT_PATH . '/vendor/autoload.php';
// 引入 Guzzle HTTP 客户端
use GuzzleHttp\Client;
// 定义缓存文件名
define('CACHE_FILE', ROOT_PATH . '/cache/access_token.json');
/**
* 获取微信 AccessToken
*
* @return string
*/
function getAccessToken()
{
// 判断缓存文件是否存在
if (file_exists(CACHE_FILE)) {
// 读取缓存文件
$cache = json_decode(file_get_contents(CACHE_FILE), true);
// 判断是否过期
if (time() < $cache['expire_time']) {
// 未过期,直接返回 AccessToken
return $cache['access_token'];
}
}
// 缓存文件不存在或已过期,调用微信接口获取 AccessToken
$client = new Client();
$response = $client->request('GET', 'https://api.weixin.qq.com/cgi-bin/token', [
'query' => [
'grant_type' => 'client_credential',
'appid' => APPID,
'secret' => APPSECRET,
],
]);
$result = json_decode($response->getBody(), true);
// 判断是否获取成功
if (isset($result['access_token'])) {
// 写入缓存文件
file_put_contents(CACHE_FILE, json_encode([
'access_token' => $result['access_token'],
'expire_time' => time() + 7000,
]));
// 返回 AccessToken
return $result['access_token'];
} else {
// 获取失败,抛出异常
throw new Exception('