以下是一个使用 PHP 调用个推(Getui)消息推送的基本示例。请确保你已经在个推平台注册并获取了相关的 AppKey、AppSecret 和 Master Secret。
<?php
class GeTui {
private $url = 'https://restapi.getui.com/v2/';
private $appId;
private $appKey;
private $masterSecret;
public function __construct($appId, $appKey, $masterSecret) {
$this->appId = $appId;
$this->appKey = $appKey;
$this->masterSecret = $masterSecret;
}
// 获取访问token
private function getToken() {
$url = "https://restapi.getui.com/v2/" . $this->appId . "/auth";
$data = json_encode([
'client_id' => 'your_client_id', // 替换为实际的 client_id
'secret' => 'your_secret' // 替换为实际的 secret
]);
return json_decode($this->curlPost($url, $data), true);
}
// 推送消息
public function pushMessage($clientId, $title, $content) {
// 获取token
$tokenResponse = $this->getToken();
if (!isset($tokenResponse['code']) || (int)$tokenResponse['code'] !== 0) {
return ['status' => false, 'msg' => 'Failed to get token.'];
}
// 创建消息内容
$messageData = [
'request_id' => uniqid(),
'action' => [
'type' => 1,
'title' => $title,
'text' => json_encode(['content' => htmlspecialchars($content)]),
'payload' => [],
// 更多设置可以参考文档 https://docs.getui.com/
],
'client_id_list' => [$clientId],
'options'=> [
"speed" => 1000,
"pushNetWorkType" => 0,
"retryInterval" => 30,
]
];
// 请求接口进行消息推送
return json_decode($this->curlPost($this->url . "{$this->appId}/push", json_encode($messageData)), true);
}
private function curlPost($url, $data) {
try {
if (function_exists('curl_init')) {
//$ch 是 cURL 的句柄
//初始化
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "$url");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,array(
"Content-Type: application/json",
"Accept: application/json",
"Authorization: Bearer {$this->getAccessToken()}" // 带上授权头部信息,如有需要的话。
));
curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
// 执行请求
return curl_exec ($ch);
} else {
throw new Exception("cURL not supported");
}
} catch(Exception$e) {
echo "Error: ".var_export(serror_get_last(),true)."\n";
}
}
}
// 示例用法:
$appId = "your_app_id"; // 替换为你的 App ID
$appKey = "your_app_key"; // 替换为你的 App Key
$masterSecret = "your_master_secret"; // 替换为你的 Master Secret
$getui = new GeTui($appId, $appKey, masterSecret);
// 客户端 ID 应该是接收者设备的 client ID,你可以通过其他方式获取。
$clientId = "receiver_client_id";
$title = "测试标题";
$content = "这是发送给客户端的测试消息";
$response = getui.pushMessage(clientId,title,$content);
print_r(response);
?>
注意事项:
- 在代码中替换相应的
your_app_id
、your_app_key
、your_master_secret
和receiver_client_id
等参数。 - 请根据个推官方文档调整 API URL 和请求格式,确保符合最新要求。
- 本示例仅供参考,具体实现可能需要根据项目需求做适当调整。
内容由零声教学AI助手提供,问题来源于学员提问