onesignal/onesignal-php-api

There is no license information available for the latest version (dev-main) of this package.

A powerful way to send personalized messages at scale and build effective customer engagement strategies. Learn more at onesignal.com

dev-main 2023-08-02 00:01 UTC

This package is not auto-updated.

Last update: 2024-07-19 02:39:27 UTC


README

A powerful way to send personalized messages at scale and build effective customer engagement strategies. Learn more at onesignal.com

For more information, please visit https://onesignal.com.

Installation & Usage

Requirements

PHP 7.3 and later.

Composer

To install the bindings via Composer, add the following to composer.json:

{
  "repositories": [
    {
      "type": "vcs",
      "url": "https://github.com/OneSignal/onesignal-php-api.git"
    }
  ],
  "require": {
    "OneSignal/onesignal-php-api": "*@dev"
  }
}

Then run composer install

Usage examples

Imports

use DateTime;
use onesignal\client\api\DefaultApi;
use onesignal\client\Configuration;
use onesignal\client\model\GetNotificationRequestBody;
use onesignal\client\model\Notification;
use onesignal\client\model\StringMap;
use onesignal\client\model\Player;
use onesignal\client\model\UpdatePlayerTagsRequestBody;
use onesignal\client\model\ExportPlayersRequestBody;
use onesignal\client\model\Segment;
use onesignal\client\model\FilterExpressions;
use PHPUnit\Framework\TestCase;
use GuzzleHttp;

Constants

const APP_ID = '<YOUR_APP_ID>';
const APP_KEY_TOKEN = '<YOUR_APP_KEY_TOKEN>';
const USER_KEY_TOKEN = '<YOUR_USER_KEY_TOKEN>';

Configure authorization

$config = Configuration::getDefaultConfiguration()
    ->setAppKeyToken(APP_KEY_TOKEN)
    ->setUserKeyToken(USER_KEY_TOKEN);

$apiInstance = new DefaultApi(
    new GuzzleHttp\Client(),
    $config
);

Notifications

Creating a notification model

function createNotification($enContent): Notification {
    $content = new StringMap();
    $content->setEn($enContent);

    $notification = new Notification();
    $notification->setAppId(APP_ID);
    $notification->setContents($content);
    $notification->setIncludedSegments(['Subscribed Users']);

    return $notification;
}

Sending a notification immediately

$notification = createNotification('PHP Test notification');

$result = $apiInstance->createNotification($notification);
print_r($result);

Scheduling a notification to be sent in 24 hours

$notification = self::createNotification('PHP Test scheduled notification');
$dt = new DateTime();
$dt->modify('+1 day');
$notification->setSendAfter($dt);

$scheduledNotification = $apiInstance->createNotification($notification);
print_r($scheduledNotification);

Sending a notification using Filters

Send this notification only to the users that have not spent any USD on IAP.

$notification = createNotification('PHP Test filtered notification');
$filter1 = new Filter();
$filter1->setField('amount_spent');
$filter1->setRelation('=');
$filter1->setValue('0');
$notification->setFilters([$filter1]);
$result = $apiInstance->createNotification($notification);
print_r($result);

Sending a notification immediately

$notification = createNotification('PHP Test notification');

$result = $apiInstance->createNotification($notification);
print_r($result);

Retrieving a notification

$scheduledNotification = $apiInstance->getNotification(APP_ID, $scheduledNotification->getId());
print_r($scheduledNotification);

Listing notifications by application ID

$getResult = $apiInstance->getNotifications(APP_ID);
print_r($getResult->getNotifications());

Getting notification history

$requestBody = new GetNotificationRequestBody();
$requestBody
    ->setAppId(APP_ID)
    ->setEvents('sent');

$getResult = $apiInstance->getNotificationHistory($scheduledNotification->getId(), $requestBody);
print_r($getResult->getSuccess());

Players

Creating a new Player model

function createPlayerModel($playerId): Player {
    $player = new Player();

    $player->setAppId(APP_ID);
    $player->setIdentifier($playerId);
    $player->setDeviceType(1);

    return $player;
}

Creating a Player

$player = createPlayerModel('php_test_player_id');
$createPlayerResult = $apiInstance->createPlayer($player);
print_r($createPlayerResult);

Getting a Player

$getPlayerResult = $apiInstance->getPlayer(APP_ID, 'php_test_player_id');
print_r($getPlayerResult);

Getting a list of Players

$limit = 10;
$getPlayersResult = $apiInstance->getPlayers(APP_ID, $limit);
print_r($getPlayersResult->getPlayers());

Deleting a player

$deletePlayerResult = $apiInstance->deletePlayer(APP_ID, 'php_test_player_id');
print_r($deletePlayerResult->getSuccess());

Exporting players into CSV-spreadsheet

$exportPlayersRequestBody = new ExportPlayersRequestBody();
$exportPlayersRequestBody->setExtraFields([]);
$exportPlayersRequestBody->setSegmentName('');

$exportPlayersResult =  $apiInstance->exportPlayers(APP_ID, $exportPlayersRequestBody);
print_r($exportPlayersResult->getCsvFileUrl());

Segments

Creating a segment

// Settings up the filter. Filters determine a segment.
$filterExpressions = new FilterExpressions();
$filterExpressions->setField('session_count');
$filterExpressions->setRelation('>');
$filterExpressions->setValue('1');

Setting up the segment itself

$segment = new Segment();
$segment->setName('test_segment_name');
$segment->setFilters([$filterExpressions]);

$createSegmentResponse = $apiInstance->createSegments(APP_ID, $segment);
print_r($createSegmentResponse);

Deleting a segment

$deleteSegmentResponse = $apiInstance->deleteSegments(APP_ID, $createSegmentResponse->getId());
print_r($deleteSegmentResponse->getSuccess());

Working with Apps

Getting an app

$getAppResponse = $apiInstance->getApp(APP_ID);
print_r($getAppResponse);

Getting a list of apps

$getAppsResponse = $apiInstance->getApps();
print_r($getAppsResponse);

Updating an app

$getAppResponse = $apiInstance->getApp(APP_ID);
$getAppResponse->setName('php_test_app_name');
$updateAppResponse = $apiInstance->updateApp(APP_ID, $getAppResponse);
print_r($updateAppResponse);

Outcomes

$outcomeNames = "os__session_duration.count,os__click.count";
$outcomeTimeRange = "1d";
$outcomePlatforms = "5";
$outcomeAttribution = "direct";
$outcomesResponse = $apiInstance->getOutcomes(APP_ID, $outcomeNames, null, $outcomeTimeRange, $outcomePlatforms, $outcomeAttribution);
print_r($outcomesResponse->getOutcomes());

Live Activities

Begin Live Activity

$activityId = "activity_id_example";
$beginLiveActivityRequest = new BeginLiveActivityRequest(array(
    'push_token' => "push_token_example",
    'subscription_id' => "player_id_example"
));

self::$apiInstance->beginLiveActivity(APP_ID, $activityId, $beginLiveActivityRequest);

Update Live Activity

$activityId = "activity_id_example";
$updateLiveActivityRequest = new UpdateLiveActivityRequest(array(
    'event' => 'update',
    'name' => 'contents',
    'event_updates' => array('data' => 'test')
));

self::$apiInstance->updateLiveActivity(APP_ID, $activityId, $updateLiveActivityRequest);

End Live Activity

$activityId = "activity_id_example";
$subscriptionId = "player_id_example";
self::$apiInstance->endLiveActivity(APP_ID, $activityId, $subscriptionId);

Users

Creating a user

// Create user model
$user = new User();
$aliasLabel = '<ALIAS_LABEL>';
$aliasId = '<ALIAS_ID>';
$pushToken = '<DEVICE_PUSH_TOKEN>';

$subscriptionObject = new SubscriptionObject();
$subscriptionObject->setType('iOSPush');
$subscriptionObject->setToken($pushToken);

$user->setIdentity(array($aliasLabel => $aliasId));
$user->setSubscriptions([$subscriptionObject]);

// Send model to API
$createUserResponse = self::$apiInstance->createUser(APP_ID, $user);

Fetch user by an alias

$fetchUserResponse = self::$apiInstance->fetchUser(APP_ID, $aliasLabel, $aliasId);

Update user

$updateUserRequest = new UpdateUserRequest(array(
    'properties' => array(
        'language' => 'fr'
    ))
);

$updateUserResponse = self::$apiInstance->updateUser(APP_ID, $aliasLabel, $aliasId, $updateUserRequest);

Delete user

self::$apiInstance->deleteUser(APP_ID, $aliasLabel, $aliasId);

Create subscription

$createSubscriptionRequestBody = new CreateSubscriptionRequestBody();
$subscriptionObject = new SubscriptionObject();
$subscriptionObject->setType('AndroidPush');
$subscriptionObject->setToken('DEVICE_PUSH_TOKEN');
$createSubscriptionRequestBody->setSubscription($subscriptionObject);

$createSubscriptionResponse =
    self::$apiInstance->createSubscription(APP_ID, $aliasLabel, $aliasId, $createSubscriptionRequestBody);

Update subscription

$updateSubscriptionRequestBody = new UpdateSubscriptionRequestBody();
$subscriptionObject = new SubscriptionObject();
$subscriptionObject->setType('AndroidPush');
$subscriptionObject->setToken('DEVICE_PUSH_TOKEN'
$updateSubscriptionRequestBody->setSubscription($subscriptionObject);

self::$apiInstance->updateSubscription(APP_ID, $subscriptionId, $updateSubscriptionRequestBody);

Delete subscription

self::$apiInstance->deleteSubscription(APP_ID, '<SUBSCRIPTION_ID>');

Delete Alias

self::$apiInstance->deleteAlias(APP_ID, '<ALIAS_LABEL>', '<ALIAS_ID>', '<ALIAS_LABEL_TO_DELETE>');

Fetch aliases by subscription id

$fetchAliasesResponse = self::$apiInstance->fetchAliases(APP_ID, '<SUBSCRIPTION_ID>');

Fetch aliases by another alias

$fetchAliasesResponse = self::$apiInstance->fetchUserIdentity(APP_ID, '<ALIAS_LABEL>', '<ALIAS_ID>');

Identify user by subscription id

$userIdentityRequestBody = new UserIdentityRequestBody();

$userIdentityRequestBody->setIdentity(array(
    '<NEW_ALIAS_LABEL>' => '<NEW_ALIAS_ID>'
));

// Act
$fetchAliasesResponse = self::$apiInstance->identifyUserBySubscriptionId(
    APP_ID, '<SUBSCRIPTION_ID>', $userIdentityRequestBody);

Identify user by another alias

$userIdentityRequestBody = new UserIdentityRequestBody();

$userIdentityRequestBody->setIdentity(array(
    '<NEW_ALIAS_LABEL>' => '<NEW_ALIAS_ID>'
));

// Act
$fetchAliasesResponse = self::$apiInstance->identifyUserByAlias(
    APP_ID, '<ALIAS_LABEL>', '<ALIAS_ID>', $userIdentityRequestBody);

Transfer subscription to another user

$transferSubscriptionRequestBody = new TransferSubscriptionRequestBody();
$transferSubscriptionRequestBody->setIdentity(array('<USER_FROM_ALIAS_LABEL>' => '<USER_FROM_ALIAS_ID>'));

// Act
$transferSubscriptionResponse = self::$apiInstance->transferSubscription(
    APP_ID, '<USER_TO_SUBSCRIPTION_ID>', $transferSubscriptionRequestBody);

Fetch in app messages

$getEligibleIamsResponse = self::$apiInstance->getEligibleIams(APP_ID, '<SUBSCRIPTION_ID>');

API Endpoints

All URIs are relative to https://onesignal.com/api/v1

Models

Authorization

All the OneSignal endpoints require either an app_key or user_key tokens for authorization. It is recommended to set up both of those keys during the initial config initialization so that you don't need to worry about which endpoint requires app_key and which user_key. You can get the value of these keys from your app dashboard and user settings pages.

app_key

  • Type: Bearer authentication

user_key

  • Type: Bearer authentication

Author

devrel@onesignal.com

  • API version: 1.2.2
    • Package version: 2.0.2