以下是一个用 PHP 从微信小程序获取 access_token 并存储在 MySQL 数据库中的示例代码:
<?php // 定义常量 define("APP_ID", "your_app_id"); define("APP_SECRET", "your_app_secret"); // 获取 access_token $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . APP_ID . "&secret=" . APP_SECRET; $result = file_get_contents($url); $result = json_decode($result, true); $access_token = $result['access_token']; // 连接数据库 $conn = mysqli_connect("localhost", "your_username", "your_password", "your_database"); // 更新数据库中的 access_token $sql = "UPDATE wx_access_token SET access_token='" . $access_token . "', expires_in='" . $result['expires_in'] . "', update_time='" . time() . "' WHERE id=1"; mysqli_query($conn, $sql); // 关闭数据库连接 mysqli_close($conn); ?>
如果要使用 memcache 缓存 access_token,可以使用以下代码:
<?php // 连接 memcache $memcache = new Memcache; $memcache->connect('localhost', 11211) or die ("Could not connect"); // 从 memcache 中获取 access_token $access_token = $memcache->get('access_token'); // 如果 memcache 中没有 access_token,则从微信服务器获取并存储在 memcache 中 if (!$access_token) { // 获取 access_token $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . APP_ID . "&secret=" . APP_SECRET; $result = file_get_contents($url); $result = json_decode($result, true); $access_token = $result['access_token']; // 将 access_token 存储在 memcache 中 $memcache->set('access_token', $access_token, 0, $result['expires_in']); } // 关闭 memcache 连接 $memcache->close(); ?>