CPP Client SDK
The OneSignal CPP API Library allows for your backend CPP application to integrate with OneSignal for backend events, data, and more.
Backend SDKs in User Model Beta
You still can try using new User Model endpoints, we advise customers to not use these SDKs in production.
Overview
- Build package: org.openapitools.codegen.languages.CppRestSdkClientCodegen
- API namespace: com.onesignal.client.api
- Model namespace: com.onesignal.client.model
- GitHub repository https://github.com/onesignal/onesignal-cpp-api
Installation
Prerequisites
Install cpprestsdk.
- Windows:
vcpkg install cpprestsdk cpprestsdk:x64-windows boost-uuid boost-uuid:x64-windows
- Mac:
brew install cpprestsdk
brew install openssl
- Linux:
sudo apt-get install libcpprest-dev
Cmake integration
You can cmake --install .
and then use find_package(CppRestOneSignalAPIClient REQUIRED)
.
Alternatively you can have it as a subdirectory as in the example below.
Take a look on our test CMakeLists.txt
:
cmake_minimum_required(VERSION 3.22)
project(CppRestOneSignalAPIClientTest)
set(CMAKE_CXX_STANDARD 14)
# Test dependencies
find_package(Catch2 REQUIRED)
# OneSignal Client Library
add_subdirectory(deps/onesignal)
# Executables for tests
add_executable(tests test.cpp)
target_link_libraries(tests Catch2::Catch2 CppRestOneSignalAPIClient)
Build
cmake -DCMAKE_CXX_FLAGS="-I/usr/local/include -I/usr/local/Cellar/include -I/usr/local/opt/include" \
-DCMAKE_MODULE_LINKER_FLAGS="-L/usr/local/lib -L/usr/local/Cellar/lib -L/usr/local/opt/lib" \
-DCMAKE_EXE_LINKER_FLAGS="-L/usr/local/lib -L/usr/local/Cellar/lib -L/usr/local/opt/lib -L/usr/local/opt/openssl/lib" \
-DOPENSSL_ROOT_DIR=/usr/local/opt/openssl \
-DOPENSSL_LIBRARIES=/usr/local/opt/openssl/lib \
make
Note, if you are getting compilation errors related to missing dependencies, and you installed them using different package managers
like Homebrew, you may need to alter cmake flags with appropriate paths.
Build on Windows with Visual Studio (VS2017)
- Right click on folder containing source code
- Select 'Open in visual studio'
- Once visual studio opens, CMake should show up in top menu bar.
- Select CMake > Build All.
*Note: If the CMake menu item doesn't show up in Visual Studio, CMake
for Visual Studio must be installed. In this case, open the 'Visual Studio
Installer' application. Select 'modify' Visual Studio 2017. Make sure
'Desktop Development with C++' is installed, and specifically that 'Visual
C++ tools for CMake' is selected in the 'Installation Details' section.
Also be sure to review the CMakeLists.txt file. Edits are likely required.*
How to use
Initializing the OneSignal CPP Client library
#include "CppRestOneSignalAPIClient/ApiClient.h"
#include "CppRestOneSignalAPIClient/ApiConfiguration.h"
#include "CppRestOneSignalAPIClient/api/DefaultApi.h"
using com::onesignal::client::api::ApiClient;
using com::onesignal::client::api::ApiConfiguration;
using com::onesignal::client::api::DefaultApi;
using utility::string_t;
using utility::conversions::to_string_t;
const std::string APP_ID = "<YOUR_APP_ID>";
const std::string APP_KEY_TOKEN = "<YOUR_API_KEY>";
const std::string USER_KEY_TOKEN = "<YOUR_USER_KEY_TOKEN>";
static DefaultApi * createApi() {
// Settings up the client
const auto configuration = ApiClient::getDefaultConfiguration();
configuration->setAppKeyToken(APP_KEY_TOKEN);
configuration->setUserKeyToken(USER_KEY_TOKEN);
const auto apiClient = std::make_shared<ApiClient>(configuration);
return new DefaultApi(apiClient);
}
If you use this library synchronously, make sure you call .get() to wait for the response and wrap it in a try-catch block, so you can see the errors if there are any.
Creating a notification model
static std::shared_ptr<Notification> createNotification() {
const auto notification = std::make_shared<Notification>();
notification->setAppId(APP_ID);
const auto content = std::make_shared<StringMap>();
content->setEn(to_string_t("OneSignal C++ Client Test: Create notification"));
std::vector<string_t> vect{ to_string_t("Active Users") };
notification->setContents(content);
notification->setIncludedSegments(vect);
notification->setIsAnyWeb(true);
notification->setIsChrome(true);
return notification;
}
Sending a notification using Filters
const auto api = createApi();
std::vector<std::shared_ptr<Filter>> filters;
// Creating a notification
const auto notification = createNotification();
// Find all the users that have not spent any amount in USD on IAP.
// https://documentation.onesignal.com/reference/create-notification#send-to-users-based-on-filters
const auto filter1 = std::make_shared<Filter>();
filter1->setField(to_string_t("amount_spent"));
filter1->setRelation(to_string_t("="));
filter1->setValue("0");
filters.push_back(filter1);
notification->setFilters(filters);
// Send a notification
const auto response = api->createNotification(notification);
const auto & responseData = response.get();
// Check the result
CHECK(responseData->getId().size() > 0);
CHECK_FALSE(responseData->errorsIsSet());
Sending a notification
const auto api = createApi();
// Creating a notification
const auto notification = createNotification();
// Send a notification
const auto response = api->createNotification(notification);
const auto & responseData = response.get();
// Check the result
CHECK(responseData->getId().size() > 0);
CHECK_FALSE(responseData->errorsIsSet());
Sending and canceling scheduled notification
const auto api = createApi();
// Create a scheduled notification
const auto notification = createNotification();
notification->setSendAfter(utility::datetime().utc_now() + utility::datetime().from_hours(1));
// Send a notification
const auto sendResponse = api->createNotification(notification);
const auto & sendResponseData = sendResponse.get();
// Cancel a scheduled notification
const auto cancelResponse = api->cancelNotification(APP_ID, sendResponseData->getId());
const auto & cancelResponseData = cancelResponse.get();
// Check the result
CHECK(cancelResponseData->isSuccess());
Getting a notification
const auto api = createApi();
// Get a notification
const auto getResponse = api->getNotification(APP_ID, "<your_notification_id>");
const auto & getResponseData = getResponse.get();
// Check the result
CHECK(getResponseData->getId() == sendResponseData->getId());
Getting a list of notifications
const auto api = createApi();
// Creating a notification
const auto notification = createNotification();
// Get list of notification with the limit of 10
const auto getResponse = api->getNotifications(APP_ID, 10, boost::none, boost::none);
const auto & notificationSlice = getResponse.get();
// Check the result
CHECK(notificationSlice->getNotifications().size() == 10);
Creating and getting a player
static std::shared_ptr<Player> createPlayer() {
const auto player = std::make_shared<Player>();
player->setAppId(APP_ID);
player->setIdentifier("Id_example");
player->setDeviceType(1);
return player;
}
const auto api = createApi();
// Creating a player
const auto player = createPlayer();
// Send a create request
const auto createResponse = api->createPlayer(player);
const auto & createResponseData = createResponse.get();
// Send a get request
const auto getResponse = api->getPlayer(APP_ID, createResponseData->getId(), boost::none);
const auto & getResponseData = getResponse.get();
CHECK(createResponseData->isSuccess());
CHECK(getResponseData->getId() == createResponseData->getId());
Creating and deleting a segment
static std::shared_ptr<Segment> createSegment(string_t segmentName) {
// Setting up filters
const auto filterExpressions = std::make_shared<FilterExpressions>();
filterExpressions->setField(to_string_t("session_count"));
filterExpressions->setRelation(to_string_t(">"));
filterExpressions->setValue("1");
std::vector<std::shared_ptr<FilterExpressions>> vect;
vect.push_back(filterExpressions);
// Setting up the segment
const auto segment = std::make_shared<Segment>();
segment->setName(segmentName);
segment->setFilters(vect);
return segment;
}
const auto api = createApi();
// Creating a segment
const auto segment = createSegment("<test_segment_name>");
// Send a create request
const auto createResponse = api->createSegments(APP_ID, segment).get();
sleep(10);
// Send a delete request
const auto deleteResponse = api->deleteSegments(APP_ID, createResponse->getId()).get();
// Check the result
CHECK(deleteResponse->isSuccess());
Getting an App
const auto api = createApi();
// Send a get request
const auto app = api->getApp(APP_ID).get();
// Check the result
CHECK(app->getId() == APP_ID);
Getting outcomes
const auto api = createApi();
// Set up the request
const auto outcomeNames = to_string_t("os__session_duration.count,os__click.count");
const auto outcomeTimeRange = to_string_t("1d");
const auto outcomePlatforms = to_string_t("5");
const auto outcomeAttribution = to_string_t("direct");
// Send the request
const auto outcomesResponse = api->getOutcomes(APP_ID,
outcomeNames,
boost::none,
outcomeTimeRange,
outcomePlatforms,
outcomeAttribution);
const auto outcomes = outcomesResponse.get()->getOutcomes();
// Check the result
CHECK(outcomes.size() > 0);
Begin Live Activity event
const auto beginLiveActivityRequest = std::make_shared<BeginLiveActivityRequest>();
beginLiveActivityRequest->setPushToken("push_token_example");
beginLiveActivityRequest->setSubscriptionId("player id example");
api->beginLiveActivity(APP_ID, "activity id example", beginLiveActivityRequest);
Update Live Activity event
const auto updateLiveActivityRequest = std::make_shared<UpdateLiveActivityRequest>();
updateLiveActivityRequest->setName("contents");
updateLiveActivityRequest->setEvent("update");
const auto eventUpdates = std::make_shared<Object>();
eventUpdates->setValue(to_string_t("data"), 1);
updateLiveActivityRequest->setEventUpdates(eventUpdates);
api->updateLiveActivity(APP_ID, "activity id example", updateLiveActivityRequest);
End Live Activity event
api->endLiveActivity(APP_ID, "activity id example", "player id example");
Users
Create User
// Creating a user model to be send to the server
const auto user = std::make_shared<User>();
const auto aliasLabel = "<ALIAS_LABEL>";
const auto aliasId = "<ALIAS_ID>";
const auto pushToken = "<DEVICE_PUSH_TOKEN>";
std::map<utility::string_t, utility::string_t> identity = {};
identity[aliasLabel] = aliasId;
user->setIdentity(identity);
com::onesignal::client::model::SubscriptionObject subscriptionObject;
subscriptionObject.setToken(pushToken);
subscriptionObject.setType("iOSPush");
std::vector<std::shared_ptr<com::onesignal::client::model::SubscriptionObject>> subscriptions = {
std::make_shared<com::onesignal::client::model::SubscriptionObject>(subscriptionObject)
};
// Sending to to the server
const auto createUserResponse = api->createUser(APP_ID, user).get();
Fetch user by alias
const auto fetchUserResponse = api->fetchUser(APP_ID, <ALIAS_LABEL>, <ALIAS_ID>).get();
Update user
const auto updateUserRequest = std::make_shared<UpdateUserRequest>();
const auto propertiesObject = std::make_shared<PropertiesObject>();
propertiesObject->setLanguage("fr");
updateUserRequest->setProperties(propertiesObject);
const auto updateUserResponse = api->updateUser(APP_ID, "<ALIAS_LABEL>", "<ALIAS_ID>", updateUserRequest).get();
CHECK(updateUserResponse->getProperties()->getLanguage() == "fr");
Delete user
api->deleteUser(APP_ID, "<ALIAS_LABEL>", "<ALIAS_ID>").get();
Create subscription
const auto subscriptionObject = std::make_shared<SubscriptionObject>();
subscriptionObject->setType("AndroidPush");
subscriptionObject->setToken("<DEVICE_PUSH_TOKEN>");
const auto createSubscriptionRequestBody = std::make_shared<CreateSubscriptionRequestBody>();
createSubscriptionRequestBody->setSubscription(subscriptionObject);
const auto createSubscriptionResponse = api->createSubscription(APP_ID, "<ALIAS_LABEL>", "<ALIAS_ID>",
createSubscriptionRequestBody).get();
CHECK(createSubscriptionResponse->getSubscription()->getToken().length() != 0);
Update subscription
subscriptionObject->setType("AndroidPush");
subscriptionObject->setToken("<DEVICE_PUSH_TOKEN>");
const auto updateSubscriptionRequestBody = std::make_shared<UpdateSubscriptionRequestBody>();
updateSubscriptionRequestBody->setSubscription(subscriptionObject);
api->updateSubscription(APP_ID, "<SUBSCRIPTION_ID>", updateSubscriptionRequestBody).get();
Delete subscription
api->deleteSubscription(APP_ID, "<SUBSCRIPTION_ID>").get();
Fetch aliases by subscription id
const auto fetchAliasesResponse = api->fetchAliases(APP_ID, "<SUBSCRIPTION_ID>").get();
Fetch aliases by an alias
const auto fetchUserIdentityResponse = api->fetchUserIdentity(APP_ID, "<ALIAS_LABEL>", "<ALIAS_ID>").get();
Fetch aliases by subscription id
const auto fetchAliasesResponse = api->fetchAliases(APP_ID, "<SUBSCRIPTION_ID>").get();
Identify user by subscription id
Basically means that you want to add an alias to the user using subscription id.
const auto subscriptionId = "<SUBSCRIPTION_ID>";
const auto newAliasLabel = "<NEW_ALIAS_LABEL>";
const auto newAliasId = "<NEW_ALIAS_ID>";
std::map<utility::string_t, utility::string_t> identity = {};
identity[newAliasLabel] = newAliasId;
user->setIdentity(identity);
const auto userIdentityRequestBody = std::make_shared<UserIdentityRequestBody>();
userIdentityRequestBody->setIdentity(identity);
const auto identifyUserBySubscriptionIdResponse =
api->identifyUserBySubscriptionId(APP_ID, subscriptionId, userIdentityRequestBody).get();
CHECK(identifyUserBySubscriptionIdResponse->getIdentity()[newAliasLabel] == newAliasId);
Identify user by an alias
Basically means that you want to add an alias to the user using another alias.
const auto subscriptionId = "<SUBSCRIPTION_ID>";
const auto newAliasLabel = "<NEW_ALIAS_LABEL>";
const auto newAliasId = "<NEW_ALIAS_ID>";
std::map<utility::string_t, utility::string_t> identity = {};
identity[newAliasLabel] = newAliasId;
user->setIdentity(identity);
const auto userIdentityRequestBody = std::make_shared<UserIdentityRequestBody>();
userIdentityRequestBody->setIdentity(identity);
const auto identifyUserBySubscriptionIdResponse =
api->identifyUserByAlias(APP_ID, "<ALIAS_LABEL>", "<ALIAS_ID>", userIdentityRequestBody).get();
CHECK(identifyUserBySubscriptionIdResponse->getIdentity()[newAliasLabel] == newAliasId);
Transfers subscription ownership
const auto transferSubscriptionRequestBody = std::make_shared<TransferSubscriptionRequestBody>();
std::map<utility::string_t, utility::string_t> identity = {};
identity["<USER_FROM_ALIAS_LABEL>"] = "<USER_FROM_ALIAS_ID>";
transferSubscriptionRequestBody->setIdentity(identity);
const auto identifyUserByAliasResponse =
api->transferSubscription(APP_ID, "<USER_TO_SUBSCRIPTION_ID>", transferSubscriptionRequestBody).get();
Fetch IAMs
api->getEligibleIams(APP_ID, "<SUBSCRIPTION_ID>").get();
Updated 5 months ago