### Example Notification Buttons Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/types.md An example demonstrating how to configure buttons for a notification. This includes setting the notification content, target segments, and the buttons themselves. ```php $params = [ 'contents' => ['en' => 'Choose an action'], 'included_segments' => ['All'], 'buttons' => [ ['id' => 'approve', 'text' => 'Approve'], ['id' => 'reject', 'text' => 'Reject'], ] ]; ``` -------------------------------- ### Example .env Configuration Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/errors.md Example of essential environment variables required for OneSignal configuration. Ensure these are set in your .env file. ```env ONESIGNAL_APP_ID=your-app-id ONESIGNAL_REST_API_KEY=your-key USER_AUTH_KEY=your-key ``` -------------------------------- ### Example .env File Configuration Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/api-reference/OneSignalServiceProvider.md This example demonstrates how to configure the OneSignal service provider using environment variables in a .env file. It includes all required and optional variables for setting up the OneSignal integration. ```dotenv ONESIGNAL_APP_ID=12345678-1234-1234-1234-123456789012 ONESIGNAL_REST_API_KEY=ABC123def456GHI789jkl012MNO345pqr USER_AUTH_KEY=XYZ789abc456DEF123ghi678JKL012mno ONESIGNAL_REST_API_URL=https://api.onesignal.com ONESIGNAL_GUZZLE_CLIENT_TIMEOUT=30 ``` -------------------------------- ### Example Filter Arrays Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/types.md Examples demonstrate single and multiple conditions for filtering, including numeric comparisons. Multiple conditions are implicitly ANDed. ```php // Single condition [ ["field" => "tag", "key" => "email", "relation" => "=", "value" => "user@example.com"] ] ``` ```php // Multiple conditions (implicit AND) [ ["field" => "tag", "key" => "plan", "relation" => "=", "value" => "premium"], ["field" => "tag", "key" => "verified", "relation" => "=", "value" => "true"] ] ``` ```php // Numeric comparisons [ ["field" => "tag", "key" => "session_count", "relation" => ">", "value" => "5"], ["field" => "tag", "key" => "days_active", "relation" => ">=", "value" => "30"] ] ``` -------------------------------- ### GET /apps Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/README.md Lists all available applications associated with the account. ```APIDOC ## GET /apps ### Description Lists all available applications associated with the account. ### Method GET ### Endpoint /apps ### Parameters (Not specified in source) ### Request Example (Not specified in source) ### Response #### Success Response (200) (Not specified in source) #### Response Example (Not specified in source) ``` -------------------------------- ### Basic Usage Examples Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/api-reference/OneSignalFacade.md Demonstrates how to send notifications to all users, specific users, and segments using the OneSignalFacade. ```APIDOC ## Basic Notification Sending ### Description Examples of sending notifications to different targets. ### Usage ```php use Berkayk\OneSignal\OneSignalFacade as OneSignal; // Send notification to all users OneSignal::sendNotificationToAll("Hello World"); // Send to specific user OneSignal::sendNotificationToUser("Hello", "$userId"); // Send to segment OneSignal::sendNotificationToSegment("Welcome", "New Users"); ``` ``` -------------------------------- ### App Management Methods Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/api-reference/OneSignalFacade.md Provides examples for retrieving information about OneSignal apps, including a specific app or a list of all apps. ```php // App management OneSignal::getApp($appId); OneSignal::getApps(); ``` -------------------------------- ### Method Chaining Example Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/api-reference/OneSignalFacade.md Illustrates how to use method chaining with the OneSignalFacade to build complex notification parameters before sending. ```APIDOC ## Method Chaining ### Description The facade supports method chaining, allowing you to set multiple parameters fluently before sending a notification. ### Example 1: Setting Multiple Parameters ```php OneSignal::setParam('priority', 10) ->setParam('android_accent_color', 'FFCCAA72') ->setParam('led_color', 'FFAACCAA') ->sendNotificationToAll("Important message"); ``` ### Example 2: Combining Parameters and Async ```php OneSignal::addParams([ 'android_accent_color' => 'FFCCAA72', 'priority' => 10 ]) ->async() ->sendNotificationToSegment("Special offer", "Premium Users"); ``` ``` -------------------------------- ### Get All Applications Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/api-reference/OneSignalClient.md Retrieves metadata for all applications owned by the user account. ```APIDOC ## GET /apps ### Description Retrieves metadata for all applications owned by the user account. ### Method GET ### Endpoint `/apps` ### Response #### Success Response (200) - **Array of App Objects** - Each object contains metadata for an application. ### Response Example ```json [ { "id": "app-id-1", "name": "App One" }, { "id": "app-id-2", "name": "App Two" } ] ``` ``` -------------------------------- ### GET /apps Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/MANIFEST.txt Lists all applications associated with the account. This endpoint provides an overview of all configured applications. ```APIDOC ## GET /apps ### Description Lists all applications associated with the account. This endpoint provides an overview of all configured applications. ### Method GET ### Endpoint /apps ### Response #### Success Response (200) - An array of application objects, each containing ID, name, and player count. #### Response Example ```json [ { "id": "app_id_1", "name": "App One", "players": 1500 }, { "id": "app_id_2", "name": "App Two", "players": 750 } ] ``` ``` -------------------------------- ### Get All Application Details Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/api-reference/OneSignalClient.md Retrieves metadata for all applications associated with the user account. The response contains an array of app objects. ```php public function getApps(): mixed $response = OneSignal::getApps(); $apps = json_decode($response->getBody()); foreach ($apps as $app) { echo $app->name . ": " . $app->id . "\n"; } ``` -------------------------------- ### Get App Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/INDEX.md Retrieves details of a specific application by its ID. ```APIDOC ## GET /apps/{id} ### Description Gets an app. ### Method GET ### Endpoint /apps/{id} ``` -------------------------------- ### Get Test Credentials Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/api-reference/OneSignalClient.md Retrieves configured App ID and REST API Key for testing. Returns a formatted string. ```php public function testCredentials(): string ``` ```php echo OneSignal::testCredentials(); // Output: APP ID: abc123 REST: xyz789 ``` -------------------------------- ### Example .env File for OneSignal Configuration Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/configuration.md This snippet shows how to set the necessary environment variables in your .env file for the OneSignal Laravel wrapper. Ensure all required variables are present. ```env # OneSignal Configuration ONESIGNAL_APP_ID=12345678-1234-1234-1234-123456789012 ONESIGNAL_REST_API_KEY=ABC123def456GHI789jkl012MNO345pqr678stu901vwx234yz USER_AUTH_KEY=XYZ789abc456DEF123ghi678JKL012mno345pqr678stu901vwx ONESIGNAL_REST_API_URL=https://api.onesignal.com ONESIGNAL_GUZZLE_CLIENT_TIMEOUT=30 ``` -------------------------------- ### Install OneSignal Laravel Package Source: https://github.com/berkayk/laravel-onesignal/blob/master/README.md Install the OneSignal Laravel package using Composer. This is the first step to integrate OneSignal push notifications into your Laravel application. ```sh composer require berkayk/onesignal-laravel ``` -------------------------------- ### GET /apps/{id} Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/README.md Retrieves information about a specific application using its ID. ```APIDOC ## GET /apps/{id} ### Description Retrieves information about a specific application using its ID. ### Method GET ### Endpoint /apps/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the app to retrieve. ### Request Example (Not specified in source) ### Response #### Success Response (200) (Not specified in source) #### Response Example (Not specified in source) ``` -------------------------------- ### Get Application Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/api-reference/OneSignalClient.md Retrieves metadata for a specific application. If no app ID is provided, it uses the client's default app ID. ```APIDOC ## GET /apps/{app_id} ### Description Retrieves metadata for a specific application. Uses the client's app ID if `$app_id` is not provided. ### Method GET ### Endpoint `/apps/{app_id}` ### Parameters #### Query Parameters - **app_id** (string|null) - Optional - App ID; uses client's app ID if not provided ### Response #### Success Response (200) - **name** (string) - The name of the application. ### Response Example ```json { "name": "My Awesome App" } ``` ``` -------------------------------- ### Send Notification Using Tags (Email Filter) Source: https://github.com/berkayk/laravel-onesignal/blob/master/README.md Send a message to users matching specific email tags. This example targets users with specific email addresses. ```php OneSignal::sendNotificationUsingTags( "Some Message", array( ["field" => "tag", "key" => "email", "relation" => "=", "value" => "email21@example.com"], ["field" => "tag", "key" => "email", "relation" => "=", "value" => "email1@example.com"], ... ), $url = null, $data = null, $buttons = null, $schedule = null ); ``` -------------------------------- ### Global Alias Registration Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/api-reference/OneSignalFacade.md Example of how the OneSignal facade is registered as a global alias in `config/app.php` for convenient access without explicit import. ```php 'aliases' => [ 'OneSignal' => Berkayk\OneSignal\OneSignalFacade::class ] ``` -------------------------------- ### Get Application Details Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/api-reference/OneSignalClient.md Retrieves metadata for a specific OneSignal application. Uses the client's default app ID if none is provided. ```php public function getApp(string|null $app_id = null): mixed $response = OneSignal::getApp(); $app = json_decode($response->getBody()); echo $app->name; ``` -------------------------------- ### Send Notification Using Tags (Numeric Filter) Source: https://github.com/berkayk/laravel-onesignal/blob/master/README.md Send a message to users matching numeric tag filters. This example targets users based on session count and first session time. ```php OneSignal::sendNotificationUsingTags( "Some Message", array( ["field" => "tag", "key" => "session_count", "relation" => ">", "value" => '2'], ["field" => "tag", "key" => "first_session", "relation" => ">", "value" => '2000'], ), $url = null, $data = null, $buttons = null, $schedule = null ); ``` -------------------------------- ### ISO 639-1 Language Codes for Content Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/types.md Provides examples of ISO 639-1 language codes used for the 'contents', 'headings', and 'subtitle' parameters in OneSignal notifications. Ensure correct codes are used for multi-language support. ```php [ 'en' => 'English message', 'es' => 'Mensaje en español', 'fr' => 'Message français', 'de' => 'Deutsche Nachricht', 'it' => 'Messaggio italiano', 'ja' => '日本語メッセージ', 'zh' => '中文消息', 'pt' => 'Mensagem em português', 'ru' => 'Русское сообщение', 'ar' => 'رسالة عربية', ] ``` -------------------------------- ### Send GET Request Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/api-reference/OneSignalClient.md Sends a GET request to a specified endpoint. Use for retrieving resources. ```php public function get(string $endPoint): mixed ``` -------------------------------- ### Using Aliased Facade Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/api-reference/OneSignalFacade.md Shows how to use the facade directly via its global alias 'OneSignal' without needing to import the class. ```php OneSignal::sendNotificationToAll("Hello"); ``` -------------------------------- ### Migration from Direct Class Usage Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/api-reference/OneSignalFacade.md Compares the old way of instantiating `OneSignalClient` directly with the new, simplified facade usage. ```php // Old way $client = new OneSignalClient($appId, $key, $userKey); $client->sendNotificationToAll("Hello"); // New way with facade OneSignal::sendNotificationToAll("Hello"); ``` -------------------------------- ### Get Notification Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/INDEX.md Retrieves the details of a specific notification by its ID. ```APIDOC ## GET /notifications/{id} ### Description Gets a notification. ### Method GET ### Endpoint /notifications/{id} ``` -------------------------------- ### Parameter Building Methods Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/api-reference/OneSignalFacade.md Illustrates methods for building notification parameters using `addParams` and `setParam` before sending. ```php // Parameter building OneSignal::addParams($params); OneSignal::setParam($key, $value); ``` -------------------------------- ### Initialize OneSignalClient Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/api-reference/OneSignalClient.md Instantiate the OneSignalClient with your application credentials and optional configuration for Guzzle client timeout and API URL. ```php use Berkayk\OneSignal\OneSignalClient; $client = new OneSignalClient( 'your-app-id', 'your-rest-api-key', 'your-user-auth-key', 30 ); ``` -------------------------------- ### Check Configuration File Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/api-reference/OneSignalServiceProvider.md Inspect the published OneSignal configuration file to ensure it exists and is accessible. ```bash cat config/onesignal.php ``` -------------------------------- ### GET /notifications/{id} Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/README.md Retrieves details of a specific notification using its ID. ```APIDOC ## GET /notifications/{id} ### Description Retrieves details of a specific notification using its ID. ### Method GET ### Endpoint /notifications/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the notification to retrieve. ### Request Example (Not specified in source) ### Response #### Success Response (200) (Not specified in source) #### Response Example (Not specified in source) ``` -------------------------------- ### Create Player Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/INDEX.md Creates a new player record. ```APIDOC ## POST /players ### Description Creates a player. ### Method POST ### Endpoint /players ``` -------------------------------- ### GET /notifications Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/MANIFEST.txt Lists all notifications for the application. This endpoint allows for retrieving a history of sent notifications. ```APIDOC ## GET /notifications ### Description Lists all notifications for the application. This endpoint allows for retrieving a history of sent notifications. ### Method GET ### Endpoint /notifications ### Parameters #### Query Parameters - **app_id** (string) - Required - The ID of the application to list notifications for. ### Response #### Success Response (200) - An array of notification objects, each containing details like ID, content, and creation timestamp. #### Response Example ```json [ { "id": "notification_id_123", "contents": {"en": "Hello World!"}, "created_at": "2023-10-27T10:00:00Z" }, { "id": "notification_id_456", "contents": {"en": "Another message"}, "created_at": "2023-10-26T09:00:00Z" } ] ``` ``` -------------------------------- ### Development Environment Configuration Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/configuration.md Configure OneSignal credentials and timeout for the development environment using a `.env.local` or `.env.development` file. ```env # .env.local or .env.development ONESIGNAL_APP_ID=dev-app-id-xxx ONESIGNAL_REST_API_KEY=dev-rest-key-xxx USER_AUTH_KEY=dev-user-key-xxx ONESIGNAL_GUZZLE_CLIENT_TIMEOUT=30 ``` -------------------------------- ### Available Methods Overview Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/api-reference/OneSignalFacade.md Lists common methods available through the OneSignalFacade for notification sending, parameter building, async operations, and management tasks. ```APIDOC ## Available Methods ### Description All public methods of OneSignalClient are accessible via the facade. This section lists common operations. ### Notification Sending - `sendNotificationToAll($message)` - `sendNotificationToUser($message, $userId)` - `sendNotificationToExternalUser($message, $externalId)` - `sendNotificationToSegment($message, $segment)` - `sendNotificationUsingTags($message, $filters)` - `sendNotificationCustom($parameters)` ### Parameter Building - `addParams($params)` - `setParam($key, $value)` ### Async Operations - `async()->sendNotificationToAll($message)` - `async()->callback($callback)->sendNotificationCustom($params)` ### Notification Management - `getNotifications($appId, $limit, $offset)` - `getNotification($notificationId)` - `deleteNotification($notificationId)` ### App Management - `getApp($appId)` - `getApps()` ### Player Management - `createPlayer($parameters)` - `editPlayer($parameters)` ### Testing - `testCredentials()` *For detailed documentation of each method, refer to the [OneSignalClient documentation](./OneSignalClient.md).* ``` -------------------------------- ### GET /notifications/{id} Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/MANIFEST.txt Retrieves a specific notification by its ID. This endpoint provides details about a previously sent notification. ```APIDIDOCOC ## GET /notifications/{id} ### Description Retrieves a specific notification by its ID. This endpoint provides details about a previously sent notification. ### Method GET ### Endpoint /notifications/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the notification to retrieve. ### Response #### Success Response (200) - **id** (string) - The unique ID of the notification. - **contents** (object) - The notification content. - **headings** (object) - The notification headings. - **recipients** (integer) - The number of recipients. - **created_at** (string) - The timestamp when the notification was created. #### Response Example ```json { "id": "notification_id_123", "contents": {"en": "Hello World!"}, "headings": {"en": "Greeting"}, "recipients": 2, "created_at": "2023-10-27T10:00:00Z" } ``` ``` -------------------------------- ### Configuration Options Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/MANIFEST.txt Details on environment variables and configuration file keys required for setting up the OneSignal integration. ```APIDOC ## CONFIGURATION DOCUMENTED ### ENVIRONMENT VARIABLES (5): - **ONESIGNAL_APP_ID** [Required] - **ONESIGNAL_REST_API_KEY** [Required] - **USER_AUTH_KEY** [Required] - **ONESIGNAL_REST_API_URL** [Optional, default: https://api.onesignal.com] - **ONESIGNAL_GUZZLE_CLIENT_TIMEOUT** [Optional, default: 0] ### CONFIG FILE KEYS (5): - **app_id** [Reads from ONESIGNAL_APP_ID] - **rest_api_key** [Reads from ONESIGNAL_REST_API_KEY] - **user_auth_key** [Reads from USER_AUTH_KEY] - **rest_api_url** [Reads from ONESIGNAL_REST_API_URL] - **guzzle_client_timeout** [Reads from ONESIGNAL_GUZZLE_CLIENT_TIMEOUT] ### Description Proper configuration is essential for the package to function. You can set up your OneSignal integration using environment variables or a configuration file. Key variables include your App ID, REST API Key, and User Auth Key. Optional settings like the API URL and client timeout can also be configured. ``` -------------------------------- ### Accessing OneSignal Client Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/api-reference/OneSignalServiceProvider.md Demonstrates three ways to access the OneSignal client: using a facade, retrieving it from the service container, or through dependency injection. ```php // 1. Via facade OneSignal::sendNotificationToAll("Hello"); ``` ```php // 2. From service container app('onesignal')->sendNotificationToAll("Hello"); ``` ```php // 3. Via dependency injection public function notify(OneSignalClient $client) { $client->sendNotificationToAll("Hello"); } ``` -------------------------------- ### Basic Usage of OneSignalFacade Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/api-reference/OneSignalFacade.md Demonstrates how to use the OneSignalFacade to send notifications to all users, specific users, or segments. Ensure the facade is imported or aliased. ```php use Berkayk\OneSignal\OneSignalFacade as OneSignal; // Send notification to all users OneSignal::sendNotificationToAll("Hello World"); // Send to specific user OneSignal::sendNotificationToUser("Hello", $userId); // Send to segment OneSignal::sendNotificationToSegment("Welcome", "New Users"); ``` -------------------------------- ### GET /apps/{id} Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/MANIFEST.txt Retrieves details for a specific application. This endpoint provides information about an application configured within OneSignal. ```APIDOC ## GET /apps/{id} ### Description Retrieves details for a specific application. This endpoint provides information about an application configured within OneSignal. ### Method GET ### Endpoint /apps/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the application to retrieve. ### Response #### Success Response (200) - **id** (string) - The unique ID of the application. - **name** (string) - The name of the application. - **players** (integer) - The number of players registered for the application. #### Response Example ```json { "id": "your_app_id", "name": "My Awesome App", "players": 1500 } ``` ``` -------------------------------- ### Catching Missing Device Type Exception Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/errors.md Demonstrates how to catch a generic PHP Exception when the 'device_type' parameter is missing or not numeric during player creation. ```PHP use Berkayk\OneSignal\OneSignalClient; try { $params = [ 'language' => 'en', 'timezone' => 'America/New_York' // Missing: 'device_type' ]; OneSignal::createPlayer($params); } catch (\Exception $e) { if (strpos($e->getMessage(), 'device_type') !== false) { echo "Device type is required: " . $e->getMessage(); } } ``` -------------------------------- ### Fixing Missing Device Type Exception Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/errors.md Shows the correct usage of the createPlayer method by including the required 'device_type' parameter. ```PHP // Correct usage with device_type $params = [ 'device_type' => 5, // 5 = Chrome Web Push 'language' => 'en', 'timezone' => 'America/New_York' ]; OneSignal::createPlayer($params); ``` -------------------------------- ### Notification Management Methods Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/api-reference/OneSignalFacade.md Shows methods for managing notifications, such as retrieving lists, getting a specific notification, and deleting notifications. ```php // Notification management OneSignal::getNotifications($appId, $limit, $offset); OneSignal::getNotification($notificationId); OneSignal::deleteNotification($notificationId); ``` -------------------------------- ### Method Chaining for Notification Building Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/api-reference/OneSignalFacade.md Demonstrates method chaining to set multiple notification parameters before sending a notification to all users. ```php // Build notification with multiple parameters OneSignal::setParam('priority', 10) ->setParam('android_accent_color', 'FFCCAA72') ->setParam('led_color', 'FFAACCAA') ->sendNotificationToAll("Important message"); ``` -------------------------------- ### Clear Configuration and Cache Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/api-reference/OneSignalServiceProvider.md Clear the application's configuration and general cache to apply any changes or fixes. ```bash php artisan config:clear php artisan cache:clear ``` -------------------------------- ### Get Notifications List - OneSignalClient Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/api-reference/OneSignalClient.md Retrieves a paginated list of notifications for the application. You can specify an app ID, a limit for the number of results, and an offset for pagination. ```php // Get first 50 notifications $response = OneSignal::getNotifications(null, 50, 0); // Get next page $response = OneSignal::getNotifications(null, 50, 50); ``` -------------------------------- ### Production Environment Configuration Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/configuration.md Configure OneSignal credentials and timeout for the production environment using a `.env.production` file. Ensure secure management of production secrets. ```env # .env.production ONESIGNAL_APP_ID=prod-app-id-xxx ONESIGNAL_REST_API_KEY=prod-rest-key-xxx USER_AUTH_KEY=prod-user-key-xxx ONESIGNAL_GUZZLE_CLIENT_TIMEOUT=30 ``` -------------------------------- ### Verify Environment Variables Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/api-reference/OneSignalServiceProvider.md Confirm that the necessary OneSignal environment variables (APP_ID and REST_API_KEY) are set. ```bash php artisan tinker >>> env('ONESIGNAL_APP_ID') >>> env('ONESIGNAL_REST_API_KEY') ``` -------------------------------- ### Handle Guzzle Timeout Exception Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/errors.md Example of catching a Guzzle ConnectException and checking if the error message indicates a timeout. This helps in providing user feedback or implementing retry logic. ```php use GuzzleHttp\Exception\ConnectException; try { OneSignal::sendNotificationToAll("Hello"); } catch (ConnectException $e) { if (strpos($e->getMessage(), 'timed out') !== false) { echo "Request timed out, increase ONESIGNAL_GUZZLE_CLIENT_TIMEOUT"; } } ``` -------------------------------- ### Create Player Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/api-reference/OneSignalClient.md Creates a new player/user device record in OneSignal. Requires `device_type` to be specified. ```APIDOC ## POST /players ### Description Creates a new player/user device record in OneSignal. The `device_type` parameter is mandatory. ### Method POST ### Endpoint `/players` ### Parameters #### Request Body - **device_type** (integer) - Required - The type of device (e.g., 0 for iOS, 1 for Android, 5 for Chrome Web Push). - **language** (string) - Optional - The language of the user. - **timezone** (string) - Optional - The user's timezone. - **external_user_id** (string) - Optional - An identifier for the user in your system. ### Request Example ```json { "device_type": 5, "language": "en", "timezone": "America/New_York", "external_user_id": "user123" } ``` ### Response #### Success Response (200) - **id** (string) - The unique ID of the created player. ### Response Example ```json { "id": "player-uuid" } ``` ### Throws - `Exception` if `device_type` is missing or not numeric. ``` -------------------------------- ### Send Notification with Custom Heading and Subtitle Source: https://github.com/berkayk/laravel-onesignal/blob/master/README.md Use this example to send a notification to a segment with a custom heading and subtitle. The heading and subtitle are passed as the 7th and 8th arguments respectively. ```php use OneSignal; OneSignal::sendNotificationToSegment( "Test message with custom heading and subtitle", "Testers", null, null, null, null, "Custom Heading", "Custom subtitle" ); ``` -------------------------------- ### Testing Environment Configuration Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/configuration.md Configure OneSignal credentials and timeout for the testing environment using a `.env.testing` file. ```env # .env.testing ONESIGNAL_APP_ID=test-app-id-xxx ONESIGNAL_REST_API_KEY=test-rest-key-xxx USER_AUTH_KEY=test-user-key-xxx ONESIGNAL_GUZZLE_CLIENT_TIMEOUT=5 ``` -------------------------------- ### Get Notification Details - OneSignalClient Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/api-reference/OneSignalClient.md Retrieves detailed information for a specific notification using its ID. An optional app ID can be provided; if omitted, the client's default app ID is used. ```php $response = OneSignal::getNotification('notification-uuid'); $data = json_decode($response->getBody()); ``` -------------------------------- ### Player Management Methods Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/api-reference/OneSignalFacade.md Illustrates methods for managing player data, such as creating or editing player information. ```php // Player management OneSignal::createPlayer($parameters); OneSignal::editPlayer($parameters); ``` -------------------------------- ### Configure OneSignal Library Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/00-START-HERE.md Configure the OneSignal library by setting your App ID and REST API Key in the .env file. Ensure these values are correctly set for the library to function. ```env ONESIGNAL_APP_ID=your-id ONESIGNAL_REST_API_KEY=your-key USER_AUTH_KEY=your-key ``` -------------------------------- ### List Apps Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/INDEX.md Retrieves a list of all applications. ```APIDOC ## GET /apps ### Description Lists apps. ### Method GET ### Endpoint /apps ``` -------------------------------- ### Complete Error Handling for OneSignal Notifications Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/errors.md This example demonstrates comprehensive error handling for sending notifications via OneSignal. It catches specific Guzzle exceptions like ConnectException and RequestException, as well as general exceptions. It logs errors and returns appropriate JSON responses with status codes. ```php use GuzzleHttp\Exception\ConnectException; use GuzzleHttp\Exception\RequestException; public function sendNotification($message) { try { $response = OneSignal::sendNotificationToAll($message); $data = json_decode($response->getBody()); Log::info("Notification sent", [ 'id' => $data->id, 'recipients' => $data->recipients, ]); return response()->json([ 'success' => true, 'notification_id' => $data->id, ]); } catch (ConnectException $e) { Log::error("OneSignal connection error", [ 'message' => $e->getMessage(), ]); return response()->json([ 'error' => 'Connection to OneSignal failed', 'retry' => true, ], 503); } catch (RequestException $e) { $statusCode = $e->getResponse()->getStatusCode(); $body = (string)$e->getResponse()->getBody(); Log::error("OneSignal API error", [ 'status' => $statusCode, 'body' => $body, ]); if ($statusCode === 401) { return response()->json([ 'error' => 'OneSignal credentials invalid', ], 500); } if ($statusCode >= 500) { return response()->json([ 'error' => 'OneSignal is temporarily unavailable', 'retry' => true, ], 503); } return response()->json([ 'error' => 'Failed to send notification', 'details' => $body, ], 400); } catch (\Exception $e) { Log::error("Unexpected error", [ 'message' => $e->getMessage(), 'trace' => $e->getTraceAsString(), ]); return response()->json([ 'error' => 'An unexpected error occurred', ], 500); } } ``` -------------------------------- ### OneSignal Configuration File Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/configuration.md This is the content of the published `config/onesignal.php` file. It maps environment variables to configuration keys. You can override default values here. ```php return [ /* |-------------------------------------------------------------------------- | OneSignal App ID |-------------------------------------------------------------------------- | */ 'app_id' => env('ONESIGNAL_APP_ID'), /* |-------------------------------------------------------------------------- | Rest API Key |-------------------------------------------------------------------------- | */ 'rest_api_url' => env('ONESIGNAL_REST_API_URL', 'https://api.onesignal.com'), 'rest_api_key' => env('ONESIGNAL_REST_API_KEY'), 'user_auth_key' => env('USER_AUTH_KEY'), /* |-------------------------------------------------------------------------- | Guzzle Timeout |-------------------------------------------------------------------------- | */ 'guzzle_client_timeout' => env('ONESIGNAL_GUZZLE_CLIENT_TIMEOUT', 0), ]; ``` -------------------------------- ### Publish Configuration File Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/api-reference/OneSignalServiceProvider.md Users can publish the default configuration file for OneSignal using the provided Artisan command. This command specifies the service provider and the tag for the configuration. ```bash php artisan vendor:publish --provider="Berkayk\OneSignal\OneSignalServiceProvider" --tag="config" ``` -------------------------------- ### Building Parameters Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/00-START-HERE.md Methods for setting notification parameters, either individually or in batches. ```APIDOC ## addParams() ### Description Sets multiple notification parameters at once. ### Method POST ### Endpoint /parameters ### Parameters #### Request Body - **params** (object) - Required - An object containing key-value pairs of parameters to set. ### Request Example { "example": "{\"params\": {\"headings\": {\"en\": \"New Update!\"}, \"data\": {\"update_url\": \"http://example.com/update\"}}}" } ### Response #### Success Response (200) - **success** (boolean) - Indicates if the parameters were set successfully. #### Response Example { "example": "{\"success\": true}" } ``` ```APIDOC ## setParam() ### Description Sets a single notification parameter. ### Method POST ### Endpoint /parameter ### Parameters #### Request Body - **key** (string) - Required - The name of the parameter to set. - **value** (mixed) - Required - The value of the parameter. ### Request Example { "example": "{\"key\": \"contents\", \"value\": {\"en\": \"A single parameter update.\"}}" } ### Response #### Success Response (200) - **success** (boolean) - Indicates if the parameter was set successfully. #### Response Example { "example": "{\"success\": true}" } ``` -------------------------------- ### Sending Notifications to Multiple Users in a Batch Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/README.md Demonstrates how to send a single notification to multiple users efficiently by providing an array of user IDs to `include_player_ids` or `include_external_user_ids`. ```php OneSignal::sendNotificationToUser( "Hello", ['user-1', 'user-2', 'user-3'] ); ``` -------------------------------- ### App Response Structure Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/types.md Details of an application, including its ID, name, user count, and configuration details. Returned by the getApp() method. ```php { 'id' => string, // App ID 'name' => string, // App name 'players' => integer, // Total users/devices 'created_at' => integer, // Unix timestamp 'gcm_key' => string, // Android key if configured 'chrome_web_icon' => string, // Chrome icon URL 'android_accent_color' => string, // Default Android color 'org_id' => string, // Organization ID } ``` -------------------------------- ### Managing Apps Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/00-START-HERE.md Methods for listing applications and retrieving information about a specific application. ```APIDOC ## getApps() ### Description Lists all applications associated with your OneSignal account. ### Method GET ### Endpoint /apps ### Parameters #### Query Parameters - **user_auth_key** (string) - Required - Your OneSignal User Authentication Key. ### Response #### Success Response (200) - **total_count** (integer) - The total number of applications. - **offset** (integer) - The offset of the results. - **limit** (integer) - The limit of the results. - **apps** (array) - An array of application objects. #### Response Example { "example": "{\"total_count\": 5, \"offset\": 0, \"limit\": 50, \"apps\": [{\"id\": \"app_id_1\", \"name\": \"My First App\"}, {\"id\": \"app_id_2\", \"name\": \"My Second App\"}]}" } ``` ```APIDOC ## getApp() ### Description Retrieves detailed information about a specific application. ### Method GET ### Endpoint /apps/{app_id} ### Parameters #### Path Parameters - **app_id** (string) - Required - The ID of the application to retrieve. #### Query Parameters - **user_auth_key** (string) - Required - Your OneSignal User Authentication Key. ### Response #### Success Response (200) - **id** (string) - The application ID. - **name** (string) - The name of the application. - **players** (integer) - The number of players registered for the app. - **apns_env** (string) - The APNS environment (development or production). - **created_at** (string) - The timestamp when the app was created. - **updated_at** (string) - The timestamp when the app was last updated. #### Response Example { "example": "{\"id\": \"app_id_1\", \"name\": \"My First App\", \"players\": 10000, \"apns_env\": \"production\", \"created_at\": \"2023-01-01T12:00:00Z\", \"updated_at\": \"2023-10-26T14:30:00Z\"}" } ``` -------------------------------- ### Laravel OneSignal File Structure Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/README.md Overview of the directory structure for the laravel-onesignal package, highlighting key files and their purposes. ```text laravel-onesignal/ ├── src/ │ ├── OneSignalClient.php # Main client class │ ├── OneSignalFacade.php # Facade │ └── OneSignalServiceProvider.php # Service provider ├── config/ │ └── onesignal.php # Configuration file ├── README.md # Installation guide └── composer.json # Package manifest ``` -------------------------------- ### Catching Guzzle ConnectException Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/errors.md Demonstrates how to catch a Guzzle ConnectException, which occurs when an HTTP connection fails. Includes logging the error message and request details. ```PHP use GuzzleHttp\Exception\ConnectException; use Berkayk\OneSignal\OneSignalClient; try { OneSignal::sendNotificationToAll("Hello"); } catch (ConnectException $e) { echo "Network error: " . $e->getMessage(); Log::error("OneSignal connection failed", [ 'error' => $e->getMessage(), 'request' => $e->getRequest(), ]); } ``` -------------------------------- ### Method Chaining with Async and Parameters Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/api-reference/OneSignalFacade.md Combines method chaining for setting parameters with asynchronous sending for notifications to a segment. ```php // Combine parameters and async OneSignal::addParams([ 'android_accent_color' => 'FFCCAA72', 'priority' => 10 ]) ->async() ->sendNotificationToSegment("Special offer", "Premium Users"); ``` -------------------------------- ### Manual Registration for Laravel <5.5 Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/api-reference/OneSignalServiceProvider.md Shows how to manually register the OneSignal Service Provider and its facade alias in `config/app.php` for Laravel versions below 5.5. ```php 'providers' => [ // ... Berkayk\\\OneSignal\\OneSignalServiceProvider::class, ], 'aliases' => [ // ... 'OneSignal' => Berkayk\\\OneSignal\\OneSignalFacade::class, ] ``` -------------------------------- ### Create Player Record Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/api-reference/OneSignalClient.md Creates a new player or user device record in OneSignal. Requires a `device_type` parameter and can include other details like `language` and `external_user_id`. Catches exceptions if `device_type` is missing or invalid. ```php public function createPlayer(array $parameters): mixed try { $params = [ 'device_type' => 5, // Chrome Web Push 'language' => 'en', 'timezone' => 'America/New_York', 'external_user_id' => 'user123' ]; $response = OneSignal::createPlayer($params); $player = json_decode($response->getBody()); echo "Player ID: " . $player->id; } catch (\Exception $e) { echo "Error: " . $e->getMessage(); } ``` -------------------------------- ### Configure OneSignal Credentials Source: https://github.com/berkayk/laravel-onesignal/blob/master/README.md Set your OneSignal REST API URL, App ID, and REST API Key in the .env file. ```env ONESIGNAL_REST_API_URL=https://api.onesignal.com ONESIGNAL_APP_ID=xxxxxxxxxxxxxxxxxxxx ONESIGNAL_REST_API_KEY=xxxxxxxxxxxxxxxxxx ``` -------------------------------- ### Asynchronous Operations Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/api-reference/OneSignalFacade.md Demonstrates how to perform asynchronous notification sending using the `async` method, optionally with a callback. ```php // Async operations OneSignal::async()->sendNotificationToAll($message); OneSignal::async()->callback($callback)->sendNotificationCustom($params); ``` -------------------------------- ### Types and Structures Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/MANIFEST.txt Documentation on various data structures and types used within the package, including notification parameters, filters, player details, and device types. ```APIDOC ## TYPES & STRUCTURES DOCUMENTED ### PARAMETER STRUCTURES: - **Notification parameters** [20+ parameters with types] - **Filter structure** [Tag-based with 6 operators] - **Player structure** [Device creation/update fields] - **Button structure** [Action buttons format] - **Response types** [5 response schemas] - **Tag structure** [Custom attributes] - **Language codes** [100+ language support] - **DateTime formats** [ISO 8601 examples] ### DEVICE TYPES (12): - **0: iOS** - **1: Android** - **2: Amazon Device** - **3: Windows Phone (MPNS)** - **4: Chrome Apps/Extensions** - **5: Chrome Web Push** - **6: Windows (WNS)** - **7: Safari** - **8: Firefox** - **9: MacOS** - **10: Alexa** - **11: Web push (generic)** ### Description This section details the various data structures and types used throughout the package. It covers the extensive parameters for notifications, the structure of filters for targeting, fields for player data, and the format for action buttons. It also lists supported language codes, date-time formats, and a comprehensive enumeration of device types that can be targeted. ``` -------------------------------- ### POST /players Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/README.md Creates a new player entry in the OneSignal system. ```APIDOC ## POST /players ### Description Creates a new player entry in the OneSignal system. ### Method POST ### Endpoint /players ### Parameters #### Request Body (Not specified in source) ### Request Example (Not specified in source) ### Response #### Success Response (200) (Not specified in source) #### Response Example (Not specified in source) ``` -------------------------------- ### Player Management Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/MANIFEST.txt Methods for creating new players (devices), editing existing player information, and requesting a CSV of players. ```APIDOC ## PLAYERS ### Methods - **createPlayer()** - **editPlayer()** - **requestPlayersCSV()** ### Description Manage player (device) data with these methods. `createPlayer()` adds a new device to your OneSignal application, `editPlayer()` updates an existing player's details, and `requestPlayersCSV()` allows you to export your player data as a CSV file. ``` -------------------------------- ### Parameter Management Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/MANIFEST.txt Methods for adding and setting parameters, likely for use in notification or player configurations. ```APIDOC ## PARAMETERS ### Methods - **addParams()** - **setParam()** ### Description These utility methods are used for managing parameters. `addParams()` likely adds a set of parameters, while `setParam()` sets a specific parameter, potentially for configuring notifications or player data. ``` -------------------------------- ### Create Direct OneSignal Client Instances for Multiple Apps Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/configuration.md Instantiate `OneSignalClient` directly for each OneSignal application when you need to manage multiple apps. This approach provides explicit control over which app's credentials are used for sending notifications. ```php use Berkayk\OneSignal\OneSignalClient; $primary = new OneSignalClient( config('onesignal.apps.primary.app_id'), config('onesignal.apps.primary.rest_api_key'), config('onesignal.apps.primary.user_auth_key'), config('onesignal.apps.primary.guzzle_client_timeout') ); $secondary = new OneSignalClient( config('onesignal.apps.secondary.app_id'), config('onesignal.apps.secondary.rest_api_key'), config('onesignal.apps.secondary.user_auth_key'), config('onesignal.apps.secondary.guzzle_client_timeout') ); $primary->sendNotificationToAll("Hello from primary"); $secondary->sendNotificationToAll("Hello from secondary"); ``` -------------------------------- ### Testing Credentials Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/api-reference/OneSignalFacade.md A simple method to test the configured OneSignal credentials. ```php // Testing OneSignal::testCredentials(); ``` -------------------------------- ### Default OneSignal Configuration Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/api-reference/OneSignalServiceProvider.md The default configuration file for the OneSignal service provider, showing environment variable defaults. ```php return [ 'app_id' => env('ONESIGNAL_APP_ID'), 'rest_api_url' => env('ONESIGNAL_REST_API_URL', 'https://api.onesignal.com'), 'rest_api_key' => env('ONESIGNAL_REST_API_KEY'), 'user_auth_key' => env('USER_AUTH_KEY'), 'guzzle_client_timeout' => env('ONESIGNAL_GUZZLE_CLIENT_TIMEOUT', 0), ]; ``` -------------------------------- ### Player Structure for Creation/Update Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/types.md This structure is used for creating or updating player data. 'id' is required for updates, while 'device_type' is required for creation. 'app_id' is set automatically. ```php [ 'id' => string, // Required for updates, OneSignal player ID 'device_type' => integer, // Required for creation: 0-11 'app_id' => string, // Automatically set from config 'language' => string, // ISO-639-1 code (e.g., 'en') 'timezone' => string, // IANA timezone (e.g., 'America/New_York') 'external_user_id' => string, // Custom user ID 'tags' => array, // Custom tags/attributes 'test_type' => integer, // 1=Development, 2=Production ] ``` -------------------------------- ### Configure OneSignal Environment Variables Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/00-START-HERE.md Set your OneSignal application ID, REST API key, and user authentication key in your .env file. ```env ONESIGNAL_APP_ID=your-app-id ONESIGNAL_REST_API_KEY=your-rest-api-key USER_AUTH_KEY=your-user-auth-key ``` -------------------------------- ### Enable Guzzle HTTP Client Logging Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/errors.md Configure Guzzle to log HTTP requests and responses for debugging. This requires setting up a HandlerStack with a logging middleware. ```php use GuzzleHttp\Client; use GuzzleHttp\HandlerStack; use GuzzleHttp\Middleware; use Psr\Http\Message\RequestInterface; $handlerStack = HandlerStack::create(); $handlerStack->push(Middleware::log( Log::getMonolog(), new \GuzzleHttp\MessageFormatter() )); // Custom client initialization $client = new Client([ 'handler' => $handlerStack, ]); ``` -------------------------------- ### Resolving Facade from Service Container Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/api-reference/OneSignalFacade.md Shows how to manually resolve the OneSignal client from the Laravel service container using `app()` or dependency injection. ```php $client = app('onesignal'); $client->sendNotificationToAll("Hello"); // Or with dependency injection app()->make('onesignal')->sendNotificationToAll("Hello"); ``` -------------------------------- ### Internal Exception for Missing Device Type Source: https://github.com/berkayk/laravel-onesignal/blob/master/_autodocs/types.md This exception is thrown by the `createPlayer()` method when the `device_type` parameter is not provided. ```php // Exception thrown by createPlayer() when device_type is missing Exception: 'The `device_type` param is required as integer to create a player(device)' ```