Sends notifications to your users
OneSignal's Hiring!
If you love OneSignal and would like to work here, let us know! Feel free to browse our open positions and apply on our careers page: https://onesignal.com/careers
The Create Notification method is used when you want your server to programmatically send messages. You may target users in one of three ways using this method: by Segment, by Filter, or by User ID. 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
include_external_user_ids
parameter withfilters
. You must use one or the other.
Send to Segments
Segments are the most common way to target large groups of devices. Sending to segments is easy: you simply specify which segments you want to target and, optionally, which ones you don't.
Parameter | Type | Description |
---|---|---|
included_segments | array_string | 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.
Example Code
Send to Users Based on Filters
Filters work the same as segments without needing to create the segment first. Filters can be combined to form advanced, highly precise user targeting.
The filters
parameter targets notification recipients using an array of JSON objects containing field conditions to check. The following are filter field options:
field | Description |
---|---|
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 see Language & Localization. |
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 To send emails to specific email addresses use |
country | relation = "=" value = 2-digit Country codeExample: "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. AND
s have priority overOR
s.- 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"}
]
Example Code
Send to Specific Devices
You may also target specific devices. Targeting devices is typically used in two ways:
-
For transactional notifications that target individual users.
-
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:
Parameter | Type | Description |
---|---|---|
include_player_ids | array_string | Specific playerids 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 | 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, email, or sms subscribers with same ids, use with channel_for_external_user_ids to indicate you are sending a push or email or sms. |
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: [email protected] Limit of 2,000 entries per REST API call |
include_phone_numbers | array_string | Recommended for Sending SMS - Target specific phone numbers. The phone number should be in the E.164 format. Phone number should be an existing subscriber on OneSignal. Refer our docs to learn how to add phone numbers to OneSignal. Example phone number: +1999999999 Limit of 2,000 entries per REST API call |
include_ios_tokens | array_string | Not Recommended: Please consider using include_player_ids or include_external_user_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 or include_external_user_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 or include_external_user_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 or include_external_user_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 or include_external_user_ids instead.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 or include_external_user_ids instead.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 |
Common Parameters
The following are parameters in Create Notifications common to all methods of targeting users.
App
Parameter | Type | Platform | Description |
---|---|---|---|
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 . |
Idempotency
Parameter | Type | Platform | Description |
---|---|---|---|
external_id | string (UUID) | All | Correlation and idempotency key. A request received with this parameter will first look for another notification with the same 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 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.
Parameter | Type | Platform | Description |
---|---|---|---|
contents | object | All - Push | 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 tag substitutions. English must be included in the hash. Example: {"en": "English Message", "es": "Spanish Message"} |
headings | object | All - Push | Required for Huawei Web Push requires a heading but can be omitted from request since defaults to the Site Name set in OneSignal Settings. 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 tag substitutions. Example: {"en": "English Title", "es": "Spanish Title"} |
name | string | All | Optional for Push. An identifier for tracking message within the OneSignal dashboard or export analytics. Not shown to end user. |
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. Example: |
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: |
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. |
target_content_identifier | string | iOS 13+ | Use to target a specific experience in your App Clip, or to target your notification to a specific window in a multi-scene App. |
Email Content
If you are sending an email, use the following parameters:
Parameter | Type | Description |
---|---|---|
email_subject | string | Required: The subject of the email. |
email_body | string (HTML supported) | Required unless The body of the email you wish to send. Typically, customers include their own HTML templates here. Must include 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 not specified, will default to "from name" set in the OneSignal Dashboard Email Settings. |
email_from_address | string (valid email address) | The email address the email is from. If not specified, will default to "from email" set in the OneSignal Dashboard Email Settings. |
name | string | Optional for Email. An identifier for tracking message within the OneSignal dashboard or export analytics. Not shown to end user. |
SMS Content
If you are sending an SMS, use the following parameters.
Parameter | Type | Description |
---|---|---|
name | string | Required for SMS Messages. An identifier for tracking message within the OneSignal dashboard or export analytics. Not shown to end user. |
sms_from | string | Phone Number used to send SMS. Should be a registered Twilio phone number. OneSignal supports sending SMS using regular 10 digit long codes, short codes, and toll-free numbers. |
contents | string | Text content for the SMS |
sms_media_urls | array_string | URLs for the media files to be attached to the SMS content. Limit: 10 media urls with a total max. size of 5MBs. |
Attachments
Push notifications only
These are additional content attached to push notifications, primarily images.
Parameter | Type | Platform | Description |
---|---|---|---|
data | object | All | A custom map of data that is passed back to your app. Same as using Additional Data within the dashboard. Can use up to 2048 bytes of data.Example: {"abc": 123, "foo": "bar", "event_performed": true, "amount": 12.1} |
huawei_msg_type | string | Huawei | Use "data" or "message" depending on the type of notification you are sending. More details in Data & Background Notifications. |
url | string | All | The URL to open in the browser when a user clicks on the notification. Example: https://onesignal.com Note: iOS needs https or updated NSAppTransportSecurity in plist This field supports tag substitutions. Omit if including web_url or app_url |
web_url | string | Push - All Browsers | Same as url but only sent to web push platforms.Including Chrome, Firefox, Safari, Opera, etc. |
app_url | string | Push - Mobile 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. |
huawei_big_picture | string | Huawei | Picture to display in the expanded view. Can be a drawable resource name or a URL. |
chrome_web_image | string | Chrome 56+ | Sets the web push notification's large image to be shown below the notification's title and text. Please see Web Push Notification Icons. |
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
Push notifications only
These add buttons to push notifications, allowing the user to take more than one action on a notification. Learn more about Action Buttons.
Parameter | Type | Platform | Description |
---|---|---|---|
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: |
web_buttons | array_object | Chrome 48+ | Add action buttons to the notification. The id field is required.Example: |
ios_category | string | iOS | Category APS payload, use with registerUserNotificationSettings:categories in your Objective-C / Swift code.Example: iOS 10+ This will trigger your UNNotificationContentExtension whose ID matches this category. |
Appearance
Push notifications only
These parameters let you adjust icons, badges, and other appearance changes to your push notifications.
Android & Huawei Notification Categories / Channels
- Allows customizing Importance, Sound, Vibration, LED Color, Badges, and Lockscreen Visibility.
- Required to customize these options on Android 8 (Oreo) based devices.
- OneSignal SDK handles fallback to Android 7 and older, no need to set field level values if
android_channel_id
is set.
- OneSignal SDK handles fallback to Android 7 and older, no need to set field level values if
- See the Category documentation on more details on creating and using them.
Icons - Different platforms handle icons differently.
- Android - The OneSignal SDK shows a bell icon by default. See our Android Notification Icons guide to change this.
- Huawei- Defaults to the App Icon. 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.
Badges - Useful to indicate to the user the number of notifications outstanding.
- iOS - Can customize the number badge number on the app icon.
- Android - Always reflects the number of notifications in the shade.
- The OneSignal SDK automatically handles this behavior.
Parameter | Type | Platform | Description |
---|---|---|---|
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. |
huawei_channel_id | UUID | Huawei | 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. |
huawei_existing_channel_id | string | Huawei | 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.
Example: |
small_icon | string | Android | Icon shown in the status bar and on the top left of the notification. 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 |
huawei_small_icon | string | Huawei | Icon shown in the status bar and on the top left of the notification. Use an Android resource path (E.g. /drawable/small_icon ).Defaults to your app icon if not set. |
large_icon | string | Android | Can be a drawable resource name or a URL. See: How to create large icons |
huawei_large_icon | string | Huawei | 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 | 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 | 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 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 Example: |
android_sound | string | Android | ⚠Deprecated, this field doesn't work on Android 8 (Oreo) and newer devices! Please use Notification Categories / Channels noted above instead to support ALL versions of Android. Sound file that is included in your app to play instead of the default device notification sound. Pass NOTE: Leave off file extension for Android. Example: |
huawei_sound | string | Huawei | ⚠Deprecated, this field ONLY works on EMUI 5 (Android 7 based) and older devices. Please also set Notification Categories / Channels noted above to support EMUI 8 (Android 8 based) devices. Sound file that is included in your app to play instead of the default device notification sound. NOTE: Leave off file extension for and include the full path. Example: |
adm_sound | string | Amazon | ⚠Deprecated, this field doesn't work on Android 8 (Oreo) and newer devices! Please use Notification Categories / Channels noted above instead to support ALL versions of Android. Sound file that is included in your app to play instead of the default device notification sound. Pass NOTE: Leave off file extension for Android. Example: |
wp_wns_sound | string | Windows | Sound file that is included in your app to play instead of the default device notification sound. Example: |
android_led_color | string | Android | ⚠Deprecated, this field doesn't work on Android 8 (Oreo) and newer devices! Please use Notification Categories / Channels noted above instead to support ALL versions of Android. Sets the devices LED notification light if the device has one. ARGB Hex format. Example(Blue): |
huawei_led_color | string | Huawei | ⚠Deprecated, this field ONLY works on EMUI 5 (Android 7 based) and older devices. Please also set Notification Categories / Channels noted above to support EMUI 8 (Android 8 based) devices. Sets the devices LED notification light if the device has one. RGB Hex format. Example(Blue): |
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): |
huawei_accent_color | string | Huawei | Accent Color used on Action Buttons and Group overflow count. Uses RGB Hex value (E.g. #9900FF). Defaults to device’s theme color if not set. |
android_visibility | int | Android 5.0+ | ⚠Deprecated, this field doesn't work on Android 8 (Oreo) and newer devices! Please use Notification Categories / Channels noted above instead to support ALL versions of Android. 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) |
huawei_visibility | int | Huawei | ⚠Deprecated, this field ONLY works on EMUI 5 (Android 7 based) and older devices. Please also set Notification Categories / Channels noted above to support EMUI 8 (Android 8 based) 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. |
web_push_topic | string | Push - All Browsers | Display multiple notifications at once with different topics. |
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. |
Delivery
Parameter | Type | Platform | Description |
---|---|---|---|
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)" Note: SMS currently only supports send_after parameter. |
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.Cannot be used if Throttling enabled. Set throttle_rate_per_minute to 0 to disable throttling if enabled to use these features. |
delivery_time_of_day | string | All | Use with delayed_option=timezone .Examples: "9:00AM" "21:45" "9:45:30" |
ttl | integer | iOS, Android, Chrome, Firefox, 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 or any other integer for normal 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 | valid values: voip Set the value to voip for sending VoIP NotificationsThis field maps to the APNS header apns-push-type .Note: alert and background are automatically set by OneSignal |
throttle_rate_per_minute (optional) | postive integer | All | Apps with throttling enabled - does not work with timezone or intelligent delivery, throttling limits will take precedence. Set to 0 if you want to use timezone or intelligent delivery.- the parameter value will be used to override the default application throttling value set from the dashboard settings. - parameter value 0 indicates not to apply throttling to the notification. - if the parameter is not passed then the default app throttling value will be applied to the notification. Apps with throttling disabled - this parameter can be used to throttle delivery for the notification even though throttling is not enabled at the application level. Refer to throttling for more details. |
Grouping & Collapsing
Push notifications only
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.
Parameter | Type | Platform | Description |
---|---|---|---|
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 Languages - The value of each key is the message that will be sent to users for that language. Example: |
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: |
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
).
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.
Limitation Targeting
include_player_ids
orinclude_external_user_ids
These parameters will be ignored if sending to devices directly with
include_player_ids
orinclude_external_user_ids
For example, sending push to
external_user_id
associated with Android, iOS and Web Platform:{ "include_external_user_ids": ["external_user_id_on_android_ios_web"], "channel_for_external_user_ids": "push", "isIos": true }
This will ignore
isIos
and send the push message to all subscribed devices with these External User IDs.
Targeting
include_external_user_id
channelsExternal User IDs can be associated with Push, Email, or SMS records, you must set
channel_for_external_user_ids
to"push"
or"email"
or"sms"
when sending to that channel.For Example, sending email to
external_user_id
associated with a push, email and sms record:{ "include_external_user_ids": ["external_user_id_on_push_email_sms"], "channel_for_external_user_ids": "email" }
Parameter | Type | Platform | Description |
---|---|---|---|
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. |
isHuawei | boolean | Huawei | Indicates whether to send to all devices registered under your app's Huawei Android platform. |
isAnyWeb | boolean | All Browsers | 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 | boolean | Chrome | 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 | Firefox | Indicates whether to send to all Mozilla Firefox desktop users registered under your Firefox web push platform. |
isSafari | boolean | Safari | 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 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" or "sms" | Indicates if the message type when targeting with include_external_user_ids for cases where an email, sms, and/or push subscribers have the same external user id. Example: Use the string |
Example Code - Create notification
Send to a specific segment or all subscribers - Create notification
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\"},
\"headings\": {\"en\": \"English Title\"},
\"included_segments\": [\"Subscribed Users\"]}" \
https://onesignal.com/api/v1/notifications
{
"app_id": "5eb5a37e-b458-11e3-ac11-000c2940e62c",
"included_segments": ["Subscribed Users"],
"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(
'Subscribed Users'
),
'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\": [\"Subscribed 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 NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj");
var serializer = new JavaScriptSerializer();
var obj = new { app_id = "5eb5a37e-b458-11e3-ac11-000c2940e62c",
contents = new { en = "English Message" },
included_segments = new string[] {"Subscribed 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" => ["Subscribed 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
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": ["Subscribed 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: ["Subscribed Users"]
};
sendNotification(message);
#!/usr/bin/perl -w
use strict;
use warnings;
use Net::Curl::Easy qw(/^CURLOPT_.*/);;
use JSON;
use Data::Dumper;
sub SendNotification
{
my ($url , $authorisation , $app_id , $contents) = @_;
my $curl = Net::Curl::Easy->new;
my $json = JSON->new();
my $response_body;
my $json_string = $json->encode({ app_id => $app_id ,
included_segments => ["Subscribed Users"] ,
data => { "key1" => "Value 1" } ,
ios_badgeType => "Increase" ,
ios_badgeCount => 1 ,
contents => { en => $contents}
});
$curl->setopt( CURLOPT_URL, $url);
$curl->setopt( CURLOPT_SSL_VERIFYHOST , 0);
$curl->setopt( CURLOPT_SSL_VERIFYPEER , 0);
$curl->setopt( CURLOPT_HTTPHEADER, ['Content-Type: application/json; charset=utf-8' ,
"Authorization: Basic $authorisation"]);
$curl->setopt( CURLOPT_POST , 1);
$curl->setopt( CURLOPT_POSTFIELDS , $json_string);
$curl->setopt( CURLOPT_WRITEDATA , \$response_body);
$curl->perform;
print Dumper($response_body);
}
SendNotification("https://onesignal.com/api/v1/notifications" ,
"<< PUT YOUR REST API KEY HERE>>" ,
"<< PUT YOUR APP ID KEY HERE >>" ,
"Hello World");
exit(0);
send = function(params) {
var promise = new Parse.Promise();
var jsonBody = {
app_id: "5eb5a37e-b458-11e3-ac11-000c2940e62c",
included_segments: ["Subscribed 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: ["Subscribed 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 NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj");
con.setRequestMethod("POST");
String strJsonBody = "{"
+ "\"app_id\": \"5eb5a37e-b458-11e3-ac11-000c2940e62c\","
+ "\"included_segments\": [\"Subscribed 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();
}
Send based on filters/tags - Create notification
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\"},
\"headings\": {\"en\": \"English Title\"},
\"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 { @operator = "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
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 strict;
use warnings;
use Net::Curl::Easy qw(/^CURLOPT_.*/);;
use JSON;
use Data::Dumper;
sub SendNotification
{
my ($url , $authorisation , $app_id , $contents) = @_;
my $curl = Net::Curl::Easy->new;
my $json = JSON->new();
my $response_body;
my $json_string = $json->encode({ app_id => $app_id ,
filters => [
{"field": "tag", "key": "level", "relation": "=", "value": "10"},
{"operator": "OR"}, {"field": "amount_spent", "relation": ">", "value": "0"}
],
contents => { en => $contents}
});
$curl->setopt( CURLOPT_URL, $url);
$curl->setopt( CURLOPT_SSL_VERIFYHOST , 0);
$curl->setopt( CURLOPT_SSL_VERIFYPEER , 0);
$curl->setopt( CURLOPT_HTTPHEADER, ['Content-Type: application/json; charset=utf-8' ,
"Authorization: Basic $authorisation"]);
$curl->setopt( CURLOPT_POST , 1);
$curl->setopt( CURLOPT_POSTFIELDS , $json_string);
$curl->setopt( CURLOPT_WRITEDATA , \$response_body);
$curl->perform;
print Dumper($response_body);
}
SendNotification("https://onesignal.com/api/v1/notifications" ,
"<< PUT YOUR REST API KEY HERE>>" ,
"<< PUT YOUR APP ID KEY HERE >>" ,
"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();
}
Send based on External User IDs - Create notification
curl --include \
--request POST \
--header "Content-Type: application/json; charset=utf-8" \
--header "Authorization: Basic YOUR_REST_API_KEY" \
--data-binary "{\"app_id\": \"5eb5a37e-b458-11e3-ac11-000c2940e62c\",
\"contents\": {\"en\": \"English Message\"},
\"headings\": {\"en\": \"English Title\"},
\"channel_for_external_user_ids\": \"push\",
\"include_external_user_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_external_user_ids": ["6392d91a-b206-4b7b-a620-cd68e32c3a76","76ece62b-bcfe-468c-8a78-839aeaa8c5fa","8e0f21fa-9a5a-4ae7-a9a6-ca1f24294b86"],
"channel_for_external_user_ids": "push",
"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_external_user_ids' => array("6392d91a-b206-4b7b-a620-cd68e32c3a76","76ece62b-bcfe-468c-8a78-839aeaa8c5fa","8e0f21fa-9a5a-4ae7-a9a6-ca1f24294b86"),
'channel_for_external_user_ids' => 'push',
'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\"},"
+ "\"channel_for_external_user_ids\": \"push\","
+ "\"include_external_user_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";
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" },
channel_for_external_user_ids = "push",
include_external_user_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"},
"channel_for_external_user_ids" => "push",
"include_external_user_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',
'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_external_user_ids": ["6392d91a-b206-4b7b-a620-cd68e32c3a76","76ece62b-bcfe-468c-8a78-839aeaa8c5fa","8e0f21fa-9a5a-4ae7-a9a6-ca1f24294b86"],
"channel_for_external_user_ids": "push",
"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"},
channel_for_external_user_ids: "push",
include_external_user_ids: ["6392d91a-b206-4b7b-a620-cd68e32c3a76","76ece62b-bcfe-468c-8a78-839aeaa8c5fa","8e0f21fa-9a5a-4ae7-a9a6-ca1f24294b86"]
};
sendNotification(message);
#!/usr/bin/perl -w
use strict;
use warnings;
use Net::Curl::Easy qw(/^CURLOPT_.*/);;
use JSON;
use Data::Dumper;
sub SendNotification
{
my ($url , $authorisation , $app_id , $contents) = @_;
my $curl = Net::Curl::Easy->new;
my $json = JSON->new();
my $response_body;
my $json_string = $json->encode({ app_id => $app_id ,
include_external_user_ids => ["6392d91a-b206-4b7b-a620-cd68e32c3a76","76ece62b-bcfe-468c-8a78-839aeaa8c5fa","8e0f21fa-9a5a-4ae7-a9a6-ca1f24294b86"],
channel_for_external_user_ids => "push",
contents => { en => $contents}
});
$curl->setopt( CURLOPT_URL, $url);
$curl->setopt( CURLOPT_SSL_VERIFYHOST , 0);
$curl->setopt( CURLOPT_SSL_VERIFYPEER , 0);
$curl->setopt( CURLOPT_HTTPHEADER, ['Content-Type: application/json; charset=utf-8' ,
"Authorization: Basic $authorisation"]);
$curl->setopt( CURLOPT_POST , 1);
$curl->setopt( CURLOPT_POSTFIELDS , $json_string);
$curl->setopt( CURLOPT_WRITEDATA , \$response_body);
$curl->perform;
print Dumper($response_body);
}
SendNotification("https://onesignal.com/api/v1/notifications" ,
"<< PUT YOUR APP ID KEY HERE >>" ,
"Hello World");
exit(0);
send = function(params) {
var promise = new Parse.Promise();
var jsonBody = {
app_id: "5eb5a37e-b458-11e3-ac11-000c2940e62c",
include_external_user_ids: ["6392d91a-b206-4b7b-a620-cd68e32c3a76","76ece62b-bcfe-468c-8a78-839aeaa8c5fa","8e0f21fa-9a5a-4ae7-a9a6-ca1f24294b86"],
contents: {en: "English Message"},
channel_for_external_user_ids: "push",
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",
include_external_user_ids: ["6392d91a-b206-4b7b-a620-cd68e32c3a76","76ece62b-bcfe-468c-8a78-839aeaa8c5fa","8e0f21fa-9a5a-4ae7-a9a6-ca1f24294b86"],
contents: {en: "English Message"},
channel_for_external_user_ids: "push",
};
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\","
+ "\"include_external_user_ids\": [\"6392d91a-b206-4b7b-a620-cd68e32c3a76\",\"76ece62b-bcfe-468c-8a78-839aeaa8c5fa\",\"8e0f21fa-9a5a-4ae7-a9a6-ca1f24294b86\"],"
+ "\"channel_for_external_user_ids\": \"push\","
+ "\"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();
}
Send based on OneSignal Player IDs - Create notification
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\"},
\"headings\": {\"en\": \"English Title\"},
\"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
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 strict;
use warnings;
use Net::Curl::Easy qw(/^CURLOPT_.*/);;
use JSON;
use Data::Dumper;
sub SendNotification
{
my ($url , $authorisation , $app_id , $contents) = @_;
my $curl = Net::Curl::Easy->new;
my $json = JSON->new();
my $response_body;
my $json_string = $json->encode({ app_id => $app_id ,
include_player_ids => ["6392d91a-b206-4b7b-a620-cd68e32c3a76","76ece62b-bcfe-468c-8a78-839aeaa8c5fa","8e0f21fa-9a5a-4ae7-a9a6-ca1f24294b86"],
contents => { en => $contents}
});
$curl->setopt( CURLOPT_URL, $url);
$curl->setopt( CURLOPT_SSL_VERIFYHOST , 0);
$curl->setopt( CURLOPT_SSL_VERIFYPEER , 0);
$curl->setopt( CURLOPT_HTTPHEADER, ['Content-Type: application/json; charset=utf-8']);
$curl->setopt( CURLOPT_POST , 1);
$curl->setopt( CURLOPT_POSTFIELDS , $json_string);
$curl->setopt( CURLOPT_WRITEDATA , \$response_body);
$curl->perform;
print Dumper($response_body);
}
SendNotification("https://onesignal.com/api/v1/notifications" ,
"<< PUT YOUR APP ID KEY HERE >>" ,
"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();
}
<cfset stFields = {
"app_id": "YOUR_APP_ID",
"include_player_ids": ["6392d91a-b206-4b7b-a620-cd68e32c3a76","0969472e-3298-4d7a-82e2-8fa127141892","c98fcb48-98e2-4302-8eab-b36eb891b10c"],
"data": {"foo": "bar"},
"contents": {"en": "English Message"}
}>
<cfhttp url="https://onesignal.com/api/v1/notifications" method="post" result="result">
<cfhttpparam type="header" name="Content-Type" value="application/json; charset=utf-8" />
<cfhttpparam type="body" value="#serializeJSON(stFields)#" />
</cfhttp>
Send Email based on Email Addresses - Create notification
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_email_tokens" => ["[email protected]", "[email protected]"],
}
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.
Send SMS using Phone Numbers - Create notification
params = {
"app_id" => "5eb5a37e-b458-11",
"name": "Identifier for SMS Message",
"sms_from": "+15555555555",
"contents" => { en: "Welcome to Cat Facts!" },
"sms_media_urls": ["https://cat.com/cat.jpg"],
"include_phone_numbers": ["+1999999999"]}
}
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 NGEwMGZmMjItY2NkNy0xMWUzLTk5")
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 NGEwMGZmMjItY2NkNy0xMWUzLT"}
payload = {
"app_id": "5eb5a37e-b458-11",
"name": "Identifier for SMS Message",
"sms_from": "+15555555555",
"contents": { "en": "Welcome to Cat Facts!" },
"sms_media_urls": ["https://cat.com/cat.jpg"],
"include_phone_numbers": ["+19999999999"]
}
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 NGEwMGZmMjItY2NkNy0xMWj"
};
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-11",
"name": "Identifier for SMS Message",
"sms_from": "+15555555555",
"contents" => { en: "Welcome to Cat Facts!" },
"sms_media_urls": ["https://cat.com/cat.jpg"],
"include_phone_numbers": ["+19999999999"]
};
sendNotification(message);
Results - Create notification
-
If a message was successfully created, you will get a
200
response and anid
for the notification. -
If the
200
response contains"invalid_player_ids"
or"invalid_external_user_ids"
this will mark devices that exist in the providedapp_id
but are no longer subscribed. -
invalid_phone_numbers
will list unsubscribed and invalid phone numbers within the providedapp_id
.
No id
or response will be returned and no message will be created if targeting User IDs that do not exist under the provided app_id
.
{
"id": "b98881cc-1e94-4366-bbd9-db8f3429292b",
"external_id": null
}
{
"errors": [
"Message Notifications must have English language content"
]
}
// Returned if using include_player_ids and some were valid and others were not.
// Please process these on your server and remove them from your database if you are tracking them.
{
"id": "c0bf597f-08e9-4e0a-8cc5-0de94ffa6033",
"external_id": null,
"errors": {
"invalid_player_ids": [
"b186912c-cf25-4688-8218-06cb13e09a4f"
]
}
}
{
"id": "",
"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
{
"id": "57127ecc-85ff-4888-a522-7de9f0d5182e",
"external_id": null,
"errors": {
"invalid_external_user_ids": [
"786956"
]
}
}
// Returned if using include_phone_numbers and some were valid and others were not valid or unsubscribed.
// Please process these on your server and remove them from your database if you are tracking them.
{
"id": "c0bf597f-08e9-4e0a-8cc5-0de94ffa6033",
"external_id": null,
"errors": {
"invalid_phone_numbers": [
"+15555555555","+14444444444"
]
}
}