PHP获取获取微信(微信小程序)AccessToken,这是技术宅根据微信开发文档写的PHP小工具。
这个实现具有以下特点:
- 封装成类,便于复用和维护
- 包含完整的错误处理机制,包括网络请求错误、JSON 解析错误和 API 返回错误
- 遵循微信 API 的要求,正确构建请求参数
- 提供了清晰的返回结果处理
- 包含使用示例,方便开发者快速上手
使用时,你需要:
将your_appid_here
和your_appsecret_here
替换为实际的微信小程序(公众号/小店) ID 和 secret
可以将获取到的 access_token
存储在缓存或数据库中
根据返回的expires_in(有效期)设置定时刷新机制,建议在过期前 30 分钟刷新
按照文档建议,最好实现中控服务器统一管理 access_token 的获取和刷新
请将服务器IP添加进微信公众号(小程序/小店)的IP白名单
注意:由于 access_token
有有效期且重复获取会导致旧 token 失效,建议实现合理的缓存机制,并确保在分布式系统中不会出现并发刷新导致的问题。
<?php class WechatAccessToken { /** * 小店唯一凭证 * @var string */ private $appId; /** * 小店唯一凭证密钥 * @var string */ private $appSecret; /** * API接口URL * @var string */ private $apiUrl = 'https://api.weixin.qq.com/cgi-bin/token'; /** * 构造函数 * @param string $appId 小店ID * @param string $appSecret 小店secret */ public function __construct(string $appId, string $appSecret) { $this->appId = $appId; $this->appSecret = $appSecret; } /** * 获取access_token * @return array|false 返回包含access_token和expires_in的数组,失败返回false */ public function getToken() { // 构建请求参数 $params = [ 'grant_type' => 'client_credential', 'appid' => $this->appId, 'secret' => $this->appSecret ]; // 构建完整URL $url = $this->apiUrl . '?' . http_build_query($params); // 发送请求 $response = $this->httpGet($url); if (!$response) { return false; } // 解析JSON响应 $result = json_decode($response, true); // 检查解析结果 if (json_last_error() !== JSON_ERROR_NONE) { error_log('解析access_token响应失败: ' . json_last_error_msg()); return false; } // 检查是否有错误 if (isset($result['errcode']) && $result['errcode'] != 0) { error_log('获取access_token失败: [' . $result['errcode'] . '] ' . $result['errmsg']); return false; } // 检查返回结果是否包含必要字段 if (!isset($result['access_token']) || !isset($result['expires_in'])) { error_log('access_token返回结果不完整'); return false; } return $result; } /** * 发送GET请求 * @param string $url 请求URL * @return string|false 响应内容或false */ private function httpGet(string $url) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); // 验证SSL证书 curl_setopt($ch, CURLOPT_TIMEOUT, 10); // 超时时间10秒 $response = curl_exec($ch); // 检查是否有错误发生 if (curl_errno($ch)) { error_log('HTTP请求错误: ' . curl_error($ch)); curl_close($ch); return false; } curl_close($ch); return $response; } } // 使用示例 // 替换为实际的appid和secret $appId = 'your_appid_here'; $appSecret = 'your_appsecret_here'; $tokenFetcher = new WechatAccessToken($appId, $appSecret); $tokenInfo = $tokenFetcher->getToken(); if ($tokenInfo) { echo "获取access_token成功:\n"; echo "access_token: " . $tokenInfo['access_token'] . "\n"; echo "有效期: " . $tokenInfo['expires_in'] . "秒\n"; // 建议在此处将access_token存储起来,并记录获取时间以便过期前刷新 } else { echo "获取access_token失败\n"; } ?>
将以上PHP代码保存为WechatAccessToken.php
并上传至服务器,修改相关的appid
和secret
访问即可获取AccessToken
,