mkwsra liked a comment+100 XP
3mos ago
i have some questions..
How do I set up OneSignal in Laravel? What packages or libraries should I use?
is it possible to do via onesignal rest api?
currently i have tried this but failed?
OneSignalService
<?php
namespace App\Services;
use GuzzleHttp\Client;
class OneSignalService
{
protected $appId;
protected $apiKey;
protected $client;
public function __construct()
{
$this->appId = config('services.onesignal.app_id');
$this->apiKey = config('services.onesignal.api_key');
$this->client = new Client();
}
public function sendPush($title, $message, array $playerIds = [])
{
$url = 'https://api.onesignal.com/notifications?c=push';
$headers = [
'Authorization' => 'Key ' . $this->apiKey,
'Content-Type' => 'application/json',
'Accept' => 'application/json',
];
$payload = [
'app_id' => $this->appId,
'headings' => ['en' => $title],
'contents' => ['en' => $message],
"target_channel" => "push"
];
if (!empty($playerIds)) {
$payload['include_subscription_ids'] = $playerIds;
} else {
$payload['included_segments'] = ['All'];
}
try {
$response = $this->client->post($url, [
'headers' => $headers,
'json' => $payload,
]);
return json_decode($response->getBody(), true);
} catch (\Exception $e) {
return ['error' => $e->getMessage()];
}
}
}
Route::get('/test', function () {
$users = User::whereNotNull('onesignal_player_id')->get();
$playerIds = $users->pluck('onesignal_player_id')->toArray();
if (!empty($playerIds)) {
$response = app(OneSignalService::class)->sendPush(
"Hi there",
"This is a test notification",
$playerIds
);
dd($response);
}
});
and i cant figure what type of token/id should i get/save from flutter? to user model?
Any guidance, code examples, or links to relevant documentation would be greatly appreciated!