Push Notification Content
If you are sending push notifications, use the following parameters. Read more in 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. Any language codes used must also be used within headings property.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 you wish to include must have a language code string for a key mapped to the localized text you would like users to receive for that language. Any language codes used must also be used within contents property.This field supports tag substitutions. Example: {"en": "English Title", "es": "Spanish Title"} |
subtitle | object | iOS 10+ | The notification's subtitle, a map of language codes to text for each language. Each hash must have a language code string for a key, mapped to the localized text you would like users to receive for that language. 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: be4a8044-bbd6-11e4-a581-000c2940e62c |
content_available | boolean | iOS | Sending true wakes your app from background to run custom native code (Apple interprets this as content-available=1 ). Note: Not applicable if the app is in the "force-quit" state (i.e app was swiped away). Omit the contents field to prevent displaying a visible notification. |
mutable_content | boolean | iOS 10+ | Always defaults to true and cannot be turned off. Allows tracking of notification receives and changing of the notification content in your app before it is displayed. Triggers didReceive(_:withContentHandler:) on your UNNotificationServiceExtension. |
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. |
Attachments
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. |
huawei_category | string | Huawei | Messaging self-classification categories for sending to users in China (which requires an approved self-classification application). Default category is set to MARKETING , which are subject to limitations of 2-5 daily sends, depending on which third-level classifications they fall in. More details in our Huawei Setup Guide- IM - VOIP - SUBSCRIPTION - TRAVEL - HEALTH - WORK - ACCOUNT - EXPRESS - FINANCE - DEVICE_REMINDER - MAIL - MARKETING |
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. Works for Chrome for Windows & Android only. Chrome for macOS uses the same image set for the chrome_web_icon . |
adm_big_picture | string | Amazon | Picture to display in the expanded view. Can be a drawable resource name or a URL. |
chrome_big_picture | string | ChromeApp | Large picture to display below the notification text. Must be a local URL. |
Action Buttons
These add buttons to push notifications, allowing the user to take more than one action on a notification. Learn more about Action Buttons.
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. |
icon_type | string | iOS | In iOS you can specify the type of icon to be used in an Action button as being either ['system', 'custom'] |
Appearance
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.
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 | ⚠Deprecated, this field doesn't work on Android 12+ 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. Set the icon name without the file extension. 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 (exclude file extension) 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. |
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. Works for Chrome for Windows & Android only. Chrome for macOS uses the same image set for the chrome_web_icon . |
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 | 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 . |
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. |
Grouping & Collapsing
Grouping lets you combine multiple notifications into a single notification to improve the user experience. Collapsing lets you dismiss old notifications in favor of newer ones.
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: |
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. |
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 " |
ios_relevance_score | float between 0-1 | iOS 15+ | A iOS: Relevance Score is a score to be set per notification to indicate how it should be displayed when grouped. |
ios_interruption_level | string | iOS 15+ | iOS: Focus Modes and Interruption Levels indicate the priority and delivery timing of a notification, to ‘interrupt’ the user. Up until iOS 15, Apple primarily focused on Critical notifications. Can choose from options: ['active', 'passive', 'time_sensitive', 'critical'] Default is active . |
Delivery
Parameter | Type | Platform | Description |
---|---|---|---|
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 |
enable_frequency_cap | boolean | All - Push | When frequency capping is enabled for the app, sending true will apply the frequency capping to the notification. If the parameter is not included, the default behavior is to apply frequency capping if the setting is enabled for the app. Setting the parameter to false will override the frequency capping, meaning that the notification will be sent without considering frequency capping. |
Examples Sending Notifications
See our Using Postman guide for a low-code solution.
Send to a specific segment or all subscribers
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);
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
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);
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
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);
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
curl --include \
--request POST \
--header "Content-Type: application/json; charset=utf-8" \
--data-binary "{\"app_id\": \"5eb5a37e-b458-11e3-ac11-000c2940e62c\",
\"name\": {\"en\": \"My notification Name\"},
\"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);
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>