Create notification
Sends notifications to your users
The Create Notification method is used when you want your server to programmatically send notifications or emails to a segment or individual users. You may target users in one of three ways using this method: by Segment, by Filter, or by Device. At least one targeting parameter must be specified.
You may only use one method of targeting users
If a targeting parameter of one type is used, then targeting parameters from other types may not be used. For instance, you cannot use the included_segments
parameter (from segments) with the filters
.
Send to Segments
Segments are the most common way developers send notifications via OneSignal. Sending to segments is easy: you simply specify which segments you want to send to, and, optionally, which ones you don't.
included_segments
array_string
Required The segment names you want to target. Users in these segments will receive a notification. This targeting parameter is only compatible with excluded_segments
.
Example: ["Active Users", "Inactive Users"]
excluded_segments
array_string
Segment that will be excluded when sending. Users in these segments will not receive a notification, even if they were included in included_segments
. This targeting parameter is only compatible with included_segments
.
Example: ["Active Users", "Inactive Users"]
Requires Authentication Key
Requires your OneSignal App's REST API Key, available in Keys & IDs.
Segments Usage
- Tip: If you want to send to all your subscribed users, use any segment that has no filters. See Segments for information on how to identify which segments you have as well as information about built-in segments that OneSignal will create for every app.
Send to Users Based on Filters
Filters are a powerful way to target users, allowing you to use both data that OneSignal has about a user and any Tags your app may send OneSignal. Filters can be combined together to form advanced, highly precise user targeting. OneSignal customers use all sorts of filters to send notifications, including language, location, user activity, and more.
The filters
parameter targets notification recipients using an array of JSON objects containing field conditions to check. The following are filter field options:
last_session
relation
= ">"
or "<"
hours_ago
= number of hours before or after the users last session. Example: "1.1"
first_session
relation
= ">"
or "<"
hours_ago
= number of hours before or after the users first session. Example: "1.1"
session_count
relation
= ">"
, "<"
, "="
or "!="
value
= number sessions. Example: "1"
session_time
relation
= ">"
or "<"
value
= Time in seconds the user has been in your app. Example: "3600"
amount_spent
relation
= ">"
, "<"
, or "="
value
= Amount in USD a user has spent on IAP (In App Purchases). Example: "0.99"
bought_sku
relation
= ">"
, "<"
or "="
key
= SKU purchased in your app as an IAP (In App Purchases). Example: "com.domain.100coinpack"
value
= value of SKU to compare to. Example: "0.99"
tag
relation
= ">"
, "<"
, "="
, "!="
, "exists"
, "not_exists"
, "time_elapsed_gt"
(paid plan only) or "time_elapsed_lt"
(paid plan only) See Time Operatorskey
= Tag key to compare.value
= Tag value to compare. Not required for "exists"
or "not_exists"
. Example: See Formatting Filters
language
relation
= "="
or "!="
value
= 2 character language code. Example: "en"
. For a list of all language codes go here
app_version
relation
= ">"
, "<"
, "="
or "!="
value
= app version. Example: "1.0.0"
location
radius
= in meterslat
= latitudelong
= longitude
email
value
= email address
Only for sending Push Notifications
Use this for targeting push subscribers associated with an email set with all SDK setEmail
methods
To send emails to specific email addresses use include_email_tokens
parameter
country
relation
= "="
value
= 2-digit Country code
Example: "field": "country", "relation": "=", "value", "US"
Requires Authentication Key
Requires your OneSignal App's REST API Key, available in Keys & IDs.
Filter Usage
- Filter entries use
AND
by default; insert{"operator": "OR"}
between entries toOR
the parameters together. - For performance reasons, a maximum of 200 entries can be used at a time. The 200 entries limit includes the "field" entry and "OR" entries -- each would count towards the 200 limit.
Below, "Formatting Example 1" would be 2 entries and "Formatting Example 2" would be 3 entries. - This filter targeting parameter cannot be combined with any other targeting parameters.
Formatting Filters
The power of filters comes from combining several fields and operators to precisely target your users. The following are examples of filters and how to format them:
A user is level 10 and purchased an item
A user is level 10 or 20
A user is not VIP or is admin
User's tags include key username and the user is not banned.
[
{"field": "tag", "key": "level", "relation": ">", "value": "10"},
{"field": "amount_spent", "relation": ">","value": "0"}
]
[
{"field": "tag", "key": "level", "relation": "=", "value": "10"},
{"operator": "OR"}, {"field": "tag", "key": "level", "relation": "=", "value": "20"}
]
[
{"field": "tag", "key": "is_vip", "relation": "!=", "value": "true"},
{"operator": "OR"}, {"field": "tag","key": "is_admin", "relation": "=", "value": "true"}
]
[
{"field": "tag", "key": "username", "relation": "exists"},
{"field": "tag", "key": "banned", "relation": "!=", "value": "true"}
]
Note: ANDs have priority over ORs.
Send to Specific Devices
Finally, you may also target specific devices with the create notification method. Targeting devices is typically used in two ways:
For notifications that target individual users, such as if they've received a message from someone.
For apps that wish to manage their own segments, such as tracking a user's followers and sending notifications to them when that user posts.
When targeting specific devices, you may use any of the following parameters together:
include_player_ids
array_string
Recommended - Specific players to send your notification to. Does not require API Auth Key.
Do not combine with other targeting parameters. Not compatible with any other targeting parameters. Example: ["1dd608f2-c6a1-11e3-851d-000c2940e62c"]
Limit of 2,000 entries per REST API call
include_external_user_ids
array_string
Recommended - Target specific devices by custom user IDs assigned via API. Not compatible with any other targeting parameters
Example: [“custom-id-assigned-by-api”]
REQUIRED: REST API Key Authentication
Limit of 2,000 entries per REST API call.
Note: If targeting push and email subscribers with same ids, use with channel_for_external_user_ids to indicate you are sending a push or email.
include_email_tokens
array_string
Recommended - For Sending Emails - Target specific email addresses. If an email does not correspond to an existing user, a new user will be created. Example: nick@catfac.ts
Limit of 2,000 entries per REST API call
include_ios_tokens
array_string
Not Recommended - Please consider using include_player_ids
instead.
Target using iOS device tokens. Warning: Only works with Production tokens.
All non-alphanumeric characters must be removed from each token. If a token does not correspond to an existing user, a new user will be created. Example: ce777617da7f548fe7a9ab6febb56cf39fba6d38203...
Limit of 2,000 entries per REST API call
include_wp_wns_uris
array_string
Not Recommended Please consider using include_player_ids
instead.
Target using Windows URIs. If a token does not correspond to an existing user, a new user will be created. Example: http://s.notify.live.net/u/1/bn1/HmQAAACPaLDr-...
Limit of 2,000 entries per REST API call
include_amazon_reg_ids
array_string
Not Recommended Please consider using include_player_ids
instead.
Target using Amazon ADM registration IDs. If a token does not correspond to an existing user, a new user will be created. Example: amzn1.adm-registration.v1.XpvSSUk0Rc3hTVVV...
Limit of 2,000 entries per REST API call
include_chrome_reg_ids
array_string
Not Recommended Please consider using include_player_ids
instead.
Target using Chrome App registration IDs. If a token does not correspond to an existing user, a new user will be created. Example: APA91bEeiUeSukAAUdnw3O2RB45FWlSpgJ7Ji_...
Limit of 2,000 entries per REST API call
include_chrome_web_reg_ids
array_string
Not Recommended Please consider using include_player_ids
instead, as web push registration IDs can vary over time where OneSignal player IDs remain constant.
Target using Chrome Web Push registration IDs. If a token does not correspond to an existing user, a new user will be created. Example: APA91bEeiUeSukAAUdnw3O2RB45FWlSpgJ7Ji_...
Limit of 2,000 entries per REST API call
include_android_reg_ids
array_string
Not Recommended Please consider using include_player_ids
instead, as android tokens occasionally change, which causes devices to become invalid and limits your audience.
Target using Android device registration IDs. If a token does not correspond to an existing user, a new user will be created. Example: APA91bEeiUeSukAAUdnw3O2RB45FWlSpgJ7Ji_...
Limit of 2,000 entries per REST API call
Requires Authentication Key
NEVER use your 'REST API key' in client code, it is intended for use on your system or server only. Add the REST API Key to the HTTP 'Authorization' header as basic authentication.
Common Parameters
The following are parameters in Create Notifications common to all methods of targeting users.
App
app_id
string
All
Required
Your OneSignal application ID, which can be found in Keys & IDs. It is a UUID and looks similar to 8250eaf6-1a58-489e-b136-7c74a864b434
.
external_id
string (UUID)
All
Correlation and idempotency key.
A request received with this parameter will first look for another notification with the same external_id
. If one exists, a notification will not be sent, and result of the previous operation will instead be returned. Therefore, if you plan on using this feature, it's important to use a good source of randomness to generate the UUID passed here.
This key is only idempotent for 30 days. After 30 days, the notification could be removed from our system and a notification with the same external_id
will be sent again.
See Idempotent Notification Requests for more details
Content & Language
Notification Content
If you are sending push notifications, use the following parameters. Read more: supported languages.
contents
object
All
Required unless content_available=true
or template_id
is set.
The notification's content (excluding the title), a map of language codes to text for each language.
Each hash must have a language code string for a key, mapped to the localized text you would like users to receive for that language.
This field supports inline substitutions.
English must be included in the hash.
Example: {"en": "English Message", "es": "Spanish Message"}
headings
object
All
The notification's title, a map of language codes to text for each language. Each hash must have a language code string for a key, mapped to the localized text you would like users to receive for that language.
This field supports inline substitutions.
Example: {"en": "English Title", "es": "Spanish Title"}
subtitle
object
iOS 10+
The notification's subtitle, a map of language codes to text for each language. Each hash must have a language code string for a key, mapped to the localized text you would like users to receive for that language.
This field supports inline substitutions.
Example: {"en": "English Subtitle", "es": "Spanish Subtitle"}
template_id
string
All
Use a template you setup on our dashboard. The template_id is the UUID found in the URL when viewing a template on our dashboard.
Example: be4a8044-bbd6-11e4-a581-000c2940e62c
content_available
boolean
iOS
Sending true
wakes your app from background to run custom native code (Apple interprets this as content-available=1
). Note: Not applicable if the app is in the "force-quit" state (i.e app was swiped away). Omit the contents
field to prevent displaying a visible notification.
mutable_content
boolean
iOS 10+
Always defaults to true
and cannot be turned off. Allows tracking of notification receives and changing of the notification content in your app before it is displayed. Triggers didReceive(_:withContentHandler:)
on your UNNotificationServiceExtension.
email_subject
string
Required The subject of the email.
email_body
string (HTML supported)
Required unless template_id
is set.
The body of the email you wish to send. Typically, customers include their own HTML templates here. Must include [unsubscribe_url]
in an <a>
tag somewhere in the email.
Note: any malformed HTML content will be sent to users. Please double-check your HTML is valid.
email_from_name
string
The name the email is from. If this is not specified, this will use your default from name set in Email Setup.
email_from_address
string (valid email address)
The email address the email is from. If this is not specified, this will use your default from email in Email Setup.
Attachments
These are additional content attached to push notifications, primarily images.
data
object
All
A custom map of data that is passed back to your app.
Example: {"abc": "123", "foo": "bar"}
url
string
All
The URL to open in the browser when a user clicks on the notification.
Example: http://www.google.com
Note: iOS needs https or updated NSAppTransportSecurity in plist
This field supports inline substitutions.
Omit if including web_url
or app_url
web_url
string
All Browsers
Same as url
but only sent to web push platforms.
Including Chrome, Firefox, Safari, Opera, etc.
app_url
string
All Apps
Same as url
but only sent to app platforms.
Including iOS, Android, macOS, Windows, ChromeApps, etc.
ios_attachments
object
iOS 10+
Adds media attachments to notifications. Set as JSON object, key as a media id of your choice and the value as a valid local filename or URL. User must press and hold on the notification to view.
Do not set mutable_content
to download attachments. The OneSignal SDK does this automatically
Example: {"id1": "https://domain.com/image.jpg"}
big_picture
string
Android
Picture to display in the expanded view. Can be a drawable resource name or a URL.
adm_big_picture
string
Amazon
Picture to display in the expanded view. Can be a drawable resource name or a URL.
chrome_big_picture
string
ChromeApp
Large picture to display below the notification text. Must be a local URL.
Action Buttons
These add buttons to push notifications, allowing the user to take more than one action on a notification. Learn more about Action Buttons.
buttons
array_object
iOS 8.0+, Android 4.1+ (and derivatives like Amazon)
Buttons to add to the notification. Icon only works for Android.
Example: [{"id": "id1", "text": "button1", "icon": "ic_menu_share"}, {"id": "id2", "text": "button2", "icon": "ic_menu_send"}]
Swift Example: [["id": "id1", "text": "button1"], ["id": "id2", "text": "button2"]]
web_buttons
array_object
Chrome 48+
Add action buttons to the notification. The id
field is required.
Example: [{"id": "like-button", "text": "Like", "icon": "http://i.imgur.com/N8SN8ZS.png", "url": "https://yoursite.com"}, {"id": "read-more-button", "text": "Read more", "icon": "http://i.imgur.com/MIxJp1L.png", "url": "https://yoursite.com"}]
ios_category
string
iOS
Category APS payload, use with registerUserNotificationSettings:categories
in your Objective-C / Swift code.
Example: calendar
category which contains actions like accept
and decline
iOS 10+ This will trigger your UNNotificationContentExtension whose ID matches this category.
Appearance
These parameters let you adjust icons, sounds, badges, and other appearance changes to your push notifications.
Icons - Different platforms handle icons differently.
- Android - Our SDK shows a bell icon by default. See our Android Notification Icons guide to change this.
- iOS - The icon will always be your app icon. Apple does not allow this to be configured.
Sounds - By default, the device notification sound plays when a new notification arrives. You may alter this by specifying a different sound asset.
Badges - shows the number of notifications outstanding. Note: Android badges are automatically handled by OneSignal.
android_channel_id
UUID
Android
The Android Oreo Notification Category to send the notification under. See the Category documentation on creating one and getting it's id.
existing_android_channel_id
string
Android
Use this if you have client side Android Oreo Channels you have already defined in your app with code.
android_background_layout
object
Android
Allowing setting a background image for the notification. This is a JSON object containing the following keys. See our Background Image documentation for image sizes.
image
- Asset file, android resource name, or URL to remote image.
headings_color
- Title text color ARGB Hex format. Example(Blue): "FF0000FF"
.
contents_color
- Body text color ARGB Hex format. Example(Red): "FFFF0000"
Example: {"image": "https://domain.com/background_image.jpg", "headings_color": "FFFF0000", "contents_color": "FF00FF00"}
small_icon
string
Android
If not set a bell icon will be used or ic_stat_onesignal_default
if you have set this resource name.
See: How to create small icons
large_icon
string
Android
If blank the small_icon
is used. Can be a drawable resource name or a URL.
See: How to create large icons
adm_small_icon
string
Amazon
If not set a bell icon will be used or ic_stat_onesignal_default
if you have set this resource name.
See: How to create small icons
adm_large_icon
string
Amazon
If blank the small_icon
is used. Can be a drawable resource name or a URL.
See: How to create large icons
chrome_web_icon
string
Chrome
Sets the web push notification's icon. An image URL linking to a valid image. Common image types are supported; GIF will not animate. We recommend 256x256 (at least 80x80) to display well on high DPI devices. Firefox will also use this icon, unless you specify firefox_icon
.
chrome_web_image
string
Chrome 56+ Only
Sets the web push notification's large image to be shown below the notification's title and text. Please see Web Push Notification Icons.
chrome_web_badge
string
Chrome 56+ Only
Sets the web push notification icon for Android devices in the notification shade. Please see Web Push Notification Badge.
firefox_icon
string
Firefox
Not recommended Few people need to set Firefox-specific icons. We recommend setting chrome_web_icon
instead, which Firefox will also use.
Sets the web push notification's icon for Firefox. An image URL linking to a valid image. Common image types are supported; GIF will not animate. We recommend 256x256 (at least 80x80) to display well on high DPI devices.
chrome_icon
string
ChromeApp
This flag is not used for web push For web push, please see chrome_web_icon
instead.
The local URL to an icon to use. If blank, the app icon will be used.
ios_sound
string
iOS
Sound file that is included in your app to play instead of the default device notification sound. Pass nil
to disable vibration and sound for the notification.
Example: "notification.wav"
android_sound
string
Android
Sound file that is included in your app to play instead of the default device notification sound. Pass nil
to disable sound for the notification.
NOTE: Leave off file extension for Android.
Example: "notification"
adm_sound
string
Amazon
Sound file that is included in your app to play instead of the default device notification sound. Pass nil
to disable sound for the notification.
NOTE: Leave off file extension for Android.
Example: "notification"
wp_wns_sound
string
Windows
Sound file that is included in your app to play instead of the default device notification sound.
Example: "notification.wav"
android_led_color
string
Android
Sets the devices LED notification light if the device has one. ARGB Hex format.
Example(Blue): "FF0000FF"
android_accent_color
string
Android
Sets the background color of the notification circle to the left of the notification text. Only applies to apps targeting Android API level 21+ on Android 5.0+ devices.
Example(Red): "FFFF0000"
android_visibility
int
Android 5.0+
Sets the lock screen visibility for apps targeting Android API level 21+ running on Android 5.0+ devices.
1
= Public (default) (Shows the full message on the lock screen unless the user has disabled all notifications from showing on the lock screen. Please consider the user and mark private if the contents are.)
0
= Private (Hides message contents on lock screen if the user set "Hide sensitive notification content" in the system settings)
-1
= Secret (Notification does not show on the lock screen at all)
ios_badgeType
string
iOS
Describes whether to set or increase/decrease your app's iOS badge count by the ios_badgeCount
specified count. Can specify None
, SetTo
, or Increase
.
None
leaves the count unaffected.
SetTo
directly sets the badge count to the number specified in ios_badgeCount
.
Increase
adds the number specified in ios_badgeCount
to the total. Use a negative number to decrease the badge count.
ios_badgeCount
integer
iOS
Used with ios_badgeType
, describes the value to set or amount to increase/decrease your app's iOS badge count by.
You can use a negative number to decrease the badge count when used with an ios_badgeType
of Increase
.
collapse_id
string
iOS 10+ Android
Only one notification with the same id will be shown on the device. Use the same id to update an existing notification instead of showing a new one. Limit of 64 characters.
apns_alert
object
iOS 10+
iOS can localize push notification messages on the client using special parameters such as loc-key
. When using the Create Notification endpoint, you must include these parameters inside of a field called apns_alert
. Please see Apple's guide on localizing push notifications to learn more.
send_after
string
All
Schedule notification for future delivery. API defaults to UTC -1100
Examples: All examples are the exact same date & time.
"Thu Sep 24 2015 14:00:00 GMT-0700 (PDT)"
"September 24th 2015, 2:00:00 pm UTC-07:00"
"2015-09-24 14:00:00 GMT-0700"
"Sept 24 2015 14:00:00 GMT-0700"
"Thu Sep 24 2015 14:00:00 GMT-0700 (Pacific Daylight Time)"
delayed_option
string
All
Possible values are:
timezone
(Deliver at a specific time-of-day in each users own timezone)
last-active
Same as Intelligent Delivery . (Deliver at the same time of day as each user last used your app).
If send_after
is used, this takes effect after the send_after
time has elapsed.
delivery_time_of_day
string
All
Use with delayed_option=timezone
.
Examples: "9:00AM"
"21:45"
"9:45:30"
ttl
integer
iOS, Android, Chrome, Safari, ChromeWeb
Time To Live - In seconds. The notification will be expired if the device does not come back online within this time. The default is 259,200 seconds (3 days).
Max value to set is 2419200
seconds (28 days).
priority
integer
Android, Chrome, ChromeWeb
Delivery priority through the push server (example GCM/FCM). Pass 10
for high priority. Defaults to normal priority for Android and high for iOS. For Android 6.0+ devices setting priority to high will wake the device out of doze mode.
apns_push_type_override
string
iOS
Set the value to voip
for sending VoIP Notifications
Other valid values (Apple docs):
alert
background
complication
fileprovider
mdm
Grouping & Collapsing
Grouping lets you combine multiple notifications into a single notification to improve the user experience. Collapsing lets you dismiss old notifications in favor of newer ones.
android_group
string
Android
Notifications with the same group will be stacked together using Android's Notification Grouping feature.
android_group_message
object
Android
Note: This only works for Android 6 and older. Android 7+ allows full expansion of all message.
Summary message to display when 2+ notifications are stacked together. Default is "# new messages". Include $[notif_count]
in your message and it will be replaced with the current number.
Languages - The value of each key is the message that will be sent to users for that language. "en"
(English) is required. The key of each hash is either a a 2 character language code or one of zh-Hans/zh-Hant for Simplified or Traditional Chinese. Read more: supported languages.
Example: {"en": "You have $[notif_count] new messages"}
adm_group
string
Amazon
Notifications with the same group will be stacked together using Android's Notification Grouping feature.
adm_group_message
object
Amazon
Summary message to display when 2+ notifications are stacked together. Default is "# new messages". Include $[notif_count] in your message and it will be replaced with the current number. "en" (English) is required. The key of each hash is either a a 2 character language code or one of zh-Hans/zh-Hant for Simplified or Traditional Chinese. The value of each key is the message that will be sent to users for that language.
Example: {"en": "You have $[notif_count] new messages"}
thread_id
string
iOS 12+
This parameter is supported in iOS 12 and above. It allows you to group related notifications together.
If two notifications have the same thread-id
, they will both be added to the same group.
summary_arg
string
iOS 12+
When using thread_id
to create grouped notifications in iOS 12+, you can also control the summary. For example, a grouped notification can say "12 more notifications from John Doe".
The summary_arg
lets you set the name of the person/thing the notifications are coming from, and will show up as "X more notifications from summary_arg
"
summary_arg_count
number
iOS 12+
When using thread_id
, you can also control the count of the number of notifications in the group. For example, if the group already has 12 notifications, and you send a new notification with summary_arg_count
= 2
, the new total will be 14 and the summary will be "14 more notifications from summary_arg
"
Platform to Deliver To
By default, OneSignal will send to every platform (each of these is true
).
The following parameters are all boolean
except for:
channel_for_external_user_ids
To only send to specific platforms, you may pass in true
on one or more of these boolean parameters corresponding to the platform you wish to send to. If you do so, all other platforms will be set to false
and will not be delivered to.
These parameters will be ignored if sending to devices directly with include_player_ids
or include_external_user_ids
isIos
boolean
iOS
Indicates whether to send to all devices registered under your app's Apple iOS platform.
isAndroid
boolean
Android
Indicates whether to send to all devices registered under your app's Google Android platform.
isAnyWeb
boolean
Web
Indicates whether to send to all subscribed web browser users, including Chrome, Firefox, and Safari.
You may use this instead as a combined flag instead of separately enabling isChromeWeb
, isFirefox
, and isSafari
, though the three options are equivalent to this one.
isEmail
boolean
Indicates whether to send to users with email.
isChromeWeb
boolean
Web
Indicates whether to send to all Google Chrome, Chrome on Android, and Mozilla Firefox users registered under your Chrome & Firefox web push platform.
isFirefox
*
boolean
Web
Indicates whether to send to all Mozilla Firefox desktop users registered under your Firefox web push platform.
isSafari
boolean
Web
Does not support iOS Safari Indicates whether to send to all Apple's Safari desktop users registered under your Safari web push platform. Read more: iOS Safari
isWP_WNS
boolean
Windows
Indicates whether to send to all devices registered under your app's Windows platform.
isAdm
boolean
Amazon
Indicates whether to send to all devices registered under your app's Amazon Fire platform.
isChrome
boolean
ChromeApp
This flag is not used for web push Please see isChromeWeb
for sending to web push users. This flag only applies to Google Chrome Apps & Extensions.
Indicates whether to send to all devices registered under your app's Google Chrome Apps & Extension platform.
channel_for_external_user_ids
string
push or email
Indicates if the message type when targeting with include_external_user_ids for cases where an email and push subscriber has the same external user id.
Example: Use the string "push"
to indicate you are sending a push notification or the string "email"
for sending emails.
- Shell
- JSON
- PHP
- C# (.NET standard)
- C# (ASP.NET)
- Ruby (Rails)
- Python
- NodeJS
- Perl
- Parse Cloud
- GameSparks
- Java
curl --include \
--request POST \
--header "Content-Type: application/json; charset=utf-8" \
--header "Authorization: Basic YOUR_REST_API_KEY" \
--data-binary "{\"app_id\": \"YOUR_APP_ID\",
\"contents\": {\"en\": \"English Message\"},
\"included_segments\": [\"Subscribed Users\"]}" \
https://onesignal.com/api/v1/notifications
{
"app_id": "5eb5a37e-b458-11e3-ac11-000c2940e62c",
"included_segments": ["All"],
"data": {"foo": "bar"},
"contents": {"en": "English Message"}
}
<?PHP
function sendMessage() {
$content = array(
"en" => 'English Message'
);
$hashes_array = array();
array_push($hashes_array, array(
"id" => "like-button",
"text" => "Like",
"icon" => "http://i.imgur.com/N8SN8ZS.png",
"url" => "https://yoursite.com"
));
array_push($hashes_array, array(
"id" => "like-button-2",
"text" => "Like2",
"icon" => "http://i.imgur.com/N8SN8ZS.png",
"url" => "https://yoursite.com"
));
$fields = array(
'app_id' => "5eb5a37e-b458-11e3-ac11-000c2940e62c",
'included_segments' => array(
'All'
),
'data' => array(
"foo" => "bar"
),
'contents' => $content,
'web_buttons' => $hashes_array
);
$fields = json_encode($fields);
print("\nJSON sent:\n");
print($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json; charset=utf-8',
'Authorization: Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
$response = sendMessage();
$return["allresponses"] = $response;
$return = json_encode($return);
$data = json_decode($response, true);
print_r($data);
$id = $data['id'];
print_r($id);
print("\n\nJSON received:\n");
print($return);
print("\n");
?>
using System.IO;
using System.Net;
using System.Text;
var request = WebRequest.Create("https://onesignal.com/api/v1/notifications") as HttpWebRequest;
request.KeepAlive = true;
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
request.Headers.Add("authorization", "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj");
byte[] byteArray = Encoding.UTF8.GetBytes("{"
+ "\"app_id\": \"5eb5a37e-b458-11e3-ac11-000c2940e62c\","
+ "\"contents\": {\"en\": \"English Message\"},"
+ "\"included_segments\": [\"All\"]}");
string responseContent = null;
try {
using (var writer = request.GetRequestStream()) {
writer.Write(byteArray, 0, byteArray.Length);
}
using (var response = request.GetResponse() as HttpWebResponse) {
using (var reader = new StreamReader(response.GetResponseStream())) {
responseContent = reader.ReadToEnd();
}
}
}
catch (WebException ex) {
System.Diagnostics.Debug.WriteLine(ex.Message);
System.Diagnostics.Debug.WriteLine(new StreamReader(ex.Response.GetResponseStream()).ReadToEnd());
}
System.Diagnostics.Debug.WriteLine(responseContent);
using System.IO;
using System.Net;
using System.Text;
var request = WebRequest.Create("https://onesignal.com/api/v1/notifications") as HttpWebRequest;
request.KeepAlive = true;
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
request.Headers.Add("authorization", "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj");
var serializer = new JavaScriptSerializer();
var obj = new { app_id = "5eb5a37e-b458-11e3-ac11-000c2940e62c",
contents = new { en = "English Message" },
included_segments = new string[] {"All"} };
var param = serializer.Serialize(obj);
byte[] byteArray = Encoding.UTF8.GetBytes(param);
string responseContent = null;
try {
using (var writer = request.GetRequestStream()) {
writer.Write(byteArray, 0, byteArray.Length);
}
using (var response = request.GetResponse() as HttpWebResponse) {
using (var reader = new StreamReader(response.GetResponseStream())) {
responseContent = reader.ReadToEnd();
}
}
}
catch (WebException ex) {
System.Diagnostics.Debug.WriteLine(ex.Message);
System.Diagnostics.Debug.WriteLine(new StreamReader(ex.Response.GetResponseStream()).ReadToEnd());
}
System.Diagnostics.Debug.WriteLine(responseContent);
params = {"app_id" => "5eb5a37e-b458-11e3-ac11-000c2940e62c",
"contents" => {"en" => "English Message"},
"included_segments" => ["All"]}
uri = URI.parse('https://onesignal.com/api/v1/notifications')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(uri.path,
'Content-Type' => 'application/json;charset=utf-8',
'Authorization' => "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj")
request.body = params.as_json.to_json
response = http.request(request)
puts response.body
req = requests.post("https://onesignal.com/api/v1/notifications", headers=header, data=json.dumps(payload))
print(req.status_code, req.reason)
import requests
import json
header = {"Content-Type": "application/json; charset=utf-8",
"Authorization": "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj"}
payload = {"app_id": "5eb5a37e-b458-11e3-ac11-000c2940e62c",
"included_segments": ["All"],
"contents": {"en": "English Message"}}
req = requests.post("https://onesignal.com/api/v1/notifications", headers=header, data=json.dumps(payload))
print(req.status_code, req.reason)
var sendNotification = function(data) {
var headers = {
"Content-Type": "application/json; charset=utf-8",
"Authorization": "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj"
};
var options = {
host: "onesignal.com",
port: 443,
path: "/api/v1/notifications",
method: "POST",
headers: headers
};
var https = require('https');
var req = https.request(options, function(res) {
res.on('data', function(data) {
console.log("Response:");
console.log(JSON.parse(data));
});
});
req.on('error', function(e) {
console.log("ERROR:");
console.log(e);
});
req.write(JSON.stringify(data));
req.end();
};
var message = {
app_id: "5eb5a37e-b458-11e3-ac11-000c2940e62c",
contents: {"en": "English Message"},
included_segments: ["All"]
};
sendNotification(message);
#!/usr/bin/perl -w
use ;
use ;
use :::: qw(/^CURLOPT_.*/);;
use ;
use :: ;
sub
{
my ($url , $authorisation , $app_id , $contents) = @_;
my $curl = ::::->new;
my $json = ->new();
my $response_body;
my $json_string = $json-> ({ => $app_id ,
=> ["All"] ,
=> { "key1" => "Value 1" } ,
=> "Increase" ,
=> 1 ,
=> { => $contents}
});
$curl-> ( , $url);
$curl-> ( , 0);
$curl-> ( , 0);
$curl-> ( , ['Content-Type: application/json; charset=utf-8' ,
"Authorization: Basic $authorisation"]);
$curl-> ( , 1);
$curl-> ( , $json_string);
$curl-> ( , \$response_body);
$curl-> ;
print ($response_body);
}
("https://onesignal.com/api/v1/notifications" ,
" " ,
" " ,
"Hello World");
exit(0);
send = function(params) {
var promise = new Parse.Promise();
var jsonBody = {
app_id: "5eb5a37e-b458-11e3-ac11-000c2940e62c",
included_segments: ["All"],
contents: {en: "English Message"},
data: {foo: "bar"}
};
Parse.Cloud.httpRequest({
method: "POST",
url: "https://onesignal.com/api/v1/notifications",
headers: {
"Content-Type": "application/json;charset=utf-8",
"Authorization": "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj"
},
body: JSON.stringify(jsonBody)
}).then(function (httpResponse) {
promise.resolve(httpResponse)
},
function (httpResponse) {
promise.reject(httpResponse);
});
return promise;
};
exports.send = send;
function SendNewNotification() {
var jsonBody = {
app_id: "5eb5a37e-b458-11e3-ac11-000c2940e62c",
included_segments: ["All"],
contents: {en: "English Message"},
};
var promise = Spark.getHttp("https://onesignal.com/api/v1/notifications").setHeaders({
"Content-Type": "application/json;charset=utf-8",
"Authorization": "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj"
}).postJson(jsonBody);
return promise;
}
var response = SendNewNotification().getResponseJson();
Spark.setScriptData("response", response)
try {
String jsonResponse;
URL url = new URL("https://onesignal.com/api/v1/notifications");
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setUseCaches(false);
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.setRequestProperty("Authorization", "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj");
con.setRequestMethod("POST");
String strJsonBody = "{"
+ "\"app_id\": \"5eb5a37e-b458-11e3-ac11-000c2940e62c\","
+ "\"included_segments\": [\"All\"],"
+ "\"data\": {\"foo\": \"bar\"},"
+ "\"contents\": {\"en\": \"English Message\"}"
+ "}";
System.out.println("strJsonBody:\n" + strJsonBody);
byte[] sendBytes = strJsonBody.getBytes("UTF-8");
con.setFixedLengthStreamingMode(sendBytes.length);
OutputStream outputStream = con.getOutputStream();
outputStream.write(sendBytes);
int httpResponse = con.getResponseCode();
System.out.println("httpResponse: " + httpResponse);
if ( httpResponse >= HttpURLConnection.HTTP_OK
&& httpResponse < HttpURLConnection.HTTP_BAD_REQUEST) {
Scanner scanner = new Scanner(con.getInputStream(), "UTF-8");
jsonResponse = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
scanner.close();
}
else {
Scanner scanner = new Scanner(con.getErrorStream(), "UTF-8");
jsonResponse = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
scanner.close();
}
System.out.println("jsonResponse:\n" + jsonResponse);
} catch(Throwable t) {
t.printStackTrace();
}
- Shell
- JSON
- PHP
- C# (.NET standard)
- C# (ASP.NET)
- Ruby (Rails)
- Python
- NodeJS
- Perl
- Parse Cloud
- GameSparks
- Java
curl --include \
--request POST \
--header "Content-Type: application/json; charset=utf-8" \
--header "Authorization: Basic YOUR_REST_API_KEY" \
--data-binary "{\"app_id\": \"YOUR_APP_ID\",
\"contents\": {\"en\": \"English Message\"},
\"included_segments\": [\"Active Users\"]}" \
https://onesignal.com/api/v1/notifications
{
"app_id": "5eb5a37e-b458-11e3-ac11-000c2940e62c",
"included_segments": ["Active Users"],
"data": {"foo": "bar"},
"contents": {"en": "English Message"}
}
<?PHP
function sendMessage(){
$content = array(
"en" => 'English Message'
);
$fields = array(
'app_id' => "5eb5a37e-b458-11e3-ac11-000c2940e62c",
'included_segments' => array('Active Users'),
'data' => array("foo" => "bar"),
'contents' => $content
);
$fields = json_encode($fields);
print("\nJSON sent:\n");
print($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8',
'Authorization: Basic YOUR_REST_API_KEY'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
$response = sendMessage();
$return["allresponses"] = $response;
$return = json_encode( $return);
print("\n\nJSON received:\n");
print($return);
print("\n");
?>
using System.IO;
using System.Net;
using System.Text;
var request = WebRequest.Create("https://onesignal.com/api/v1/notifications") as HttpWebRequest;
request.KeepAlive = true;
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
request.Headers.Add("authorization", "Basic YOUR_REST_API_KEY");
byte[] byteArray = Encoding.UTF8.GetBytes("{"
+ "\"app_id\": \"5eb5a37e-b458-11e3-ac11-000c2940e62c\","
+ "\"contents\": {\"en\": \"English Message\"},"
+ "\"included_segments\": [\"Active Users\"]}");
string responseContent = null;
try {
using (var writer = request.GetRequestStream()) {
writer.Write(byteArray, 0, byteArray.Length);
}
using (var response = request.GetResponse() as HttpWebResponse) {
using (var reader = new StreamReader(response.GetResponseStream())) {
responseContent = reader.ReadToEnd();
}
}
}
catch (WebException ex) {
System.Diagnostics.Debug.WriteLine(ex.Message);
System.Diagnostics.Debug.WriteLine(new StreamReader(ex.Response.GetResponseStream()).ReadToEnd());
}
System.Diagnostics.Debug.WriteLine(responseContent);
using System.IO;
using System.Net;
using System.Text;
var request = WebRequest.Create("https://onesignal.com/api/v1/notifications") as HttpWebRequest;
request.KeepAlive = true;
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
request.Headers.Add("authorization", "Basic YOUR_REST_API_KEY");
var serializer = new JavaScriptSerializer();
var obj = new { app_id = "5eb5a37e-b458-11e3-ac11-000c2940e62c",
contents = new { en = "English Message" },
included_segments = new string[] {"Active Users"} };
var param = serializer.Serialize(obj);
byte[] byteArray = Encoding.UTF8.GetBytes(param);
string responseContent = null;
try {
using (var writer = request.GetRequestStream()) {
writer.Write(byteArray, 0, byteArray.Length);
}
using (var response = request.GetResponse() as HttpWebResponse) {
using (var reader = new StreamReader(response.GetResponseStream())) {
responseContent = reader.ReadToEnd();
}
}
}
catch (WebException ex) {
System.Diagnostics.Debug.WriteLine(ex.Message);
System.Diagnostics.Debug.WriteLine(new StreamReader(ex.Response.GetResponseStream()).ReadToEnd());
}
System.Diagnostics.Debug.WriteLine(responseContent);
params = {"app_id" => "5eb5a37e-b458-11e3-ac11-000c2940e62c",
"contents" => {"en" => "English Message"},
"included_segments" => ["Active Users"]}
uri = URI.parse('https://onesignal.com/api/v1/notifications')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(uri.path,
'Content-Type' => 'application/json;charset=utf-8',
'Authorization' => "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj")
request.body = params.as_json.to_json
response = http.request(request)
puts response.body
req = requests.post("https://onesignal.com/api/v1/notifications", headers=header, data=json.dumps(payload))
print(req.status_code, req.reason)
import requests
import json
header = {"Content-Type": "application/json; charset=utf-8",
"Authorization": "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj"}
payload = {"app_id": "5eb5a37e-b458-11e3-ac11-000c2940e62c",
"included_segments": ["Active Users"],
"contents": {"en": "English Message"}}
req = requests.post("https://onesignal.com/api/v1/notifications", headers=header, data=json.dumps(payload))
print(req.status_code, req.reason)
var sendNotification = function(data) {
var headers = {
"Content-Type": "application/json; charset=utf-8",
"Authorization": "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj"
};
var options = {
host: "onesignal.com",
port: 443,
path: "/api/v1/notifications",
method: "POST",
headers: headers
};
var https = require('https');
var req = https.request(options, function(res) {
res.on('data', function(data) {
console.log("Response:");
console.log(JSON.parse(data));
});
});
req.on('error', function(e) {
console.log("ERROR:");
console.log(e);
});
req.write(JSON.stringify(data));
req.end();
};
var message = {
app_id: "5eb5a37e-b458-11e3-ac11-000c2940e62c",
contents: {"en": "English Message"},
included_segments: ["Active Users"]
};
sendNotification(message);
#!/usr/bin/perl -w
use ;
use ;
use :::: qw(/^CURLOPT_.*/);;
use ;
use :: ;
sub
{
my ($url , $authorisation , $app_id , $contents) = @_;
my $curl = ::::->new;
my $json = ->new();
my $response_body;
my $json_string = $json-> ({ => $app_id ,
=> ["Active Users"] ,
=> { => $contents}
});
$curl-> ( , $url);
$curl-> ( , 0);
$curl-> ( , 0);
$curl-> ( , ['Content-Type: application/json; charset=utf-8' ,
"Authorization: Basic $authorisation"]);
$curl-> ( , 1);
$curl-> ( , $json_string);
$curl-> ( , \$response_body);
$curl-> ;
print ($response_body);
}
("https://onesignal.com/api/v1/notifications" ,
" " ,
" " ,
"Hello World");
exit(0);
send = function(params) {
var promise = new Parse.Promise();
var jsonBody = {
app_id: "5eb5a37e-b458-11e3-ac11-000c2940e62c",
included_segments: ["Active Users"],
contents: {en: "English Message"},
data: {foo: "bar"}
};
Parse.Cloud.httpRequest({
method: "POST",
url: "https://onesignal.com/api/v1/notifications",
headers: {
"Content-Type": "application/json;charset=utf-8",
"Authorization": "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj"
},
body: JSON.stringify(jsonBody)
}).then(function (httpResponse) {
promise.resolve(httpResponse)
},
function (httpResponse) {
promise.reject(httpResponse);
});
return promise;
};
exports.send = send;
function SendNewNotification() {
var jsonBody = {
app_id: "5eb5a37e-b458-11e3-ac11-000c2940e62c",
included_segments: ["Active Users"],
contents: {en: "English Message"},
};
var promise = Spark.getHttp("https://onesignal.com/api/v1/notifications").setHeaders({
"Content-Type": "application/json;charset=utf-8",
"Authorization": "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj"
}).postJson(jsonBody);
return promise;
}
var response = SendNewNotification().getResponseJson();
Spark.setScriptData("response", response)
try {
String jsonResponse;
URL url = new URL("https://onesignal.com/api/v1/notifications");
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setUseCaches(false);
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.setRequestProperty("Authorization", "Basic YOUR_REST_API_KEY");
con.setRequestMethod("POST");
String strJsonBody = "{"
+ "\"app_id\": \"5eb5a37e-b458-11e3-ac11-000c2940e62c\","
+ "\"included_segments\": [\"Active Users\"],"
+ "\"data\": {\"foo\": \"bar\"},"
+ "\"contents\": {\"en\": \"English Message\"}"
+ "}";
System.out.println("strJsonBody:\n" + strJsonBody);
byte[] sendBytes = strJsonBody.getBytes("UTF-8");
con.setFixedLengthStreamingMode(sendBytes.length);
OutputStream outputStream = con.getOutputStream();
outputStream.write(sendBytes);
int httpResponse = con.getResponseCode();
System.out.println("httpResponse: " + httpResponse);
if ( httpResponse >= HttpURLConnection.HTTP_OK
&& httpResponse < HttpURLConnection.HTTP_BAD_REQUEST) {
Scanner scanner = new Scanner(con.getInputStream(), "UTF-8");
jsonResponse = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
scanner.close();
}
else {
Scanner scanner = new Scanner(con.getErrorStream(), "UTF-8");
jsonResponse = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
scanner.close();
}
System.out.println("jsonResponse:\n" + jsonResponse);
} catch(Throwable t) {
t.printStackTrace();
}
- Shell
- JSON
- PHP
- C# (.NET standard)
- C# (ASP.NET)
- Ruby (Rails)
- Python
- NodeJS
- Perl
- Parse Cloud
- GameSparks
- Java
curl --include \
--request POST \
--header "Content-Type: application/json; charset=utf-8" \
--header "Authorization: Basic YOUR_REST_API_KEY" \
--data-binary "{\"app_id\": \"YOUR_APP_ID\",
\"contents\": {\"en\": \"English Message\"},
\"filters\": [{\"field\": \"tag\", \"key\": \"level\", \"relation\": \">\", \"value\": \"10\"},{\"operator\": \"OR\"},{\"field\": \"amount_spent\", \"relation\": \">\",\"value\": \"0\"}]}" \
https://onesignal.com/api/v1/notifications
{
"app_id": "5eb5a37e-b458-11e3-ac11-000c2940e62c",
"filters": [
{"field": "tag", "key": "level", "relation": "=", "value": "10"},
{"operator": "OR"}, {"field": "amount_spent", "relation": ">", "value": "0"}
],
"data": {"foo": "bar"},
"contents": {"en": "English Message"}
}
<?PHP
function sendMessage(){
$content = array(
"en" => 'English Message'
);
$fields = array(
'app_id' => "5eb5a37e-b458-11e3-ac11-000c2940e62c",
'filters' => array(array("field" => "tag", "key" => "level", "relation" => "=", "value" => "10"),array("operator" => "OR"),array("field" => "amount_spent", "relation" => "=", "value" => "0")),
'data' => array("foo" => "bar"),
'contents' => $content
);
$fields = json_encode($fields);
print("\nJSON sent:\n");
print($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8',
'Authorization: Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
$response = sendMessage();
$return["allresponses"] = $response;
$return = json_encode( $return);
print("\n\nJSON received:\n");
print($return);
print("\n");
?>
using System.IO;
using System.Net;
using System.Text;
var request = WebRequest.Create("https://onesignal.com/api/v1/notifications") as HttpWebRequest;
request.KeepAlive = true;
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
request.Headers.Add("authorization", "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj");
byte[] byteArray = Encoding.UTF8.GetBytes("{"
+ "\"app_id\": \"5eb5a37e-b458-11e3-ac11-000c2940e62c\","
+ "\"contents\": {\"en\": \"English Message\"},"
+ "\"filters\": [{\"field\": \"tag\", \"key\": \"level\", \"relation\": \">\", \"value\": \"10\"},{\"operator\": \"OR\"},{\"field\": \"amount_spent\", \"relation\": \">\",\"value\": \"0\"}]}");
string responseContent = null;
try {
using (var writer = request.GetRequestStream()) {
writer.Write(byteArray, 0, byteArray.Length);
}
using (var response = request.GetResponse() as HttpWebResponse) {
using (var reader = new StreamReader(response.GetResponseStream())) {
responseContent = reader.ReadToEnd();
}
}
}
catch (WebException ex) {
System.Diagnostics.Debug.WriteLine(ex.Message);
System.Diagnostics.Debug.WriteLine(new StreamReader(ex.Response.GetResponseStream()).ReadToEnd());
}
System.Diagnostics.Debug.WriteLine(responseContent);
using System.IO;
using System.Net;
using System.Text;
var request = WebRequest.Create("https://onesignal.com/api/v1/notifications") as HttpWebRequest;
request.KeepAlive = true;
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
request.Headers.Add("authorization", "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj");
var serializer = new JavaScriptSerializer();
var obj = new { app_id = "5eb5a37e-b458-11e3-ac11-000c2940e62c",
contents = new { en = "English Message" },
filters = new object[] { new { field = "tag", key = "level", value = "10" }, new { = "OR" }, new { field = "amount_spent", relation = ">", value = "0" } } };
var param = serializer.Serialize(obj);
byte[] byteArray = Encoding.UTF8.GetBytes(param);
string responseContent = null;
try {
using (var writer = request.GetRequestStream()) {
writer.Write(byteArray, 0, byteArray.Length);
}
using (var response = request.GetResponse() as HttpWebResponse) {
using (var reader = new StreamReader(response.GetResponseStream())) {
responseContent = reader.ReadToEnd();
}
}
}
catch (WebException ex) {
System.Diagnostics.Debug.WriteLine(ex.Message);
System.Diagnostics.Debug.WriteLine(new StreamReader(ex.Response.GetResponseStream()).ReadToEnd());
}
System.Diagnostics.Debug.WriteLine(responseContent);
params = {"app_id" => "5eb5a37e-b458-11e3-ac11-000c2940e62c",
"contents" => {"en" => "English Message"},
"filters" => [
{"field": "tag", "key": "level", "relation": "=", "value": "10"},
{"operator": "OR"}, {"field": "amount_spent", "relation": ">", "value": "0"}
]
}
uri = URI.parse('https://onesignal.com/api/v1/notifications')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(uri.path,
'Content-Type' => 'application/json;charset=utf-8',
'Authorization' => "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj")
request.body = params.as_json.to_json
response = http.request(request)
puts response.body
req = requests.post("https://onesignal.com/api/v1/notifications", headers=header, data=json.dumps(payload))
print(req.status_code, req.reason)
import requests
import json
header = {"Content-Type": "application/json; charset=utf-8",
"Authorization": "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj"}
payload = {"app_id": "5eb5a37e-b458-11e3-ac11-000c2940e62c",
"filters": [
{"field": "tag", "key": "level", "relation": "=", "value": "10"},
{"operator": "OR"}, {"field": "amount_spent", "relation": ">", "value": "0"}
],
"contents": {"en": "English Message"}}
req = requests.post("https://onesignal.com/api/v1/notifications", headers=header, data=json.dumps(payload))
print(req.status_code, req.reason)
var sendNotification = function(data) {
var headers = {
"Content-Type": "application/json; charset=utf-8",
"Authorization": "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj"
};
var options = {
host: "onesignal.com",
port: 443,
path: "/api/v1/notifications",
method: "POST",
headers: headers
};
var https = require('https');
var req = https.request(options, function(res) {
res.on('data', function(data) {
console.log("Response:");
console.log(JSON.parse(data));
});
});
req.on('error', function(e) {
console.log("ERROR:");
console.log(e);
});
req.write(JSON.stringify(data));
req.end();
};
var message = {
app_id: "5eb5a37e-b458-11e3-ac11-000c2940e62c",
contents: {"en": "English Message"},
filters: [
{"field": "tag", "key": "level", "relation": "=", "value": "10"},
{"operator": "OR"}, {"field": "amount_spent", "relation": ">", "value": "0"}
]
};
sendNotification(message);
#!/usr/bin/perl -w
use ;
use ;
use :::: qw(/^CURLOPT_.*/);;
use ;
use :: ;
sub
{
my ($url , $authorisation , $app_id , $contents) = @_;
my $curl = ::::->new;
my $json = ->new();
my $response_body;
my $json_string = $json-> ({ => $app_id ,
=> [
{"field": "tag", "key": "level", "relation": "=", "value": "10"},
{"operator": "OR"}, {"field": "amount_spent", "relation": ">", "value": "0"}
],
=> { => $contents}
});
$curl-> ( , $url);
$curl-> ( , 0);
$curl-> ( , 0);
$curl-> ( , ['Content-Type: application/json; charset=utf-8' ,
"Authorization: Basic $authorisation"]);
$curl-> ( , 1);
$curl-> ( , $json_string);
$curl-> ( , \$response_body);
$curl-> ;
print ($response_body);
}
("https://onesignal.com/api/v1/notifications" ,
" " ,
" " ,
"Hello World");
exit(0);
send = function(params) {
var promise = new Parse.Promise();
var jsonBody = {
app_id: "5eb5a37e-b458-11e3-ac11-000c2940e62c",
filters: [
{"field": "tag", "key": "level", "relation": "=", "value": "10"},
{"operator": "OR"}, {"field": "amount_spent", "relation": ">", "value": "0"}
],
contents: {en: "English Message"},
data: {foo: "bar"}
};
Parse.Cloud.httpRequest({
method: "POST",
url: "https://onesignal.com/api/v1/notifications",
headers: {
"Content-Type": "application/json;charset=utf-8",
"Authorization": "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj"
},
body: JSON.stringify(jsonBody)
}).then(function (httpResponse) {
promise.resolve(httpResponse)
},
function (httpResponse) {
promise.reject(httpResponse);
});
return promise;
};
exports.send = send;
function SendNewNotification() {
var jsonBody = {
app_id: "5eb5a37e-b458-11e3-ac11-000c2940e62c",
filters: [
{"field": "tag", "key": "level", "relation": "=", "value": "10"},
{"operator": "OR"}, {"field": "amount_spent", "relation": ">", "value": "0"}
],
contents: {en: "English Message"},
};
var promise = Spark.getHttp("https://onesignal.com/api/v1/notifications").setHeaders({
"Content-Type": "application/json;charset=utf-8",
"Authorization": "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj"
}).postJson(jsonBody);
return promise;
}
var response = SendNewNotification().getResponseJson();
Spark.setScriptData("response", response)
try {
String jsonResponse;
URL url = new URL("https://onesignal.com/api/v1/notifications");
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setUseCaches(false);
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.setRequestProperty("Authorization", "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj");
con.setRequestMethod("POST");
String strJsonBody = "{"
+ "\"app_id\": \"5eb5a37e-b458-11e3-ac11-000c2940e62c\","
+ "\"filters\": [{\"field\": \"tag\", \"key\": \"level\", \"relation\": \">\", \"value\": \"10\"},{\"operator\": \"OR\"},{\"field\": \"amount_spent\", \"relation\": \">\",\"value\": \"0\"}],"
+ "\"data\": {\"foo\": \"bar\"},"
+ "\"contents\": {\"en\": \"English Message\"}"
+ "}";
System.out.println("strJsonBody:\n" + strJsonBody);
byte[] sendBytes = strJsonBody.getBytes("UTF-8");
con.setFixedLengthStreamingMode(sendBytes.length);
OutputStream outputStream = con.getOutputStream();
outputStream.write(sendBytes);
int httpResponse = con.getResponseCode();
System.out.println("httpResponse: " + httpResponse);
if ( httpResponse >= HttpURLConnection.HTTP_OK
&& httpResponse < HttpURLConnection.HTTP_BAD_REQUEST) {
Scanner scanner = new Scanner(con.getInputStream(), "UTF-8");
jsonResponse = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
scanner.close();
}
else {
Scanner scanner = new Scanner(con.getErrorStream(), "UTF-8");
jsonResponse = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
scanner.close();
}
System.out.println("jsonResponse:\n" + jsonResponse);
} catch(Throwable t) {
t.printStackTrace();
}
- Shell
- JSON
- PHP
- C# (.NET standard)
- C# (ASP.NET)
- Ruby (Rails)
- Python
- NodeJS
- Perl
- Parse Cloud
- GameSparks
- Java
curl --include \
--request POST \
--header "Content-Type: application/json; charset=utf-8" \
--data-binary "{\"app_id\": \"5eb5a37e-b458-11e3-ac11-000c2940e62c\",
\"contents\": {\"en\": \"English Message\"},
\"include_player_ids\": [\"6392d91a-b206-4b7b-a620-cd68e32c3a76\",\"76ece62b-bcfe-468c-8a78-839aeaa8c5fa\",\"8e0f21fa-9a5a-4ae7-a9a6-ca1f24294b86\"]}" \
https://onesignal.com/api/v1/notifications
{
"app_id": "5eb5a37e-b458-11e3-ac11-000c2940e62c",
"include_player_ids": ["6392d91a-b206-4b7b-a620-cd68e32c3a76","76ece62b-bcfe-468c-8a78-839aeaa8c5fa","8e0f21fa-9a5a-4ae7-a9a6-ca1f24294b86"],
"data": {"foo": "bar"},
"contents": {"en": "English Message"}
}
<?PHP
function sendMessage(){
$content = array(
"en" => 'English Message'
);
$fields = array(
'app_id' => "5eb5a37e-b458-11e3-ac11-000c2940e62c",
'include_player_ids' => array("6392d91a-b206-4b7b-a620-cd68e32c3a76","76ece62b-bcfe-468c-8a78-839aeaa8c5fa","8e0f21fa-9a5a-4ae7-a9a6-ca1f24294b86"),
'data' => array("foo" => "bar"),
'contents' => $content
);
$fields = json_encode($fields);
print("\nJSON sent:\n");
print($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
$response = sendMessage();
$return["allresponses"] = $response;
$return = json_encode( $return);
print("\n\nJSON received:\n");
print($return);
print("\n");
?>
using System.IO;
using System.Net;
using System.Text;
var request = WebRequest.Create("https://onesignal.com/api/v1/notifications") as HttpWebRequest;
request.KeepAlive = true;
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
byte[] byteArray = Encoding.UTF8.GetBytes("{"
+ "\"app_id\": \"5eb5a37e-b458-11e3-ac11-000c2940e62c\","
+ "\"contents\": {\"en\": \"English Message\"},"
+ "\"include_player_ids\": [\"6392d91a-b206-4b7b-a620-cd68e32c3a76\",\"76ece62b-bcfe-468c-8a78-839aeaa8c5fa\",\"8e0f21fa-9a5a-4ae7-a9a6-ca1f24294b86\"]}");
string responseContent = null;
try {
using (var writer = request.GetRequestStream()) {
writer.Write(byteArray, 0, byteArray.Length);
}
using (var response = request.GetResponse() as HttpWebResponse) {
using (var reader = new StreamReader(response.GetResponseStream())) {
responseContent = reader.ReadToEnd();
}
}
}
catch (WebException ex) {
System.Diagnostics.Debug.WriteLine(ex.Message);
System.Diagnostics.Debug.WriteLine(new StreamReader(ex.Response.GetResponseStream()).ReadToEnd());
}
System.Diagnostics.Debug.WriteLine(responseContent);
using System.IO;
using System.Net;
using System.Text;
var request = WebRequest.Create("https://onesignal.com/api/v1/notifications") as HttpWebRequest;
request.KeepAlive = true;
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
var serializer = new JavaScriptSerializer();
var obj = new { app_id = "5eb5a37e-b458-11e3-ac11-000c2940e62c",
contents = new { en = "English Message" },
include_player_ids = new string[] {"6392d91a-b206-4b7b-a620-cd68e32c3a76","76ece62b-bcfe-468c-8a78-839aeaa8c5fa","8e0f21fa-9a5a-4ae7-a9a6-ca1f24294b86"} };
var param = serializer.Serialize(obj);
byte[] byteArray = Encoding.UTF8.GetBytes(param);
string responseContent = null;
try {
using (var writer = request.GetRequestStream()) {
writer.Write(byteArray, 0, byteArray.Length);
}
using (var response = request.GetResponse() as HttpWebResponse) {
using (var reader = new StreamReader(response.GetResponseStream())) {
responseContent = reader.ReadToEnd();
}
}
}
catch (WebException ex) {
System.Diagnostics.Debug.WriteLine(ex.Message);
System.Diagnostics.Debug.WriteLine(new StreamReader(ex.Response.GetResponseStream()).ReadToEnd());
}
System.Diagnostics.Debug.WriteLine(responseContent);
params = {"app_id" => "5eb5a37e-b458-11e3-ac11-000c2940e62c",
"contents" => {"en" => "English Message"},
"include_player_ids" => ["6392d91a-b206-4b7b-a620-cd68e32c3a76","76ece62b-bcfe-468c-8a78-839aeaa8c5fa","8e0f21fa-9a5a-4ae7-a9a6-ca1f24294b86"]
}
uri = URI.parse('https://onesignal.com/api/v1/notifications')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(uri.path,'Content-Type' => 'application/json;charset=utf-8')
request.body = params.as_json.to_json
response = http.request(request)
puts response.body
req = requests.post("https://onesignal.com/api/v1/notifications", headers=header, data=json.dumps(payload))
print(req.status_code, req.reason)
import requests
import json
header = {"Content-Type": "application/json; charset=utf-8"}
payload = {"app_id": "5eb5a37e-b458-11e3-ac11-000c2940e62c",
"include_player_ids": ["6392d91a-b206-4b7b-a620-cd68e32c3a76","76ece62b-bcfe-468c-8a78-839aeaa8c5fa","8e0f21fa-9a5a-4ae7-a9a6-ca1f24294b86"],
"contents": {"en": "English Message"}}
req = requests.post("https://onesignal.com/api/v1/notifications", headers=header, data=json.dumps(payload))
print(req.status_code, req.reason)
var sendNotification = function(data) {
var headers = {
"Content-Type": "application/json; charset=utf-8"
};
var options = {
host: "onesignal.com",
port: 443,
path: "/api/v1/notifications",
method: "POST",
headers: headers
};
var https = require('https');
var req = https.request(options, function(res) {
res.on('data', function(data) {
console.log("Response:");
console.log(JSON.parse(data));
});
});
req.on('error', function(e) {
console.log("ERROR:");
console.log(e);
});
req.write(JSON.stringify(data));
req.end();
};
var message = {
app_id: "5eb5a37e-b458-11e3-ac11-000c2940e62c",
contents: {"en": "English Message"},
include_player_ids: ["6392d91a-b206-4b7b-a620-cd68e32c3a76","76ece62b-bcfe-468c-8a78-839aeaa8c5fa","8e0f21fa-9a5a-4ae7-a9a6-ca1f24294b86"]
};
sendNotification(message);
#!/usr/bin/perl -w
use ;
use ;
use :::: qw(/^CURLOPT_.*/);;
use ;
use :: ;
sub
{
my ($url , $authorisation , $app_id , $contents) = @_;
my $curl = ::::->new;
my $json = ->new();
my $response_body;
my $json_string = $json-> ({ => $app_id ,
=> ["6392d91a-b206-4b7b-a620-cd68e32c3a76","76ece62b-bcfe-468c-8a78-839aeaa8c5fa","8e0f21fa-9a5a-4ae7-a9a6-ca1f24294b86"],
=> { => $contents}
});
$curl-> ( , $url);
$curl-> ( , 0);
$curl-> ( , 0);
$curl-> ( , ['Content-Type: application/json; charset=utf-8']);
$curl-> ( , 1);
$curl-> ( , $json_string);
$curl-> ( , \$response_body);
$curl-> ;
print ($response_body);
}
("https://onesignal.com/api/v1/notifications" ,
" " ,
"Hello World");
exit(0);
send = function(params) {
var promise = new Parse.Promise();
var jsonBody = {
app_id: "5eb5a37e-b458-11e3-ac11-000c2940e62c",
include_player_ids: ["6392d91a-b206-4b7b-a620-cd68e32c3a76","76ece62b-bcfe-468c-8a78-839aeaa8c5fa","8e0f21fa-9a5a-4ae7-a9a6-ca1f24294b86"],
contents: {en: "English Message"},
data: {foo: "bar"}
};
Parse.Cloud.httpRequest({
method: "POST",
url: "https://onesignal.com/api/v1/notifications",
headers: {
"Content-Type": "application/json;charset=utf-8"
},
body: JSON.stringify(jsonBody)
}).then(function (httpResponse) {
promise.resolve(httpResponse)
},
function (httpResponse) {
promise.reject(httpResponse);
});
return promise;
};
exports.send = send;
function SendNewNotification() {
var jsonBody = {
app_id: "5eb5a37e-b458-11e3-ac11-000c2940e62c",
include_player_ids: ["6392d91a-b206-4b7b-a620-cd68e32c3a76","76ece62b-bcfe-468c-8a78-839aeaa8c5fa","8e0f21fa-9a5a-4ae7-a9a6-ca1f24294b86"],
contents: {en: "English Message"},
};
var promise = Spark.getHttp("https://onesignal.com/api/v1/notifications").setHeaders({
"Content-Type": "application/json;charset=utf-8"
}).postJson(jsonBody);
return promise;
}
var response = SendNewNotification().getResponseJson();
Spark.setScriptData("response", response)
try {
String jsonResponse;
URL url = new URL("https://onesignal.com/api/v1/notifications");
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setUseCaches(false);
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.setRequestMethod("POST");
String strJsonBody = "{"
+ "\"app_id\": \"5eb5a37e-b458-11e3-ac11-000c2940e62c\","
+ "\"include_player_ids\": [\"6392d91a-b206-4b7b-a620-cd68e32c3a76\",\"76ece62b-bcfe-468c-8a78-839aeaa8c5fa\",\"8e0f21fa-9a5a-4ae7-a9a6-ca1f24294b86\"],"
+ "\"data\": {\"foo\": \"bar\"},"
+ "\"contents\": {\"en\": \"English Message\"}"
+ "}";
System.out.println("strJsonBody:\n" + strJsonBody);
byte[] sendBytes = strJsonBody.getBytes("UTF-8");
con.setFixedLengthStreamingMode(sendBytes.length);
OutputStream outputStream = con.getOutputStream();
outputStream.write(sendBytes);
int httpResponse = con.getResponseCode();
System.out.println("httpResponse: " + httpResponse);
if ( httpResponse >= HttpURLConnection.HTTP_OK
&& httpResponse < HttpURLConnection.HTTP_BAD_REQUEST) {
Scanner scanner = new Scanner(con.getInputStream(), "UTF-8");
jsonResponse = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
scanner.close();
}
else {
Scanner scanner = new Scanner(con.getErrorStream(), "UTF-8");
jsonResponse = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
scanner.close();
}
System.out.println("jsonResponse:\n" + jsonResponse);
} catch(Throwable t) {
t.printStackTrace();
}
params = {
"app_id" => "5eb5a37e-b458-11e3-ac11-000c2940e62c",
"email_subject" => "Welcome to Cat Facts!",
"email_body" => "<html><head>Welcome to Cat Facts</head><body><h1>Welcome to Cat Facts<h1><h4>Learn more about everyone's favorite furry companions!</h4><hr/><p>Hi Nick,</p><p>Thanks for subscribing to Cat Facts! We can't wait to surprise you with funny details about your favorite animal.</p><h5>Today's Cat Fact (March 27)</h5><p>In tigers and tabbies, the middle of the tongue is covered in backward-pointing spines, used for breaking off and gripping meat.</p><a href='https://catfac.ts/welcome'>Show me more Cat Facts</a><hr/><p><small>(c) 2018 Cat Facts, inc</small></p><p><small><a href='[unsubscribe_url]'>Unsubscribe</a></small></p></body></html>",
"include_player_ids" => ["6392d91a-b206-4b7b-a620-cd68e32c3a76"],
}
uri = URI.parse('https://onesignal.com/api/v1/notifications')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(uri.path,
'Content-Type' => 'application/json;charset=utf-8',
'Authorization' => "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj")
request.body = params.as_json.to_json
response = http.request(request)
puts response.body
import requests
import json
header = {"Content-Type": "application/json; charset=utf-8",
"Authorization": "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj"}
payload = {"app_id": "5eb5a37e-b458-11e3-ac11-000c2940e62c",
"include_player_ids": ["6392d91a-b206-4b7b-a620-cd68e32c3a76"],
"email_subject": "Welcome to Cat Facts!",
"email_body": "<html><head>Welcome to Cat Facts</head><body><h1>Welcome to Cat Facts<h1><h4>Learn more about everyone's favorite furry companions!</h4><hr/><p>Hi Nick,</p><p>Thanks for subscribing to Cat Facts! We can't wait to surprise you with funny details about your favorite animal.</p><h5>Today's Cat Fact (March 27)</h5><p>In tigers and tabbies, the middle of the tongue is covered in backward-pointing spines, used for breaking off and gripping meat.</p><a href='https://catfac.ts/welcome'>Show me more Cat Facts</a><hr/><p><small>(c) 2018 Cat Facts, inc</small></p><p><small><a href='[unsubscribe_url]'>Unsubscribe</a></small></p></body></html>" }
req = requests.post("https://onesignal.com/api/v1/notifications", headers=header, data=json.dumps(payload))
print(req.status_code, req.reason)
var sendNotification = function(data) {
var headers = {
"Content-Type": "application/json; charset=utf-8",
"Authorization": "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj"
};
var options = {
host: "onesignal.com",
port: 443,
path: "/api/v1/notifications",
method: "POST",
headers: headers
};
var https = require('https');
var req = https.request(options, function(res) {
res.on('data', function(data) {
console.log("Response:");
console.log(JSON.parse(data));
});
});
req.on('error', function(e) {
console.log("ERROR:");
console.log(e);
});
req.write(JSON.stringify(data));
req.end();
};
var message = {
app_id: "5eb5a37e-b458-11e3-ac11-000c2940e62c",
"include_player_ids": ["6392d91a-b206-4b7b-a620-cd68e32c3a76"],
"email_subject": "Welcome to Cat Facts!",
"email_body": "<html><head>Welcome to Cat Facts</head><body><h1>Welcome to Cat Facts<h1><h4>Learn more about everyone's favorite furry companions!</h4><hr/><p>Hi Nick,</p><p>Thanks for subscribing to Cat Facts! We can't wait to surprise you with funny details about your favorite animal.</p><h5>Today's Cat Fact (March 27)</h5><p>In tigers and tabbies, the middle of the tongue is covered in backward-pointing spines, used for breaking off and gripping meat.</p><a href='https://catfac.ts/welcome'>Show me more Cat Facts</a><hr/><p><small>(c) 2018 Cat Facts, inc</small></p><p><small><a href='[unsubscribe_url]'>Unsubscribe</a></small></p></body></html>"
};
sendNotification(message);
In every email you send, you must include an unsubscribe link. You can insert this by adding [unsubscribe_url]
in a link within your emails.
Results - Create notification
- 200 OK
- 400 Bad Request
- 200 invalid_player_ids
- 200 No Subscribed Players
- 200 invalid_external_user_ids
{
"id": "458dcec4-cf53-11e3-add2-000c2940e62c",
"recipients": 3
}
{
"errors": ["Notification content must not be null for any languages."]
}
// Returned if using include_player_ids and some were valid and others were not.
// Please process theses on your server and removing them from your database if your tracking them.
{
"errors": {
"invalid_player_ids" : ["5fdc92b2-3b2a-11e5-ac13-8fdccfe4d986", "00cb73f8-5815-11e5-ba69-f75522da5528"]
}
}
{"id": "", "recipients": 0, "errors": ["All included players are not subscribed"]}
// Returned if using include_external_user_ids and some were valid and others were not.
// If multiple devices or the same device with multiple player ids gets the same external_user_id,
// then this indicates how many were unsubscribed.
// More details on why the same device might have multiple records here: https://documentation.onesignal.com/docs/player-id
{
"errors": {
"invalid_external_user_ids" : ["Unsubscribed_external_user_id_1", "unsubscribed_external_user_id_2"]
}
}
Cancel notification
Stop a scheduled or currently outgoing notification
Used to stop a scheduled or currently outgoing notification.
Requires Authentication Key
Requires your OneSignal App's REST API Key, available in Keys & IDs.
unless the notification was created using include_player_ids
and targeting only one user.
id
String
Required Notification id
app_id
String
Required App id
curl --include \
--request DELETE \
--header "Authorization: Basic YOUR_REST_API_KEY" \
https://onesignal.com/api/v1/notifications/YOUR_NOTIFICATION_ID?app_id=YOUR_APP_ID
{'success': "true"}
View apps
View the details of all of your current OneSignal apps
Requires Authentication Key
Requires your OneSignal User Auth Key, available in Keys & IDs.
Example Code - View apps
curl --include \
--header "Authorization: Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj" \
https://onesignal.com/api/v1/apps
[
{
id: "92911750-242d-4260-9e00-9d9034f139ce",
name: "Your app 1",
players: 150,
messageable_players: 143,
updated_at: "2014-04-01T04:20:02.003Z",
created_at: "2014-04-01T04:20:02.003Z",
gcm_key: "a gcm push key",
chrome_key: "A Chrome Web Push GCM key",
chrome_web_origin: "Chrome Web Push Site URL",
chrome_web_gcm_sender_id: "Chrome Web Push GCM Sender ID",
chrome_web_default_notification_icon: "http://yoursite.com/chrome_notification_icon",
chrome_web_sub_domain:"your_site_name",
apns_env: "sandbox",
apns_certificates: "Your apns certificate",
safari_apns_certificate: "Your Safari APNS certificate",
safari_site_origin: "The homename for your website for Safari Push, including http or https",
safari_push_id: "The certificate bundle ID for Safari Web Push",
safari_icon_16_16: "http://onesignal.com/safari_packages/92911750-242d-4260-9e00-9d9034f139ce/16x16.png",
safari_icon_32_32: "http://onesignal.com/safari_packages/92911750-242d-4260-9e00-9d9034f139ce/16x16@2.png",
safari_icon_64_64: "http://onesignal.com/safari_packages/92911750-242d-4260-9e00-9d9034f139ce/32x32@2x.png",
safari_icon_128_128: "http://onesignal.com/safari_packages/92911750-242d-4260-9e00-9d9034f139ce/128x128.png",
safari_icon_256_256: "http://onesignal.com/safari_packages/92911750-242d-4260-9e00-9d9034f139ce/128x128@2x.png",
site_name: "The URL to your website for Web Push",
basic_auth_key: "NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj"
},
{
id: "e4e87830-b954-11e3-811d-f3b376925f15",
name: "Your app 2",
players: 100,
messageable_players: 80,
updated_at: "2014-04-01T04:20:02.003Z",
created_at: "2014-04-01T04:20:02.003Z",
gcm_key: "a gcm push key",
chrome_key: "A Chrome Web Push GCM key",
chrome_web_origin: "Chrome Web Push Site URL",
chrome_web_gcm_sender_id: "Chrome Web Push GCM Sender ID",
chrome_web_default_notification_icon: "http://yoursite.com/chrome_notification_icon",
chrome_web_sub_domain:"your_site_name",
apns_env: "sandbox",
apns_certificates: "Your apns certificate",
safari_apns_certificate: "Your Safari APNS certificate",
safari_site_origin: "The homename for your website for Safari Push, including http or https",
safari_push_id: "The certificate bundle ID for Safari Web Push",
safari_icon_16_16: "http://onesignal.com/safari_packages/e4e87830-b954-11e3-811d-f3b376925f15/16x16.png",
safari_icon_32_32: "http://onesignal.com/safari_packages/e4e87830-b954-11e3-811d-f3b376925f15/16x16@2.png",
safari_icon_64_64: "http://onesignal.com/safari_packages/e4e87830-b954-11e3-811d-f3b376925f15/32x32@2x.png",
safari_icon_128_128: "http://onesignal.com/safari_packages/e4e87830-b954-11e3-811d-f3b376925f15/128x128.png",
safari_icon_256_256: "http://onesignal.com/safari_packages/e4e87830-b954-11e3-811d-f3b376925f15/128x128@2x.png",
site_name: "The URL to your website for Web Push",
basic_auth_key: "NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj"
}
]
{}
View an app
View the details of a single OneSignal app
Requires Authentication Key
Requires your OneSignal User Auth Key, available in Keys & IDs.
id
String
Required An app id
Example Code - View an app
curl --include \
--header "Content-Type: application/json" \
--header "Authorization: Basic USER_AUTH_KEY" \
https://onesignal.com/api/v1/apps/YOUR_APP_ID
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/apps/YOUR_APP_ID");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
'Authorization: Basic YOUR_USER_AUTH_KEY'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$response = curl_exec($ch);
$response = json_decode($response, true);
curl_close($ch);
{
id: "92911750-242d-4260-9e00-9d9034f139ce",
name: "Your app 1",
players: 150,
messageable_players: 143,
updated_at: "2014-04-01T04:20:02.003Z",
created_at: "2014-04-01T04:20:02.003Z",
gcm_key: "a gcm push key",
chrome_key: "A Chrome Web Push GCM key",
chrome_web_origin: "Chrome Web Push Site URL",
chrome_web_gcm_sender_id: "Chrome Web Push GCM Sender ID",
chrome_web_default_notification_icon: "http://yoursite.com/chrome_notification_icon",
chrome_web_sub_domain:"your_site_name",
apns_env: "production",
apns_certificates: "Your apns certificate",
safari_apns_certificate: "Your Safari APNS certificate",
safari_site_origin: "The homename for your website for Safari Push, including http or https",
safari_push_id: "The certificate bundle ID for Safari Web Push",
safari_icon_16_16: "http://onesignal.com/safari_packages/92911750-242d-4260-9e00-9d9034f139ce/16x16.png",
safari_icon_32_32: "http://onesignal.com/safari_packages/92911750-242d-4260-9e00-9d9034f139ce/16x16@2.png",
safari_icon_64_64: "http://onesignal.com/safari_packages/92911750-242d-4260-9e00-9d9034f139ce/32x32@2x.png",
safari_icon_128_128: "http://onesignal.com/safari_packages/92911750-242d-4260-9e00-9d9034f139ce/128x128.png",
safari_icon_256_256: "http://onesignal.com/safari_packages/92911750-242d-4260-9e00-9d9034f139ce/128x128@2x.png",
site_name: "The URL to your website for Web Push",
basic_auth_key: "NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj"
}
Create an app
Creates a new OneSignal app
Requires Authentication Key
Requires your OneSignal User Auth Key, available in Keys & IDs.
name
String
Required The name of your new app, as displayed on your apps list on the dashboard. This can be renamed later.
apns_env
String
iOS - Either sandbox
or production
apns_p12
String
iOS - Your apple push notification p12 certificate file, converted to a string and Base64 encoded.
apns_p12_password
String
Required if adding p12 certificate iOS - Password for the apns_p12 file
gcm_key
String
Android - Your Google Push Messaging Auth Key
android_gcm_sender_id
String
Android - Your Google Project number. Also know as Sender ID.
chrome_web_origin
String
Chrome, Firefox - The URL to your website. This field is required if you wish to enable web push and specify other web push parameters.
chrome_web_default_notification_icon
String
Chrome - Your default notification icon. Should be 80x80 pixels.
chrome_web_sub_domain
String
Chrome - A subdomain of your choice in order to support Chrome Web Push on non-HTTPS websites. This field must be set in order for the chrome_web_gcm_sender_id
property to be processed.
safari_apns_p12
String
Safari - Your apple push notification p12 certificate file for Safari Push Notifications, converted to a string and Base64 encoded.
safari_apns_p12_password
String
Safari - Password for safari_apns_p12
file
site_name
String
Safari - The URL to your website
safari_site_origin
String
Safari - The hostname to your website including http(s)://
safari_icon_256_256
String
Safari - A url for a 256x256 png notification icon. This is the only Safari icon URL you need to provide.
chrome_key
String
Not for web push
Your Google Push Messaging Auth Key if you use Chrome Apps / Extensions.
additional_data_is_root_payload
Boolean
iOS - Notification data
(additional data) values will be added to the root of the apns payload when sent to the device.
Ignore if you're not using any other plugins or not using OneSignal SDK methods to read the payload.
organization_id
String
The Id of the Organization you would like to add this app to.
Example Code - Create an app
This method is used to create new apps in your OneSignal account. It allows you to specify your APNS and GCM auth tokens as well.
curl --include \
--request POST \
--header "Content-Type: application/json" \
--header "Authorization: Basic USER_AUTH_KEY" \
--data-binary "{\"name\" : \"Your app 1\",
\"apns_env\": \"production\",
\"apns_p12\": \"asdsadcvawe223cwef...\",
\"apns_p12_password\": \"FooBar\",
\"organization_id\": \"your_organization_id\",
\"gcm_key\": \"a gcm push key\"}" \
https://onesignal.com/api/v1/apps
<?PHP
function createApp(){
$fields = array(
'name' => "YOUR_APP_NAME",
'chrome_web_origin' => "YOUR_FULL_SITE_URL"
);
$fields = json_encode($fields);
print("\nJSON sent:\n");
print($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/apps");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8',
'Authorization: Basic YOUR_USER_AUTH_KEY'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
$response = createApp();
$return["allresponses"] = $response;
$return = json_encode( $return);
print("\n\nJSON received:\n");
print($return);
print("\n");
?>
{
id: "e4e87830-b954-11e3-811d-f3b376925f15",
name: "Your app 1",
players: 0,
messageable_players: 0,
updated_at: "2014-04-01T04:20:02.003Z",
created_at: "2014-04-01T04:20:02.003Z",
gcm_key: "a gcm push key",
chrome_web_origin: "Chrome Web Push Site URL",
chrome_web_default_notification_icon: "http://yoursite.com/chrome_notification_icon",
chrome_web_sub_domain:"your_site_name",
apns_env: "production",
apns_certificates: "Your apns certificate",
safari_apns_certificate: "Your Safari APNS certificate",
safari_site_origin: "The homename for your website for Safari Push, including http or https",
safari_push_id: "The certificate bundle ID for Safari Web Push",
safari_icon_16_16: "http://onesignal.com/safari_packages/e4e87830-b954-11e3-811d-f3b376925f15/16x16.png",
safari_icon_32_32: "http://onesignal.com/safari_packages/e4e87830-b954-11e3-811d-f3b376925f15/16x16@2.png",
safari_icon_64_64: "http://onesignal.com/safari_packages/e4e87830-b954-11e3-811d-f3b376925f15/32x32@2x.png",
safari_icon_128_128: "http://onesignal.com/safari_packages/e4e87830-b954-11e3-811d-f3b376925f15/128x128.png",
safari_icon_256_256: "http://onesignal.com/safari_packages/e4e87830-b954-11e3-811d-f3b376925f15/128x128@2x.png",
site_name: "The URL to your website for Web Push",
basic_auth_key: "NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj"
}
Update an app
Updates the name or configuration settings of an existing OneSignal app
This method can be used to update the name or configuration settings of one of your existing apps.
Same as POST /apps
The supported parameters are the same as the parameters for creating an application.
Updating Some Platforms Requires All Attributes To Be Set
Updating some platforms like Safari web push requires all parameters to be set (even if they are unchanged) in order for the update to be processed.
- To update only your app name, you can pass in only a new app name parameter.
- To update Android, be sure to pass in
gcm_key
. - To update Chrome Apps & Extensions, be sure to pass in
chrome_key
. - To update Chrome web push, be sure to pass in
chrome_web_origin
. - To update Safari web push, you must pass in all of these parameters:
safari_apns_p12
,safari_apns_p12_password
,site_name
, andsafari_site_origin
. Most users use our auto-generated Safari web ID. If you use our auto-generated Safari web ID, please setsafari_apns_p12
to""
andsafari_apns_p12_password
to""
. - To update iOS, you must pass in
apns_env
andapns_p12
.
Requires Authentication Key
Requires your OneSignal User Auth Key, available in Keys & IDs.
Example Code - Update an app
curl --include \
--request PUT \
--header "Content-Type: application/json" \
--header "Authorization: Basic YOUR_USER_AUTH_KEY" \
--data-binary "{\"name\" : \"Your app 1\",
\"apns_env\": \"production\",
\"apns_p12\": \"asdsadcvawe223cwef...\",
\"apns_p12_password\": \"FooBar\",
\"organization_id\": \"your_organization_id\",
\"gcm_key\": \"a gcm push key\"}" \
https://onesignal.com/api/v1/apps/YOUR_APP_ID
{
id: "e4e87830-b954-11e3-811d-f3b376925f15",
name: "Your app 1",
players: 0,
messageable_players: 0,
updated_at: "2014-04-01T04:20:02.003Z",
created_at: "2014-04-01T04:20:02.003Z",
gcm_key: "a gcm push key",
chrome_key: "A Chrome Web Push GCM key",
chrome_web_origin: "Chrome Web Push Site URL",
chrome_web_default_notification_icon: "http://yoursite.com/chrome_notification_icon",
chrome_web_sub_domain:"your_site_name",
apns_env: "production",
apns_certificates: "Your apns certificate",
safari_apns_certificate: "Your Safari APNS certificate",
safari_site_origin: "The homename for your website for Safari Push, including http or https",
safari_push_id: "The certificate bundle ID for Safari Web Push",
safari_icon_16_16: "http://onesignal.com/safari_packages/e4e87830-b954-11e3-811d-f3b376925f15/16x16.png",
safari_icon_32_32: "http://onesignal.com/safari_packages/e4e87830-b954-11e3-811d-f3b376925f15/16x16@2.png",
safari_icon_64_64: "http://onesignal.com/safari_packages/e4e87830-b954-11e3-811d-f3b376925f15/32x32@2x.png",
safari_icon_128_128: "http://onesignal.com/safari_packages/e4e87830-b954-11e3-811d-f3b376925f15/128x128.png",
safari_icon_256_256: "http://onesignal.com/safari_packages/e4e87830-b954-11e3-811d-f3b376925f15/128x128@2x.png",
site_name: "The URL to your website for Web Push",
basic_auth_key: "NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj"
}
View devices
View the details of multiple devices in one of your OneSignal apps
Requires Authentication Key
Requires your OneSignal App's REST API Key, available in Keys & IDs.
Unavailable for Apps > 100,000 users
For performance reasons, this method is not available for larger apps. Larger apps should use the CSV export API endpoint, which is much more performant.
app_id
String
Required The app ID that you want to view devices from
limit
String
How many devices to return. Max is 300. Default is 300
offset
String
Result offset. Default is 0. Results are sorted by id;
invalid_identifier
boolean
If true
, this is the equivalent of a user being Unsubscribed (as seen in All Users).
Example Code - View devices
See our PUT player call for a description of the fields listed below in the example.
curl --include \
--header "Authorization: Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj" \
"https://onesignal.com/api/v1/players?app_id={appId}&limit=300&offset=0"
<?php
// NOTE: Only fetches the first 300 devices.
// Will need to add looping with offset to get all devices.
function getDevices(){
$app_id = "YOUR_ONESIGNAL_APP_ID_HERE";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/players?app_id=" . $app_id);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
'Authorization: Basic YOUR_ONESIGNAL_APP_AUTH_KEY_HERE'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
$response = getDevices();
$return["allresponses"] = $response;
$return = json_encode( $return);
print("\n\nJSON received:\n");
print($return);
print("\n")
?>
{
"total_count":3,
"offset":2,
"limit":2,
"players":
[
{
"identifier":"ce777617da7f548fe7a9ab6febb56cf39fba6d382000c0395666288d961ee566",
"session_count":1,
"language":"en",
"timezone":-28800,
"game_version":"1.0",
"device_os":"7.0.4",
"device_type":0,
"device_model":"iPhone",
"ad_id":null,
"tags":{"a":"1","foo":"bar"},
"last_active":1395096859,
"amount_spent":0.0,
"created_at":1395096859,
"invalid_identifier":false,
"badge_count": 0,
"external_user_id": null
}
]
}
View device
View the details of an existing device in one of your OneSignal apps
See our Add a device documentation for descriptions of the fields.
Path Parameters
id
String
Player's OneSignal ID
email_auth_hash
String
Email - Only required if you have enabled Identity Verification and device_type
is email (11
).
app_id
String
Your app_id for this device
curl --include
https://onesignal.com/api/v1/players/PLAYER_ID?app_id=APP_ID
{
"identifier":"ce777617da7f548fe7a9ab6febb56cf39fba6d382000c0395666288d961ee566",
"session_count":1,
"language":"en",
"timezone":-28800,
"game_version":"1.0",
"device_os":"7.0.4",
"device_type":0,
"device_model":"iPhone",
"ad_id":null,
"tags":{"a":"1","foo":"bar"},
"last_active":1395096859,
"amount_spent":0.0,
"created_at":1395096859,
"invalid_identifier":false,
"badge_count": 0,
"external_user_id": null
}
Add a device
Register a new device to one of your OneSignal apps
Don't use this
This API endpoint is designed to be used from our open source Mobile and Web Push SDKs. It is not designed for developers to use it directly, unless instructed to do so by OneSignal support.
If you use this method instead of our SDKs, many OneSignal features such as conversion tracking, timezone tracking, language detection, and rich-push won't work out of the box. It will also make it harder to identify possible setup issues.
This method is used to register a new device with OneSignal.
If a device is already registered with the specified identifier, then this will update the existing device record instead of creating a new one.
The returned player is a player / user ID. Use the returned ID to send push notifications to this specific user later, or to include this player when sending to a set of users.
iOS
Must set test_type
to 1
when building your iOS app as development. Omit this field in your production app builds.
device_type
Int
Required The device's platform:0
= iOS1
= Android2
= Amazon3
= WindowsPhone (MPNS)4
= Chrome Apps / Extensions5
= Chrome Web Push6
= Windows (WNS)7
= Safari8
= Firefox9
= MacOS10
= Alexa11
= Email
email_auth_hash
String
Only required if you have enabled Identity Verification and device identifier is email.
identifier
String
Recommended Push notification identifier from Google or Apple. For Apple push identifiers, you must strip all non alphanumeric characters.
Examples:
iOS 7abcd558f29d0b1f048083e2834ad8ea4b3d87d8ad9c088b33c132706ff445f0
Android APA91bHbYHk7aq-Uam_2pyJ2qbZvqllyyh2wjfPRaw5gLEX2SUlQBRvOc6sck1sa7H7nGeLNlDco8lXj83HWWwzV...
language
String
Recommended Language code. Typically lower case two letters, except for Chinese where it must be one of zh-Hans
or zh-Hant
. Example: en
timezone
Int
Recommended Number of seconds away from UTC. Example: -28800
game_version
String
Recommended Version of your app. Example: 1.1
device_model
String
Recommended Device make and model. Example: iPhone5,1
device_os
String
Recommended Device operating system version. Example: 7.0.4
ad_id
String
Recommended The ad id for the device's platform:
Android = Advertising Id
iOS = identifierForVendor
WP8.1 = AdvertisingId
sdk
String
Recommended Name and version of the plugin that's calling this API method (if any)
session_count
Int
Number of times the user has played the game, defaults to 1
tags
Hash
Custom tags for the player. Only support string key value pairs. Does not support arrays or other nested objects. Example: {"foo":"bar","this":"that"}
amount_spent
String
Amount the user has spent in USD, up to two decimal places
created_at
Int
Unix timestamp indicating date and time when the player joined the app/site.
playtime
Int
Seconds player was running your app.
badge_count
Int
Current iOS badge count displayed on the app icon
NOTE: Not supported for apps created after June 2018, since badge count for apps created after this date are handled on the client.
last_active
Int
Date and time when the player was last active.
Format: yyyy-mm-dd hh24:mi:ss.US
UTC+0
notification_types
Int
1
= subscribed-2
= unsubscribed
iOS - These values are set each time the user opens the app from the SDK. Use the SDK function set Subscription instead.
Android - You may set this but you can no longer use the SDK method setSubscription later in your app as it will create synchronization issues.
test_type
Int
This is used in deciding whether to use your iOS Sandbox or Production push certificate when sending a push when both have been uploaded. Set to the iOS provisioning profile that was used to build your app.1
= Development2
= Ad-Hoc
Omit this field for App Store builds.
long
Double
Longitude of the device, used for geotagging to segment on.
lat
Double
Latitude of the device, used for geotagging to segment on.
country
String
Country code in the ISO 3166-1 Alpha 2 format
external_user_id
String
A custom user ID
curl --include \
--request POST \
--header "Content-Type: application/json" \
--data-binary "{\"app_id\" : \"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\",
\"identifier\":\"ce777617da7f548fe7a9ab6febb56cf39fba6d382000c0395666288d961ee566\",
\"language\":\"en\",
\"timezone\":-28800,
\"game_version\":\"1.0\",
\"device_os\":\"7.0.4\",
\"device_type\":0,
\"device_model\":\"iPhone 8,2\",
\"tags\":{\"a\":\"1\",\"foo\":\"bar\"}}" \
https://onesignal.com/api/v1/players
<?PHP
$fields = array(
'app_id' => "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
'identifier' => "ce777617da7f548fe7a9ab6febb56cf39fba6d382000c0395666288d961ee566",
'language' => "en",
'timezone' => "-28800",
'game_version' => "1.0",
'device_os' => "9.1.3",
'device_type' => "0",
'device_model' => "iPhone 8,2",
'tags' => array("foo" => "bar")
);
$fields = json_encode($fields);
print("\nJSON sent:\n");
print($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/players");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$response = curl_exec($ch);
curl_close($ch);
$return["allresponses"] = $response;
$return = json_encode( $return);
print("\n\nJSON received:\n");
print($return);
print("\n");
?>
{"success": true, "id": "ffffb794-ba37-11e3-8077-031d62f86ebf" }
Edit device
Update an existing device in one of your OneSignal apps
Warning - Web / Mobile SDK
Instead of using this REST API call we recommend using our Mobile / Web SDK methods. Changes values with this REST API call may create synchronization issues with the SDK.
id
String
Required The device's OneSignal ID
identifier
String
Push notification identifier from Google or Apple. For Apple push identifiers, you must strip all non alphanumeric characters. Example: ce777617da7f548fe7a9ab6febb56
language
String
Language code. Typically lower case two letters, except for Chinese where it must be one of zh-Hans
or zh-Hant
. Example: en
timezone
Int
Number of seconds away from UTC. Example: -28800
game_version
String
Version of your app. Example: 1.1
device_model
String
Device make and model. Example: iPhone5,1
device_os
String
Device operating system version. Example: 7.0.4
ad_id
String
The ad id for the device's platform:
Android = Advertising Id
iOS = identifierForVendor
WP8.0 = DeviceUniqueId
WP8.1 = AdvertisingId
sdk
String
Name and version of the sdk/plugin that's calling this API method (if any)
session_count
Int
Number of times the user has played the game, defaults to 1
tags
Hash
Custom tags for the player. Only support string key value pairs. Does not support arrays or other nested objects. Example: {"foo":"bar","this":"that"}
Limitations:
- 100 tags per call
- Android SDK users: tags cannot be removed or changed via API if set through SDK
sendTag
methods.
Recommended to only tag devices with 1 kilobyte of data
Please consider using your own Database to save more than 1 kilobyte of data. See: Internal Database & CRM
amount_spent
String
Amount the user has spent in USD, up to two decimal places
created_at
Int
Unixtime when the player joined the game
playtime
Int
Seconds player was running your app.
badge_count
Int
Current iOS badge count displayed on the app icon
NOTE: Not supported for apps created after June 2018, since badge count for apps created after this date are handled on the client.
last_active
Int
Unixtime when the player was last active
notification_types
Int
1
= subscribed-2
= unsubscribed
iOS - These values are set each time the user opens the app from the SDK. Use the SDK function set Subscription instead.
Android - You may set this but you can no longer use the SDK method setSubscription later in your app as it will create synchronization issues.
test_type
Int
This is used in deciding whether to use your iOS Sandbox or Production push certificate when sending a push when both have been uploaded. Set to the iOS provisioning profile that was used to build your app.1
= Development2
= Ad-Hoc
Omit this field for App Store builds.
long
Double
Longitude of the device, used for geotagging to segment on.
lat
Double
Latitude of the device, used for geotagging to segment on.
country
String
Country code in the ISO 3166-1 Alpha 2 format
external_user_id
String
A custom user ID
Deleting Tags
To delete a tag, include its key and set its value to blank. Omitting a key/value will not delete it.
For example, if I wanted to delete two existing tags rank
and category
while simultaneously adding a new tag class
, the tags
JSON would look like the following:
"tags": {
"rank": "",
"category": "",
"class": "my_new_value"
}
curl --include \
--request PUT \
--header "Content-Type: application/json" \
--data-binary "{\"app_id\" : \"APP_ID\",
\"language\":\"es\",
\"timezone\":-28800,
\"game_version\":\"1.0\",
\"device_os\":\"7.0.4\",
\"device_type\":0,
\"device_model\":\"iPhone\",
\"tags\":{\"a\":\"1\",\"foo\":\"\"}}" \
https://onesignal.com/api/v1/players/PLAYER_ID
<?PHP
$playerID = '8dee0e23-410d-4a9a-b8ce-bfe4c5257ccc';
$fields = array(
'app_id' => '02b297e7-abb5-4e7e-9c2a-9ce7e2c82ff5',
'tags' => array('OneSignal_Example_Tag' => 'YES')
);
$fields = json_encode($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://onesignal.com/api/v1/players/'.$playerID);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
curl_close($ch);
$resultData = json_decode($response, true);
echo $resultData;
?>
{"success": true }
New session
Update a device's session information
This method should be called when a device opens your app after they are already registered. This method will automatically increment the player's session_count
, and should also be used to update any fields that may have changed (such as language or timezone).
If a player record is not found, a new one will be created if and only if the request includes a device_type.
Body Parameters - New session
identifier
String
Recommended Push notification identifier from Google or Apple. For Apple push identifiers, you must strip all non alphanumeric characters. Example: ce777617da7f548fe7a9ab6febb56
language
String
Recommended Language code. Typically lower case two letters, except for Chinese where it must be one of zh-Hans
or zh-Hant
. Example: en
timezone
Int
Recommended Number of seconds away from UTC. Example: -28800
game_version
String
Recommended Version of your app. Example: 1.1
device_os
String
Recommended Device operating system version. Example: 7.0.4
ad_id
String
Recommended The ad id for the device's platform:
Android = Advertising Id
iOS = identifierForVendor
WP8.0 = DeviceUniqueId
WP8.1 = AdvertisingId
sdk
String
Recommended Name and version of sdk/plugin that's calling this method.
tags
Object
Custom tags for the player. Only support string key value pairs. Does not support arrays or other nested objects. Example: {"foo":"bar","this":"that"}
device_type
Int
If included, will create a new player record if the one is not found. Possible values are the same as device_type
in the add device call
curl --include \
--request POST \
--header "Content-Type: application/json" \
--data-binary "{\"language\":\"es\",
\"timezone\":-28800,
\"game_version\":\"1.0\",
\"device_os\":\"7.0.4\"}" \
https://onesignal.com/api/v1/players/:id/on_session
{"success": true }
New purchase
Track a new purchase in your app
purchases
Array
Required An array of purchases, each with the properties listed below.
purchases[sku]
String
Required The unique identifier of the purchased item.
purchases[amount]
Double
Required The amount, in USD, spent purchasing the item.
purchases[iso]
String
Required The 3-letter ISO 4217 currency code. Required for correct storage and conversion of amount.
existing
Boolean
Pass true on the first run of your app if you're tracking existing non-consumable purchases. This prevents tracking the same purchases more than once if the user re-installs your app.
curl --include \
--request POST \
--header "Content-Type: application/json" \
--data-binary "{\"purchases\": [{\"sku\": \"SKU123\", \"iso\": \"USD\", \"amount\": \"0.99\"}]}" \
https://onesignal.com/api/v1/players/:id/on_purchase
{
"purchases":
[{"sku": "SKU123",
"iso": "USD",
"amount": "0.99"}]
}
{"success": true }
Increment session length
Update a device's session length upon app resuming
Call this method when the app is resumed or placed into from standby.
The active_time field should be set to the duration between the last on_focus call since the app was opened. If no previous on_focus was called, then the duration should be either the time since POST /players/:id/on_session
or POST /players
were called.
Body Parameters - Increment session length
state
String
Required Set to "ping"
active_time
Int
Required The lesser of: The number of seconds since either: 1. on_focus was last called OR 2. on_session or the device first registered (POST /players)
curl --include \
--request POST \
--header "Content-Type: application/json" \
--data-binary "{\"state\": \"ping\",
\"active_time\": 60}" \
https://onesignal.com/api/v1/players/:id/on_focus
{"success": true }
CSV export
Generate a compressed CSV export of all of your current user data
This method can be used to generate a compressed CSV export of all of your current user data. It is a much faster alternative than retrieving this data using the ./players API endpoint.
You can test if it is complete by making a GET request to the csv_file_url value. If the file is not ready, a 403 error will be returned. Otherwise the file itself will be returned.
The file will be compressed using GZip.
The file may take several minutes to generate depending on the number of users in your app.
Requires Authentication Key
Requires your OneSignal App's REST API Key, available in Keys & IDs.
Concurrent Exports
Only one concurrent export is allowed per OneSignal account. Please ensure you have successfully downloaded the .csv.gz
file before exporting another app.
app_id
String
Required The app ID that you want to export devices from
extra_fields
Array of Strings
iOS Android
Additional fields that you wish to include. Currently supports location
, country
, rooted
, notification_types
, as_id
, ip
, external_user_id
, web_auth
, and web_p256
.
last_active_since
Unixtime in Seconds
Export all devices with a last_active timestamp greater than this time.
segment_name
String
Export all devices belong to the segment
curl -X POST -H "Authorization: Basic YOUR_REST_API_KEY" -H "Content-Type: application/json" -d '{
"extra_fields": ["country","notification_types","external_user_id", "location", "rooted", "ip", "country", "web_auth", "web_p256"],
"last_active_since": "1469392779", "segment_name": "Active Users"
}' "https://onesignal.com/api/v1/players/csv_export?app_id=YOUR_APP_ID"
{ "csv_file_url": "https://onesignal.com/csv_exports/b2f7f966-d8cc-11e4-bed1-df8f05be55ba/users_184948440ec0e334728e87228011ff41_2015-11-10.csv.gz" }
{}
View notification
View the details of a single notification
Requires Authentication Key
Requires your OneSignal App's REST API Key, available in Keys & IDs.
id
String
Required Notification ID
app_id
String
Required App ID
curl --include \
--header "Authorization: Basic YOUR_REST_API_KEY" \
https://onesignal.com/api/v1/notifications/THE_NOTIFICATION_ID?app_id=YOUR_APP_ID
<?PHP
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications/YOUR_NOTIFICATION_ID?app_id=YOUR_APP_ID");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
'Authorization: Basic AUTH_KEY'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$response = curl_exec($ch);
curl_close($ch);
$return["allresponses"] = $response;
$return = json_encode( $return);
print("\n\nJSON received:\n");
print($return);
print("\n");
?>
Returned Fields
remaining
- Number of notifications that have not been sent out yet. This can mean either our system is still processing the notification or you have delayed options set.successful
- Number of notifications that were sent to Google/Apple servers.failed
- Number of notifications that could not be delivered due to those devices being unsubscribed.errored
- Number of notifications that could not be delivered due to an error. You can find more information by viewing the notification in the dashboard.converted
- Number of users who have clicked / tapped on your notification.queued_at
- Unix timestamp indicating when the notification was createdsend_after
- Unix timestamp indicating when notification delivery should begin.completed_at
- Unix timestamp indicating when notification delivery completed. The delivery duration from start to finish can be calculated withcompleted_at
-send_after
.platform_delivery_stats
- Hash of delivery statistics broken out by target device platform. See the section below for additional detail.
platform_delivery_stats
response field details
Keys present in this hash correspond to the platforms targeted by the notification. For instance, if the push was sent to iOS and Android devices, the hash will have keys ios
and android
. The full mapping is enumerated below.
- iOS -
ios
- Android -
android
- Amazon Fire -
amazon_fire
- Windows Phone 8.0 -
windows_phone_legacy
- Chrome Browser Extensions -
chrome_extension
- Chrome Web Push -
chrome_web_push
- Windows Desktop and Phone -
windows
- Safari Browser Push -
safari_web_push
- Fixefox Web Push -
firefox_web_push
- macOS Desktop Push -
mac_os
- Alexa Messages -
amazon_alexa
- Email -
email
- MS Edge Web Push -
edge_web_push
Each value in this object is a per-platform object containing success
, the number of notifications successfully handed off to the upstream provider, failed
, the number of notifications rejected by the upstream provider for reasons such as being unsubscribed, and errored
, the number of messages rejected by the upstream provider for things like configuration errors, server errors, and etc.
The following example is for a notification sent to both iOS and Android, and the platform_delivery_stats
object contains objects ios
and android
.
The data in this field can be considered final once delivery is completed -- that is, when the completed_at
field has a valid timestamp. During delivery, these values are subject to change.
Result Format - View notification
{
"id": "481a2734-6b7d-11e4-a6ea-4b53294fa671",
"successful": 15,
"failed": 1,
"converted": 3,
"remaining": 0,
"queued_at": 1415914655,
"send_after": 1415914655,
"completed_at": 1415914656,
"url": "https://yourWebsiteToOpen.com",
"data":{
"foo": "bar",
"your": "custom metadata"
},
"canceled": false,
"headings":{
"en": "English and default language heading",
"es": "Spanish language heading"
},
"contents":{
"en": "English language content",
"es": "Hola"
},
"platform_delivery_stats":{
"ios": {
"success": 5,
"failed": 1,
"errored": 0
},
"android": {
"success": 10,
"failed": 0,
"errored": 0
}
}
}
View notifications
View the details of multiple notifications
Requires Authentication Key
Requires your OneSignal App's REST API Key, available in Keys & IDs.
API Notification Deletion
OneSignal periodically deletes records of API notifications older than 30 days.
If you would like to export all notification data to CSV, you can do this through our dashboard using a Paid Plan.
app_id
String
Required The app ID that you want to view notifications from
limit
String
How many notifications to return. Max is 50. Default is 50
offset
Integer
Page offset. Default is 0. Results are sorted by queued_at in descending order. queued_at is a representation of the time that the notification was queued at.
kind
Integer
Kind of notifications returned. Default (not set) is all notification types.
Dashboard only is 0.
API only is 1.
Automated only is 3.
curl --include \
--header "Authorization: Basic YOUR_REST_API_KEY" \
"https://onesignal.com/api/v1/notifications?app_id=YOUR_APP_ID"
<?PHP
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://onesignal.com/api/v1/notifications?app_id=3cb5beaa-e6ca-5932-aad9-fdabaa3b83ce&limit=50&offset=0",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"authorization: Basic ONESIGNAL_APP_REST_API_KEY_HERE",
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
echo $response;
?>
Result Format - View notifications
Due to large amount of data returned, omitted lines indicated with ...
{
"total_count": 553,
"offset": 0,
"limit": 1,
"notifications": [
{
"app_id": "3beb3078-e0f1-4629-af17-fde833b9f716",
"chrome_web_icon": "https://img.onesignal.com/t/73b9b966-f19e-4410-8b5d-51ebdef4652e.png",
"contents": {
"en": "Come by and check out our new Jordan's!!! (Shoes) 🎃🙊👻"
},
"converted": 0,
"data": {
"your_data_key": "your_data_value"
},
,
"errored": 1,
"excluded_segments": [
"3 Days Inactive"
],
"failed": 0,
"headings": {
"en": "Thomas' Greatest Site in the World!! 😜😁"
},
"id": "e664a747-324c-406a-bafb-ab51db71c960",
"included_segments": [
"all"
],
"queued_at": 1557946677,
"remaining": 0,
"send_after": 1557946620,
"completed_at": 1557946677,
"successful": 386,
"url": "https://mysite.com",
"platform_delivery_stats": {
"chrome_web_push": {
"successful": 14,
"failed": 0,
"errored": 0
},
"android": {
"errored": 1,
"successful": 368,
"failed": 0
},
"safari_web_push": {
"successful": 2,
"failed": 0,
"errored": 0
},
"ios": {
"successful": 1,
"failed": 0,
"errored": 0
},
"firefox_web_push": {
"successful": 1,
"failed": 0,
"errored": 0
}
},
"ios_attachments": {
"id": "https://img.onesignal.com/n/44843933-68d4-450c-af5c-5e5c1a9d946e.jpg"
}
}
]
}
Notification History
View the devices sent a notification - Required: OneSignal Paid Plan
This method will return all devices that were sent the given notification_id
if used within 7 days of the date sent. After 7 days of the sending date, the notification history data will be unavailable.
After a successful response is received, the destination url may be polled until the file becomes available. Most exports are done in ~1-3 minutes, so setting a poll interval of 10 seconds should be adequate.
For use cases that are not meant to be consumed by a script, an email will be sent to the supplied email address.
Requirements
1. A OneSignal Paid Plan.
2. Turn on Send History via OneSignal API in Settings -> Analytics. Cannot get data before this was turned on.
3. Must be called within 7 days after sending the notification.
4. Notifications targeting under 1000 recipients will not have "sent"
events recorded, but will show "clicked"
events.
5. Requires your OneSignal App's REST API Key
, available in Keys & IDs.
events
string
Required: The type of device data to be exported.
"sent"
will return all player ids that were sent the given notification id. Notification must target 1000+ devices for data to be available."clicked"
will return all the player ids that clicked the given notification id.
app_id
string
Required: Your OneSignal App Id. Must have Analytics turned on in dashboard.
email
string
Required: Email of which to send the device data.
curl -X POST \
https://app.onesignal.com/api/v1/notifications/{notification_id}/history \
-H 'Authorization: Basic YOUR_REST_API_KEY' \
-H 'Cache-Control: no-cache' \
-H 'Content-Type: application/json' \
-d '{
"events": "clicked",
"app_id": "YOUR_ONESIGNAL_APP_ID",
"email": "your_email@email.com"
}'
{
"events": "sent",
"app_id": "OneSignal_App_Id",
"email": "Email_to_send_data"
}
Create Segments
Create segments visible and usable in the dashboard and API - Required: OneSignal Paid Plan
The Create Segment method is used when you want your server to programmatically create a segment instead of using the OneSignal Dashboard UI. Just like creating Segments from the dashboard you can pass in filters
with multiple "AND"
or "OR"
operator
's.
Requirements
Requires your OneSignal App's REST API Key, available in Keys & IDs.
id
UUID
UUID of this segment. If left empty, it will be assigned automatically.
name
string
Required: Name of the segment you're creating. You'll see this name on the web UI.
filters
array(Filter
| Operator
)
Required: Filters or operators the segment will have.
For a list of available filters
with details, please see above Send To Users Based On Filters
Filter
Parameters
Filter
is a type of object that can be an element of the filters
parameter to the above Send To Users Based On Filters proposed API.
key
string
if field
is tag
, this field is required to specify a key
inside the tags.
field
string
Required Name of the field to use as the first operand in the filter expression.
value
string
Constant value to use as the second operand in the filter expression. This value is required when the operator is a binary operator.
relation
string
Required Operator of a filter expression (e.g. ">"
, "<"
, "="
, "!="
, "exists"
, "not_exists"
, "time_elapsed_gt"
, "time_elapsed_lt"
)
Operator
Parameters
Unlike targeting devices with filters
, you must specify an "AND"
when creating segments/
operator
string
Required Strictly, this must be either "OR"
or "AND"
$ curl -XPOST \
-H'Authorization: Basic YOUR_REST_API_KEY' \
-H'Content-Type: application/json' \
https://onesignal.com/api/v1/apps/YOUR_APP_ID/segments \
-d '{"name": "1", "filters": [{"field": "session_count", "relation": ">", "value": "1"},{"operator": "AND"}, {"field": "tag", "relation": "!=", "key": "tag_key", "value": "1"},{"operator": "OR"}, {"field": "last_session", "relation": "<", "value": "30"}]}'
{
"name": "Segment 2",
"filters": [
{"field": "session_count", "relation": ">", "value": "1"},
{"operator": "AND"},
{"field": "tag", "relation": "!=", "key": "tag_key", "value": "1"},
{"operator": "OR"},
{"field": "last_session", "relation": "<", "hours_ago": "30"}
]
}
// Always true, "id" is uuid of created segment
{"success": true, "id": "7ed2887d-bd24-4a81-8220-4b256a08ab19"}
{"success": false, "errors": ["Segment with the given id already exists."]}
//Always false, error will explain why request failed
{"success": false, "errors": ["name is required"]}
Delete Segments
Delete segments - Required: OneSignal Paid Plan
You can delete a segment under your app by calling this API. You must provide an API key in the Authorization header that has admin access on the app.
Requirements
Requires your OneSignal App's REST API Key, available in Keys & IDs.
The segment_id
can be found in the URL of the segment when viewing it in the dashboard.
$ curl -XDELETE \
-H'Authorization: Basic YOUR_REST_API_KEY' \
-H'Content-Type: application/json' \
https://onesignal.com/api/v1/apps/YOUR_APP_ID/segments/YOUR_SEGMENT_ID