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 |
---|---|---|
| array_string | The segment names you want to target. Users in these segments will receive a notification. This targeting parameter is only compatible with Example: |
| array_string | Segment that will be excluded when sending. Users in these segments will not receive a notification, even if they were included in Example: |
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 |
---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
|
|
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 |
---|---|---|
| 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: Limit of 2,000 entries per REST API call |
| array_string | Target specific devices by custom user IDs assigned via API. Not compatible with any other targeting parameters Example: 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. |
| 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: Limit of 2,000 entries per REST API call |
| 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: Limit of 2,000 entries per REST API call |
| array_string | Not Recommended: Please consider using 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: Limit of 2,000 entries per REST API call |
| array_string | Not Recommended: Please consider using Target using Windows URIs. If a token does not correspond to an existing user, a new user will be created. Example: Limit of 2,000 entries per REST API call |
| array_string | Not Recommended: Please consider using Target using Amazon ADM registration IDs. If a token does not correspond to an existing user, a new user will be created. Example: Limit of 2,000 entries per REST API call |
| array_string | Not Recommended: Please consider using Target using Chrome App registration IDs. If a token does not correspond to an existing user, a new user will be created. Example: Limit of 2,000 entries per REST API call |
| array_string | Not Recommended: Please consider using Target using Chrome Web Push registration IDs. If a token does not correspond to an existing user, a new user will be created. Example: Limit of 2,000 entries per REST API call |
| array_string | Not Recommended: Please consider using Target using Android device registration IDs. If a token does not correspond to an existing user, a new user will be created. Example: 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 |
---|---|---|---|
| string | All | Required: Your OneSignal Application ID, which can be found in Keys & IDs. It is a UUID and looks similar to |
Idempotency
Parameter | Type | Platform | Description |
---|---|---|---|
| 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.
Parameter | Type | Platform | Description |
---|---|---|---|
| object | All - Push | Required unless 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. English must be included in the hash. Example: |
| object | All - Push | Required for Huawei 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: |
| string | All | Optional for Push. An identifier for tracking message within the OneSignal dashboard or export analytics. Not shown to end user. |
| 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 [tag substitutions](doc:personalization).** Example: `{"en": "English Subtitle", "es": "Spanish Subtitle"}` |
| 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` |
| boolean | iOS | Sending |
| boolean | iOS 10+ | Always defaults to |
| 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 |
---|---|---|
| string | Required: The subject of the email. |
| 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 `` tag somewhere in the email. Note: any malformed HTML content will be sent to users. Please double-check your HTML is valid. |
| string | The name the email is from. If not specified, will default to "from name" set in the OneSignal Dashboard Email Settings. |
| 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. |
| 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 |
---|---|---|
| string | Required for SMS Messages. An identifier for tracking message within the OneSignal dashboard or export analytics. Not shown to end user. |
| 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. |
| string | Text content for the SMS |
| array_string | URLs for the media files to be attached to the SMS content. |
Attachments
Push notifications only
These are additional content attached to push notifications, primarily images.
Parameter | Type | Platform | Description |
---|---|---|---|
| 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 Example: |
| string | Huawei | Use |
| string | All | The URL to open in the browser when a user clicks on the notification. Example: Note: iOS needs https or updated NSAppTransportSecurity in plist This field supports tag substitutions. Omit if including |
| string | Push - All Browsers | Same as |
| string | Push - Mobile Apps | Same as |
| 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 Example: |
| string | Android | Picture to display in the expanded view. Can be a drawable resource name or a URL. |
| string | Huawei | Picture to display in the expanded view. Can be a drawable resource name or a URL. |
| 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. |
| string | Amazon | Picture to display in the expanded view. Can be a drawable resource name or a URL. |
| 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 |
---|---|---|---|
| array_object | iOS 8.0+, Android 4.1+, and derivatives like Amazon | Buttons to add to the notification. Icon only works for Android. Buttons show in reverse order of array position i.e. Last item in array shows as first button on device. Example: `[{"id": "id2", "text": "second button", "icon": "ic_menu_share"}, {"id": "id1", "text": "first button", "icon": "ic_menu_send"}]` |
| array_object | Chrome 48+ | Add action buttons to the notification. The 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"}]` |
| string | iOS | Category APS payload, use with Example: `calendar` category which contains actions like `accept` and `decline` iOS 10+ This will trigger your [UNNotificationContentExtension](https://developer.apple.com/documentation/usernotifications/unnotificationserviceextension) 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 |
---|---|---|---|
| UUID | Android | The Android Oreo Notification Category to send the notification under. See the Category documentation on creating one and getting it's 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. |
| string | Android | Use this if you have client side Android Oreo Channels you have already defined in your app with code. |
| string | Huawei | Use this if you have client side Android Oreo Channels you have already defined in your app with code. |
| object | Android | Allowing setting a background image for the notification. This is a JSON object containing the following keys. See our [Background Image](doc:android-customizations#section-background-images) 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"}` |
| string | Android | Icon shown in the status bar and on the top left of the notification. |
| string | Huawei | Icon shown in the status bar and on the top left of the notification. |
| string | Android | Can be a drawable resource name or a URL. |
| string | Huawei | Can be a drawable resource name or a URL. |
| string | Amazon | If not set a bell icon will be used or |
| string | Amazon | If blank the |
| 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 |
| 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. |
| string | Chrome | Sets the web push notification icon for Android devices in the notification shade. Please see Web Push Notification Badge. |
| string | Firefox | Not recommended Few people need to set Firefox-specific icons. We recommend setting 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. |
| 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. |
| 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"` |
| string | Android | ⚠Deprecated, this field doesn't work on Android 8 (Oreo) and newer devices! 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"` |
| string | Huawei | ⚠Deprecated, this field ONLY works on EMUI 5 (Android 7 based) and older 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: `"/res/raw/notification"` |
| string | Amazon | ⚠Deprecated, this field doesn't work on Android 8 (Oreo) and newer devices! 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"` |
| string | Windows | Sound file that is included in your app to play instead of the default device notification sound. Example: `"notification.wav"` |
| string | Android | ⚠Deprecated, this field doesn't work on Android 8 (Oreo) and newer devices! Sets the devices LED notification light if the device has one. ARGB Hex format. Example(Blue): `"FF0000FF"` |
| string | Huawei | ⚠Deprecated, this field ONLY works on EMUI 5 (Android 7 based) and older devices. Sets the devices LED notification light if the device has one. RGB Hex format. Example(Blue): `"0000FF"` |
| 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"` |
| string | Huawei | Accent Color used on Action Buttons and Group overflow count. |
| int | Android 5.0+ | ⚠Deprecated, this field doesn't work on Android 8 (Oreo) and newer devices!
|
| int | Huawei | ⚠Deprecated, this field ONLY works on EMUI 5 (Android 7 based) and older devices.
|
| string | iOS | Describes whether to set or increase/decrease your app's iOS badge count by the
|
| integer | iOS | Used with You can use a negative number to decrease the badge count when used with an |
| 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. |
| string | Push - All Browsers | Display multiple notifications at once with different topics. |
| object | iOS 10+ | iOS can localize push notification messages on the client using special parameters such as |
Delivery
Parameter | Type | Platform | Description |
---|---|---|---|
| string | All | Schedule notification for future delivery. API defaults to UTC -1100 Examples: All examples are the exact same date & time.
Note: SMS currently only supports |
| string | All | Possible values are:
If Cannot be used if Throttling enabled. Set |
| string | All | Use with
|
| 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 |
| integer | Android, Chrome, ChromeWeb | Delivery priority through the push server (example GCM/FCM). Pass |
| string | iOS | valid values: This field maps to the APNS header |
| postive integer | All | Apps with throttling enabled
Apps with throttling disabled
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 |
---|---|---|---|
| string | Android | Notifications with the same group will be stacked together using Android's Notification Grouping feature. |
| 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.](doc:language-localization#section-supported-languages) Example: `{"en": "You have $[notif_count] new messages"}` |
| string | Amazon | Notifications with the same group will be stacked together using Android's Notification Grouping feature. |
| 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"}` |
| 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 |
| string | iOS 12+ | When using The |
| number | iOS 12+ | When using |
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 |
---|---|---|---|
| boolean | iOS | Indicates whether to send to all devices registered under your app's Apple iOS platform. |
| boolean | Android | Indicates whether to send to all devices registered under your app's Google Android platform. |
| boolean | Huawei | Indicates whether to send to all devices registered under your app's Huawei Android platform. |
| 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`, `isFirefox`, and `isSafari`, though the three options are equivalent to this one. |
| 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. |
| boolean | Firefox | Indicates whether to send to all Mozilla Firefox desktop users registered under your Firefox web push platform. |
| 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 |
| boolean | Windows | Indicates whether to send to all devices registered under your app's Windows platform. |
| boolean | Amazon | Indicates whether to send to all devices registered under your app's Amazon Fire platform. |
| 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. |
| string |
| Indicates if the message type when targeting with [include_external_user_ids](#send-to-specific-devices) for cases where an email, sms, and/or push subscribers have 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 or `"sms"`for sending SMS. |
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",
"recipients": 1,
"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",
"recipients": 1,
"external_id": null,
"errors": {
"invalid_player_ids": [
"b186912c-cf25-4688-8218-06cb13e09a4f"
]
}
}
{
"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
{
"id": "57127ecc-85ff-4888-a522-7de9f0d5182e",
"recipients": 1,
"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",
"recipients": 1,
"external_id": null,
"errors": {
"invalid_phone_numbers": [
"+15555555555","+14444444444"
]
}
}