OneSignal v2 PHP手搓请求消息推送-供参考 - 实践

背景

项目框架: lumen5.8 由于比较老, 一些依赖包版本难免较低;

onesignal v2 php api的包的依赖包版本较新, 无法使用;

解决办法:

1.升级框架版本;

2.升级依赖包版本;

两个方案的风险均较大;就是但

于是结合当前项目仅针对特对用户进行消息推送, 结合官方文档, 手搓一个方法, 先用起;

app_id = PlatformConfigService::configValueForKey('onesignal_app_id', null);
$this->api_key = PlatformConfigService::configValueForKey('onesignal_app_key', null);
if (empty($this->app_id) || empty($this->api_key))
{
Controller::throwException("OneSignalV2 Config Err");
}
}
/**
* 推送消息到指定玩家;
* @param mixed $headings
* @param mixed $contents
* @param mixed $data
* @param mixed $external_ids
* @param string $delivery_time
*/
public function pushNotificationToUser($headings, $contents, $data, $segments, $external_ids, $delivery_time)
{
$api_url = $this->base_url . "/notifications?c=push";
//消息内容;
$push_contents = is_string($contents) ? ["en" => $contents] : $contents;
//请求参数
$params = [
"app_id" => $this->app_id,
"target_channel" => "push",
"contents" => $push_contents,
"ios_badgeType" => "Increase",//iOS角标类型(Increase/Set/None)
"ios_badgeCount" => 1,//iOS角标数量
"content_available" => true,
];
//消息标题
if (!empty($headings)) {
$params["headings"] = is_string($headings) ? ["en" => $headings] : $headings;;
}
//自定义数据(可透传到客户端)
if (!empty($data)) {
$params["data"] = $data;
}
//用户类型
if (!empty($segments)) {
$params["included_segments"] = $segments;
}
//玩家ID
if (!empty($external_ids)) {
$params["include_aliases"]["external_id"] = $external_ids;
}
//发送时间(暂时有误)
if (!empty($delivery_time))
{
// $params["delayed_option] = "timezone;
// $params["delivery_time_of_day] = $delivery_time;
}
$service = new HttpService();
$service->request($api_url, "post")
->setHeader("Authorization", "Key " . $this->api_key)//请求头;
->addParams($params)
->setCallback(function ($content, $code){
if($code == 200)
{
Log::info($content);
return $content;
}
});
$service->waiting();
return $service->retData();
}
/**
* 仅用于测试推送;
* @param int $user_ids;
*/
public function testPush($user_ids)
{
$title = "(Test)Grats! The W is incoming! ";
$message = "Nice! Victory in 3...2...1...! ";
$data = [
"event_code" => 103,
"hello" => "world",
];
if (!is_array($user_ids))
{
$user_ids = ["$user_ids"];
}
// $delivery_time = date('H:i:s', time() + 10);
$ret_data = $this->pushNotificationToUser($title, $message, $data, null, $user_ids, $delivery_time ?? null);
Log::info("testPush", [$ret_data]);
return $ret_data;
}
}

调用返回的结果

{
"id": "a8614a07-9cab-4099-a041-eb36987ddd38",
"external_id": null
}

确认APP有收到推送消息!

posted @ 2025-10-23 10:22  yjbjingcha  阅读(2)  评论(0)    收藏  举报