> ## Documentation Index
> Fetch the complete documentation index at: https://documentation.onesignal.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 服务器 SDK 参考

> 安装、配置和使用 OneSignal 服务器 SDK，从 Node.js、Python、Java、Go、PHP、Ruby、C# 和 Rust 后端发送推送通知、电子邮件和短信。

所有 OneSignal 服务器 SDK 均由同一 OpenAPI 规范生成，因此无论使用哪种语言，它们都具有一致的接口。每个 SDK 封装了 [OneSignal REST API](/reference/create-message) 并提供请求和响应的类型化模型。

## 可用 SDK

| 语言        | 包                                                                                                  | 仓库                                                          |
| --------- | -------------------------------------------------------------------------------------------------- | ----------------------------------------------------------- |
| Node.js   | [@onesignal/node-onesignal](https://www.npmjs.com/package/@onesignal/node-onesignal)               | [GitHub](https://github.com/OneSignal/node-onesignal)       |
| Python    | [onesignal-python-api](https://pypi.org/project/onesignal-python-api/)                             | [GitHub](https://github.com/OneSignal/onesignal-python-api) |
| Java      | [onesignal-java-client](https://central.sonatype.com/artifact/com.onesignal/onesignal-java-client) | [GitHub](https://github.com/OneSignal/onesignal-java-api)   |
| Go        | [onesignal-go-api](https://pkg.go.dev/github.com/OneSignal/onesignal-go-api)                       | [GitHub](https://github.com/OneSignal/onesignal-go-api)     |
| PHP       | [onesignal/onesignal-php-api](https://packagist.org/packages/onesignal/onesignal-php-api)          | [GitHub](https://github.com/OneSignal/onesignal-php-api)    |
| Ruby      | [onesignal](https://rubygems.org/gems/onesignal)                                                   | [GitHub](https://github.com/OneSignal/onesignal-ruby-api)   |
| C# (.NET) | [OneSignalApi](https://www.nuget.org/packages/OneSignalApi)                                        | [GitHub](https://github.com/OneSignal/onesignal-dotnet-api) |
| Rust      | [onesignal-rust-api](https://crates.io/crates/onesignal-rust-api)                                  | [GitHub](https://github.com/OneSignal/onesignal-rust-api)   |

***

## 安装

<Note>
  以下版本号仅为示例。请检查每个 SDK 的包注册表以安装最新版本。
</Note>

<Tabs>
  <Tab title="Node.js">
    ```bash theme={null}
    npm install @onesignal/node-onesignal
    ```
  </Tab>

  <Tab title="Python">
    ```bash theme={null}
    pip install onesignal-python-api
    ```
  </Tab>

  <Tab title="Java">
    **Maven**

    ```xml theme={null}
    <dependency>
      <groupId>com.onesignal</groupId>
      <artifactId>onesignal-java-client</artifactId>
      <version>5.3.0</version>
    </dependency>
    ```

    **Gradle**

    ```groovy theme={null}
    implementation "com.onesignal:onesignal-java-client:5.3.0"
    ```
  </Tab>

  <Tab title="Go">
    ```bash theme={null}
    go get github.com/OneSignal/onesignal-go-api/v5
    ```
  </Tab>

  <Tab title="PHP">
    添加到 `composer.json`：

    ```json theme={null}
    {
      "require": {
        "onesignal/onesignal-php-api": "^5.3"
      }
    }
    ```

    然后运行 `composer update`。
  </Tab>

  <Tab title="Ruby">
    添加到您的 `Gemfile`：

    ```ruby theme={null}
    gem 'onesignal', '~> 5.3'
    ```

    然后运行 `bundle install`。
  </Tab>

  <Tab title="C# (.NET)">
    ```bash theme={null}
    dotnet add package OneSignalApi
    ```
  </Tab>

  <Tab title="Rust">
    添加到 `Cargo.toml` 的 `[dependencies]` 下：

    ```toml theme={null}
    onesignal-rust-api = "5.3.0"
    ```
  </Tab>
</Tabs>

***

## 配置

每个 SDK 都需要通过 API 密钥进行身份验证。有两种密钥类型：

* **REST API 密钥** — 大多数端点（发送通知、管理用户等）都需要。在您应用的**设置 > 密钥和 ID** 中找到。
* **组织 API 密钥** — 仅用于组织级端点，如创建或列出应用程序。在**组织设置**中找到。

<Tabs>
  <Tab title="Node.js">
    ```javascript theme={null}
    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);
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    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)
    ```
  </Tab>

  <Tab title="Java">
    ```java theme={null}
    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);
    ```
  </Tab>

  <Tab title="Go">
    ```go theme={null}
    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())
    ```
  </Tab>

  <Tab title="PHP">
    ```php theme={null}
    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
    );
    ```
  </Tab>

  <Tab title="Ruby">
    ```ruby theme={null}
    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
    ```
  </Tab>

  <Tab title="C# (.NET)">
    ```csharp theme={null}
    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);
    ```
  </Tab>

  <Tab title="Rust">
    ```rust theme={null}
    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
    }
    ```
  </Tab>
</Tabs>

<Warning>
  将 API 密钥存储在环境变量或密钥管理器中。切勿将它们提交到源代码控制中。
</Warning>

***

## 发送推送通知

通过定向至分段，向网页和移动端[订阅](./subscriptions)发送推送通知。这些示例展示了正常路径——在生产环境中请添加错误处理（try/catch、错误回调）。

<Tabs>
  <Tab title="Node.js">
    ```javascript theme={null}
    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);
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    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)
    ```
  </Tab>

  <Tab title="Java">
    ```java theme={null}
    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());
    ```
  </Tab>

  <Tab title="Go">
    ```go theme={null}
    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())
    ```
  </Tab>

  <Tab title="PHP">
    ```php theme={null}
    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();
    ```
  </Tab>

  <Tab title="Ruby">
    ```ruby theme={null}
    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}"
    ```
  </Tab>

  <Tab title="C# (.NET)">
    ```csharp theme={null}
    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);
    ```

    注意：.NET SDK 不会自动规范化换行符。如果内容包含 `\r\n`，请在传递给 `Contents` 之前进行规范化：

    ```csharp theme={null}
    var normalizedContent = yourContent
       .Replace("\\r\\n", "\n")
       .Replace("\\n", "\n")
       .Replace("\r\n", "\n")
       .Replace("\r", "\n");
    ```
  </Tab>

  <Tab title="Rust">
    ```rust theme={null}
    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;
    ```
  </Tab>
</Tabs>

***

## 发送电子邮件

通过 `email` 渠道向[订阅](./subscriptions)发送电子邮件。

<Tabs>
  <Tab title="Node.js">
    ```javascript theme={null}
    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);
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    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)
    ```
  </Tab>

  <Tab title="Java">
    ```java theme={null}
    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);
    ```
  </Tab>

  <Tab title="Go">
    ```go theme={null}
    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()
    ```
  </Tab>

  <Tab title="PHP">
    ```php theme={null}
    $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);
    ```
  </Tab>

  <Tab title="Ruby">
    ```ruby theme={null}
    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)
    ```
  </Tab>

  <Tab title="C# (.NET)">
    ```csharp theme={null}
    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);
    ```
  </Tab>

  <Tab title="Rust">
    ```rust theme={null}
    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;
    ```
  </Tab>
</Tabs>

***

## 发送短信

通过 `sms` 渠道向[订阅](./subscriptions)发送短信。

<Tabs>
  <Tab title="Node.js">
    ```javascript theme={null}
    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);
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    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)
    ```
  </Tab>

  <Tab title="Java">
    ```java theme={null}
    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);
    ```
  </Tab>

  <Tab title="Go">
    ```go theme={null}
    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()
    ```
  </Tab>

  <Tab title="PHP">
    ```php theme={null}
    $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);
    ```
  </Tab>

  <Tab title="Ruby">
    ```ruby theme={null}
    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)
    ```
  </Tab>

  <Tab title="C# (.NET)">
    ```csharp theme={null}
    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);
    ```
  </Tab>

  <Tab title="Rust">
    ```rust theme={null}
    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;
    ```
  </Tab>
</Tabs>

***

## 完整 API 参考

每个服务器 SDK 支持相同的 API 端点集。请参阅 SDK 的 API 文档获取完整方法列表，包括用户、订阅、分段、模板等。

| SDK       | API 参考                                                                                            |
| --------- | ------------------------------------------------------------------------------------------------- |
| Node.js   | [DefaultApi.md](https://github.com/OneSignal/node-onesignal/blob/main/DefaultApi.md)              |
| Python    | [DefaultApi.md](https://github.com/OneSignal/onesignal-python-api/blob/main/docs/DefaultApi.md)   |
| Java      | [DefaultApi.md](https://github.com/OneSignal/onesignal-java-api/blob/main/docs/DefaultApi.md)     |
| Go        | [DefaultApi.md](https://github.com/OneSignal/onesignal-go-api/blob/main/docs/DefaultApi.md)       |
| PHP       | [DefaultApi.md](https://github.com/OneSignal/onesignal-php-api/blob/main/docs/Api/DefaultApi.md)  |
| Ruby      | [DefaultApi.md](https://github.com/OneSignal/onesignal-ruby-api/blob/main/docs/DefaultApi.md)     |
| C# (.NET) | [DefaultApi.md](https://github.com/OneSignal/onesignal-dotnet-api/blob/main/docs/DefaultApi.md)   |
| Rust      | [default\_api docs](https://github.com/OneSignal/onesignal-rust-api/blob/main/docs/DefaultApi.md) |

有关底层 REST API，请参阅[完整 API 参考](/reference/create-message)。

***

## 常见问题

### 我应该选择哪个服务器 SDK？

使用与您后端语言匹配的 SDK。所有服务器 SDK 均由同一 OpenAPI 规范生成并支持相同的端点，因此各语言的功能完全相同。

### REST API 密钥和组织 API 密钥有什么区别？

**REST API 密钥**作用范围为单个应用，大多数操作（如发送通知和管理用户）都需要它。**组织 API 密钥**作用范围为您的组织，仅用于创建或列出应用程序。大多数集成只需要 REST API 密钥。

### 我可以直接使用 REST API 而不使用 SDK 吗？

可以。服务器 SDK 是 [OneSignal REST API](/reference/create-message) 的便捷封装。您可以使用任何 HTTP 客户端直接调用 API，使用 `key` 认证方案（`Authorization: key YOUR_REST_API_KEY`）。

### 这些 SDK 是自动生成的吗？

是的。所有服务器 SDK 均使用 [OpenAPI Generator](https://openapi-generator.tech) 从 OneSignal OpenAPI 规范生成。这确保了所有语言的 API 覆盖一致性。

***

## 相关页面

<Columns cols={2}>
  <Card title="REST API 概览" icon="code" href="/reference/rest-api-overview">
    端点、身份验证、速率限制和请求/响应格式。
  </Card>

  <Card title="密钥和 ID" icon="key" href="./keys-and-ids">
    查找您的 App ID、REST API 密钥和 Organization API 密钥。
  </Card>

  <Card title="事务性消息" icon="paper-plane" href="./transactional-messages">
    通过 API 使用个性化数据发送 OTP、收据和时间敏感警报。
  </Card>

  <Card title="身份验证" icon="shield-halved" href="./identity-verification">
    使用服务器生成的 JWT 保护您的集成，防止用户身份冒充。
  </Card>
</Columns>
