<?php
namespaceMyWeChat;
classWeChatApi
{
// 刷新access_token
privatestaticfunctionrefreshAccessToken($appid,$appsecret)
{
$url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";
$ch= curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response= curl_exec($ch);
curl_close($ch);
$data= json_decode($response, true);
if(isset($data['access_token'])) {
return$data['access_token'];
}else{
returnfalse;
}
}
// 获取新的access_token
privatestaticfunctiongetAccessTokenFromCache($tokenFile)
{
if(file_exists($tokenFile)) {
$tokenData=include($tokenFile);
if($tokenData&&is_array($tokenData) && isset($tokenData['access_token']) && isset($tokenData['expires_at'])) {
return$tokenData;
}
}
}
// 更新access_token缓存文件
privatestaticfunctionupdateAccessTokenCache($tokenFile,$access_token,$expires_in)
{
$expires_at= time() +$expires_in- 60;
$tokenData="<?php\nreturn array('access_token' => '$access_token', 'expires_at' => $expires_at);\n";
file_put_contents($tokenFile,$tokenData);
}
// 发送订阅消息
publicstaticfunctionsendMessageWithAccessToken($appid,$appsecret,$template_id,$openid,$data_template)
{
$TOKEN_FILE='access_token.php';
$tokenData= self::getAccessTokenFromCache($TOKEN_FILE);
if($tokenData&&$tokenData['expires_at'] > time()) {
$access_token=$tokenData['access_token'];
}else{
$access_token= self::refreshAccessToken($appid,$appsecret);
if($access_token) {
self::updateAccessTokenCache($TOKEN_FILE,$access_token, 7200);
}else{
echo"Access_Token刷新失败\n";
return;
}
}
// 发送订阅消息的接口
$url="https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=$access_token";
// 需要发送的消息体
$message_data= [
"touser"=>$openid,
"template_id"=>$template_id,
"page"=>"pages/read/read?aid=360282",
"miniprogram_state"=>"formal",
"lang"=>"zh_CN",
"data"=>$data_template
];
// 初始化cURL
$ch= curl_init();
// 配置cURL
curl_setopt_array($ch, [
CURLOPT_URL =>$url,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => json_encode($message_data),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['Content-Type: application/json']
]);
// 执行cURL
$response= curl_exec($ch);
// 判断发送结果
if(curl_errno($ch)) {
// 失败
echo'执行失败: '. curl_error($ch);
}else{
// 成功
echo'执行成功: '.$response;
}
// 关闭cURL
curl_close($ch);
}
}
// 小程序配置(APPID、APPSECRET)
$APPID='xxx';// 小程序APPID
$APPSECRET='xxx';// 小程序APPSECRET
// 小程序订阅消息配置(模板id、openid、模板字段)
$template_id="xxx";// 模板id
$openid="o9usm0bhIkcbAyxM0RzDXi9tjHhM";// 接收消息的openid
// 模板id对应的模板字段
$data_template= [
"character_string1"=> ["value"=>"2023-08-03"],
"thing4"=> ["value"=>"开发测试"]
];
// 执行静态方法
WeChatApi::sendMessageWithAccessToken($APPID,$APPSECRET,$template_id,$openid,$data_template);
?>
|