Tous les SDK serveur OneSignal sont générés à partir de la même spécification OpenAPI, donc ils partagent une interface cohérente quelle que soit la langue. Chaque SDK encapsule la OneSignal REST API et fournit des modèles typés pour les requêtes et réponses.
SDK disponibles
Installation
Node.js
Python
Java
Go
PHP
Ruby
C# (.NET)
Rust
npm install @onesignal/node-onesignal
pip install onesignal-python-api
Maven<dependency>
<groupId>com.onesignal</groupId>
<artifactId>onesignal-java-client</artifactId>
<version>5.3.0</version>
</dependency>
Gradleimplementation "com.onesignal:onesignal-java-client:5.3.0"
go get github.com/OneSignal/onesignal-go-api/v5
Ajoutez à composer.json :{
"require": {
"onesignal/onesignal-php-api": "*@dev"
}
}
Puis exécutez composer update. Ajoutez à votre Gemfile :gem 'onesignal', '~> 5.3.0-beta1'
Puis exécutez bundle install. dotnet add package OneSignalApi
Ajoutez à Cargo.toml sous [dependencies] :onesignal-rust-api = "5.3.0"
Configuration
Chaque SDK nécessite une authentification via des clés API. Deux types de clés sont disponibles :
- Clé REST API — requise pour la plupart des points de terminaison (envoi de notifications, gestion des utilisateurs, etc.). Trouvée dans Paramètres > Clés et identifiants de votre application.
- Clé API d’organisation — requise uniquement pour les points de terminaison au niveau de l’organisation, comme la création ou la liste des applications. Trouvée dans Paramètres d’organisation.
Node.js
Python
Java
Go
PHP
Ruby
C# (.NET)
Rust
const OneSignal = require('@onesignal/node-onesignal');
const configuration = OneSignal.createConfiguration({
restApiKey: 'YOUR_REST_API_KEY',
organizationApiKey: 'YOUR_ORGANIZATION_API_KEY',
});
const client = new OneSignal.DefaultApi(configuration);
import onesignal
from onesignal.api import default_api
configuration = onesignal.Configuration(
rest_api_key='YOUR_REST_API_KEY',
organization_api_key='YOUR_ORGANIZATION_API_KEY',
)
with onesignal.ApiClient(configuration) as api_client:
client = default_api.DefaultApi(api_client)
import com.onesignal.client.ApiClient;
import com.onesignal.client.Configuration;
import com.onesignal.client.auth.HttpBearerAuth;
import com.onesignal.client.api.DefaultApi;
ApiClient defaultClient = Configuration.getDefaultApiClient();
HttpBearerAuth restApiAuth = (HttpBearerAuth) defaultClient
.getAuthentication("rest_api_key");
restApiAuth.setBearerToken("YOUR_REST_API_KEY");
HttpBearerAuth orgApiAuth = (HttpBearerAuth) defaultClient
.getAuthentication("organization_api_key");
orgApiAuth.setBearerToken("YOUR_ORGANIZATION_API_KEY");
DefaultApi client = new DefaultApi(defaultClient);
import onesignal "github.com/OneSignal/onesignal-go-api"
restAuth := context.WithValue(
context.Background(),
onesignal.RestApiKey,
"YOUR_REST_API_KEY",
)
orgAuth := context.WithValue(
restAuth,
onesignal.OrganizationApiKey,
"YOUR_ORGANIZATION_API_KEY",
)
apiClient := onesignal.NewAPIClient(onesignal.NewConfiguration())
use onesignal\client\api\DefaultApi;
use onesignal\client\Configuration;
use GuzzleHttp;
$config = Configuration::getDefaultConfiguration()
->setRestApiKeyToken('YOUR_REST_API_KEY')
->setOrganizationApiKeyToken('YOUR_ORGANIZATION_API_KEY');
$client = new DefaultApi(
new GuzzleHttp\Client(),
$config
);
require 'onesignal'
OneSignal.configure do |config|
config.rest_api_key = 'YOUR_REST_API_KEY'
config.organization_api_key = 'YOUR_ORGANIZATION_API_KEY'
end
client = OneSignal::DefaultApi.new
using OneSignalApi.Api;
using OneSignalApi.Client;
var config = new Configuration();
config.BasePath = "https://api.onesignal.com";
config.AccessToken = "YOUR_REST_API_KEY";
var client = new DefaultApi(config);
use onesignal::apis::configuration::Configuration;
fn create_configuration() -> Configuration {
let mut config = Configuration::new();
config.rest_api_key_token = Some("YOUR_REST_API_KEY".to_string());
config.organization_api_key_token = Some("YOUR_ORGANIZATION_API_KEY".to_string());
config
}
Stockez vos clés API dans des variables d’environnement ou un gestionnaire de secrets. Ne les commitez jamais dans le contrôle de source.
Envoyer une notification push
Envoyez des notifications push aux Abonnements web et mobiles en ciblant un segment.
Node.js
Python
Java
Go
PHP
Ruby
C# (.NET)
Rust
const notification = new OneSignal.Notification();
notification.app_id = 'YOUR_APP_ID';
notification.contents = { en: 'Hello from OneSignal!' };
notification.headings = { en: 'Push Notification' };
notification.included_segments = ['Subscribed Users'];
const response = await client.createNotification(notification);
console.log('Notification ID:', response.id);
notification = onesignal.Notification(
app_id='YOUR_APP_ID',
contents=onesignal.StringMap(en='Hello from OneSignal!'),
headings=onesignal.StringMap(en='Push Notification'),
included_segments=['Subscribed Users'],
)
response = client.create_notification(notification)
print('Notification ID:', response.id)
import com.onesignal.client.model.Notification;
import com.onesignal.client.model.StringMap;
Notification notification = new Notification();
notification.setAppId("YOUR_APP_ID");
StringMap contents = new StringMap();
contents.en("Hello from OneSignal!");
notification.setContents(contents);
StringMap headings = new StringMap();
headings.en("Push Notification");
notification.setHeadings(headings);
notification.setIncludedSegments(Arrays.asList("Subscribed Users"));
var response = client.createNotification(notification);
System.out.println("Notification ID: " + response.getId());
notification := *onesignal.NewNotification("YOUR_APP_ID")
notification.SetContents(onesignal.StringMap{En: onesignal.PtrString("Hello from OneSignal!")})
notification.SetHeadings(onesignal.StringMap{En: onesignal.PtrString("Push Notification")})
notification.SetIncludedSegments([]string{"Subscribed Users"})
response, _, err := apiClient.DefaultApi
.CreateNotification(orgAuth)
.Notification(notification)
.Execute()
if err != nil {
log.Fatal(err)
}
fmt.Println("Notification ID:", response.GetId())
use onesignal\client\model\Notification;
use onesignal\client\model\StringMap;
$content = new StringMap();
$content->setEn('Hello from OneSignal!');
$headings = new StringMap();
$headings->setEn('Push Notification');
$notification = new Notification();
$notification->setAppId('YOUR_APP_ID');
$notification->setContents($content);
$notification->setHeadings($headings);
$notification->setIncludedSegments(['Subscribed Users']);
$response = $client->createNotification($notification);
echo 'Notification ID: ' . $response->getId();
notification = OneSignal::Notification.new({
app_id: 'YOUR_APP_ID',
contents: { en: 'Hello from OneSignal!' },
headings: { en: 'Push Notification' },
included_segments: ['Subscribed Users']
})
response = client.create_notification(notification)
puts "Notification ID: #{response.id}"
using OneSignalApi.Model;
var notification = new Notification(appId: "YOUR_APP_ID")
{
Contents = new StringMap(en: "Hello from OneSignal!"),
Headings = new StringMap(en: "Push Notification"),
IncludedSegments = new List<string> { "Subscribed Users" }
};
var response = client.CreateNotification(notification);
Console.WriteLine("Notification ID: " + response.Id);
use onesignal::apis::default_api;
use onesignal::models::{Notification, StringMap};
let mut contents = StringMap::new();
contents.en = Some("Hello from OneSignal!".to_string());
let mut headings = StringMap::new();
headings.en = Some("Push Notification".to_string());
let mut notification = Notification::new("YOUR_APP_ID".to_string());
notification.contents = Some(Box::new(contents));
notification.headings = Some(Box::new(headings));
notification.included_segments = Some(vec!["Subscribed Users".to_string()]);
let config = create_configuration();
let response = default_api::create_notification(&config, notification).await;
Envoyer un e-mail
Envoyez des e-mails aux Abonnements avec le canal email.
Node.js
Python
Java
Go
PHP
Ruby
C# (.NET)
Rust
const notification = new OneSignal.Notification();
notification.app_id = 'YOUR_APP_ID';
notification.email_subject = 'Important Update';
notification.email_body = '<h1>Hello!</h1><p>This is an HTML email.</p>';
notification.included_segments = ['Subscribed Users'];
notification.channel_for_external_user_ids = 'email';
const response = await client.createNotification(notification);
notification = onesignal.Notification(
app_id='YOUR_APP_ID',
email_subject='Important Update',
email_body='<h1>Hello!</h1><p>This is an HTML email.</p>',
included_segments=['Subscribed Users'],
channel_for_external_user_ids='email',
)
response = client.create_notification(notification)
Notification notification = new Notification();
notification.setAppId("YOUR_APP_ID");
notification.setEmailSubject("Important Update");
notification.setEmailBody("<h1>Hello!</h1><p>This is an HTML email.</p>");
notification.setIncludedSegments(Arrays.asList("Subscribed Users"));
notification.setChannelForExternalUserIds("email");
var response = client.createNotification(notification);
notification := *onesignal.NewNotification("YOUR_APP_ID")
notification.SetEmailSubject("Important Update")
notification.SetEmailBody("<h1>Hello!</h1><p>This is an HTML email.</p>")
notification.SetIncludedSegments([]string{"Subscribed Users"})
notification.SetChannelForExternalUserIds("email")
response, _, err := apiClient.DefaultApi
.CreateNotification(orgAuth)
.Notification(notification)
.Execute()
$notification = new Notification();
$notification->setAppId('YOUR_APP_ID');
$notification->setEmailSubject('Important Update');
$notification->setEmailBody('<h1>Hello!</h1><p>This is an HTML email.</p>');
$notification->setIncludedSegments(['Subscribed Users']);
$notification->setChannelForExternalUserIds('email');
$response = $client->createNotification($notification);
notification = OneSignal::Notification.new({
app_id: 'YOUR_APP_ID',
email_subject: 'Important Update',
email_body: '<h1>Hello!</h1><p>This is an HTML email.</p>',
included_segments: ['Subscribed Users'],
channel_for_external_user_ids: 'email'
})
response = client.create_notification(notification)
var notification = new Notification(appId: "YOUR_APP_ID")
{
EmailSubject = "Important Update",
EmailBody = "<h1>Hello!</h1><p>This is an HTML email.</p>",
IncludedSegments = new List<string> { "Subscribed Users" },
ChannelForExternalUserIds = "email"
};
var response = client.CreateNotification(notification);
let mut notification = Notification::new("YOUR_APP_ID".to_string());
notification.email_subject = Some("Important Update".to_string());
notification.email_body = Some("<h1>Hello!</h1><p>This is an HTML email.</p>".to_string());
notification.included_segments = Some(vec!["Subscribed Users".to_string()]);
notification.channel_for_external_user_ids = Some("email".to_string());
let response = default_api::create_notification(&config, notification).await;
Envoyer un SMS
Envoyez des messages texte SMS aux Abonnements avec le canal sms.
Node.js
Python
Java
Go
PHP
Ruby
C# (.NET)
Rust
const notification = new OneSignal.Notification();
notification.app_id = 'YOUR_APP_ID';
notification.contents = { en: 'Your SMS message content here' };
notification.included_segments = ['Subscribed Users'];
notification.channel_for_external_user_ids = 'sms';
notification.sms_from = '+15551234567';
const response = await client.createNotification(notification);
notification = onesignal.Notification(
app_id='YOUR_APP_ID',
contents=onesignal.StringMap(en='Your SMS message content here'),
included_segments=['Subscribed Users'],
channel_for_external_user_ids='sms',
sms_from='+15551234567',
)
response = client.create_notification(notification)
StringMap contents = new StringMap();
contents.en("Your SMS message content here");
Notification notification = new Notification();
notification.setAppId("YOUR_APP_ID");
notification.setContents(contents);
notification.setIncludedSegments(Arrays.asList("Subscribed Users"));
notification.setChannelForExternalUserIds("sms");
notification.setSmsFrom("+15551234567");
var response = client.createNotification(notification);
notification := *onesignal.NewNotification("YOUR_APP_ID")
notification.SetContents(onesignal.StringMap{En: onesignal.PtrString("Your SMS message content here")})
notification.SetIncludedSegments([]string{"Subscribed Users"})
notification.SetChannelForExternalUserIds("sms")
notification.SetSmsFrom("+15551234567")
response, _, err := apiClient.DefaultApi
.CreateNotification(orgAuth)
.Notification(notification)
.Execute()
$content = new StringMap();
$content->setEn('Your SMS message content here');
$notification = new Notification();
$notification->setAppId('YOUR_APP_ID');
$notification->setContents($content);
$notification->setIncludedSegments(['Subscribed Users']);
$notification->setChannelForExternalUserIds('sms');
$notification->setSmsFrom('+15551234567');
$response = $client->createNotification($notification);
notification = OneSignal::Notification.new({
app_id: 'YOUR_APP_ID',
contents: { en: 'Your SMS message content here' },
included_segments: ['Subscribed Users'],
channel_for_external_user_ids: 'sms',
sms_from: '+15551234567'
})
response = client.create_notification(notification)
var notification = new Notification(appId: "YOUR_APP_ID")
{
Contents = new StringMap(en: "Your SMS message content here"),
IncludedSegments = new List<string> { "Subscribed Users" },
ChannelForExternalUserIds = "sms",
SmsFrom = "+15551234567"
};
var response = client.CreateNotification(notification);
let mut contents = StringMap::new();
contents.en = Some("Your SMS message content here".to_string());
let mut notification = Notification::new("YOUR_APP_ID".to_string());
notification.contents = Some(Box::new(contents));
notification.included_segments = Some(vec!["Subscribed Users".to_string()]);
notification.channel_for_external_user_ids = Some("sms".to_string());
notification.sms_from = Some("+15551234567".to_string());
let response = default_api::create_notification(&config, notification).await;
Référence API complète
Chaque SDK serveur prend en charge le même ensemble de points de terminaison API. Consultez la documentation API de votre SDK pour la liste complète des méthodes, incluant les utilisateurs, abonnements, segments, modèles et plus encore.
Pour l’API REST sous-jacente, consultez la référence API complète.
FAQ
Quel SDK serveur devrais-je choisir ?
Utilisez le SDK correspondant à votre langage backend. Tous les SDK serveur sont générés à partir de la même spécification OpenAPI et prennent en charge les mêmes points de terminaison, donc la fonctionnalité est identique entre les langages.
Quelle est la différence entre la clé REST API et la clé API d’organisation ?
La clé REST API est limitée à une seule application et est requise pour la plupart des opérations comme l’envoi de notifications et la gestion des utilisateurs. La clé API d’organisation est limitée à votre organisation et n’est nécessaire que pour créer ou lister des applications. La plupart des intégrations n’ont besoin que de la clé REST API.
Puis-je utiliser directement la REST API plutôt qu’un SDK ?
Oui. Les SDK serveur sont des wrappers pratiques autour de la OneSignal REST API. Vous pouvez appeler l’API directement en utilisant n’importe quel client HTTP avec l’authentification Bearer token.
Ces SDK sont-ils auto-générés ?
Oui. Tous les SDK serveur sont générés à partir de la spécification OpenAPI de OneSignal en utilisant OpenAPI Generator. Cela garantit une couverture API cohérente dans tous les langages.