引言
什么是微信Token?
获取微信Token的步骤
1. 注册微信公众账号
2. 请求Token
使用AppID和AppSecret,通过以下URL请求Token:
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
其中,APPID和APPSECRET分别替换为您自己的AppID和AppSecret。
3. 解析返回结果
{
"access_token": "ACCESS_TOKEN",
"expires_in": 7200,
"expires_at": 1597905600
}
其中,access_token为获取到的Token,expires_in为Token有效期(单位:秒),expires_at为Token过期时间戳。
4. 保存Token
为了方便后续使用,建议将Token保存到数据库或缓存中。以下是一个简单的示例:
<?php
$token = json_decode(file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET'), true);
$token['expires_at'] = time() + $token['expires_in'];
file_put_contents('token.txt', json_encode($token));
?>
5. 使用Token
<?php
$token = file_get_contents('token.txt');
$api_url = 'https://api.weixin.qq.com/cgi-bin/message/send?access_token=' . $token;
$data = json_encode(array(
'touser' => 'OPENID',
'msgtype' => 'text',
'text' => array('content' => 'Hello, WeChat!')
));
curl_setopt($api_url, CURLOPT_POST, true);
curl_setopt($api_url, CURLOPT_POSTFIELDS, $data);
curl_setopt($api_url, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($api_url);
?>