Skip to content

Instantly share code, notes, and snippets.

@guruguruman
Created September 6, 2016 14:03
Show Gist options
  • Save guruguruman/13ab9074b25419ecbd777b062fc0999e to your computer and use it in GitHub Desktop.
Save guruguruman/13ab9074b25419ecbd777b062fc0999e to your computer and use it in GitHub Desktop.
Managing to send push notification using OneSignal https://onesignal.com/
<?php namespace App\Services;
use GuzzleHttp\Client;
class OneSignal {
const API_URL_ADD_PLAYER = 'https://onesignal.com/api/v1/players';
const API_URL_CREATE_PUSH = 'https://onesignal.com/api/v1/notifications';
const DEVICE_TYPE_IOS = 0;
const DEVICE_TYPE_ANDROID = 1;
private $client;
public function __construct()
{
$this->client = new Client();
}
public function addPlayer($appId, $user, $device)
{
$response = $this->client->post(
self::API_URL_ADD_PLAYER,
[
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Basic '. \Config::get("onesignal.{$appId}.api_key"),
],
'body' => json_encode([
'app_id' => \Config::get("onesignal.{$appId}.app_id"),
'deviceType' => $device->deviceType(), // 0 = iOS, 1 = Android, 2 = Amazon, 3 = Windows Phone
'identifier' => $device->device_token,
'language' => 'ja-JP',
'timezone' => 32400,
'created_at' => $user->created_at->timestamp,
]),
]
);
$result = $response->json();
if (!$result['success']) return null;
return $result['id'];
}
public function sendPush($appId, $deviceType, $heading, $content, $scheduledTime = null, $playerIds = null)
{
$fields = [
'app_id' => \Config::get("onesignal.{$appId}.app_id"),
'headings' => [ // 見出し(heading) はAndroidのみ表示
"en" => $heading,
"ja-JP" => $heading,
],
'contents' => [
"en" => $content,
"ja-JP" => $content,
],
];
// デバイスタイプ別オプション
switch ($deviceType) {
case self::DEVICE_TYPE_IOS:
$fields['isIOS'] = true;
$fields['ios_badgeType'] = 'SetTo';
$fields['ios_badgeCount'] = 0;
break;
case self::DEVICE_TYPE_ANDROID:
$fields['isAndroid'] = true;
$fields['android_visibility'] = 0;
break;
}
// スケジュールが設定されていないと即時送信
if (!empty($scheduledTime)) {
$fields['send_after'] = date('D M d Y H:i:s \G\M\TO (T)', strtotime($scheduledTime));
}
// プレイヤーIDが無ければ全送信
if (!empty($player_ids)) {
$fields['include_player_ids'] = $player_ids;
} else {
$fields['included_segments'] = ["All"];
}
$fields = json_encode($fields);
$response = $this->client->post(
self::API_URL_CREATE_PUSH,
[
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Basic '. \Config::get("onesignal.{$appId}.api_key"),
],
'body' => $fields,
]
);
;
if ($response->getStatusCode() >= 200) {
echo ("***** SUCCESSFULLY SENT *****");
} else {
echo ("***** FAILED TO SEND <STATUS CODE:({$response->getStatusCode()})> *****");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment