PushV2 API integration guide

更新时间:
复制 MD 格式

This document provides an integration guide and best practices for the PushV2 API of Alibaba Cloud Mobile Push. It helps you quickly integrate the SDK to send push messages and notifications to iOS, Android, and HarmonyOS devices. If you are currently using the Push API, see the Migration Guide from Push API to PushV2 API.

Quick start

Prerequisites

  1. Log in to the Alibaba Cloud Mobile Push console, create an application, and obtain an AppKey.

  2. Obtain an Alibaba Cloud AccessKey ID and AccessKey secret.

  3. Set the environment variables:

export ALIBABA_CLOUD_ACCESS_KEY_ID="your-access-key-id"
export ALIBABA_CLOUD_ACCESS_KEY_SECRET="your-access-key-secret"

Integrate the SDK

Add the dependency to the pom.xml file. For the latest version, see the Alibaba Cloud SDK Center:

<dependency>
  <groupId>com.aliyun</groupId>
  <artifactId>push20160801</artifactId>
  <version>${push-sdk-version}</version>
</dependency>

First push example

import com.aliyun.push20160801.Client
import com.aliyun.push20160801.models.PushV2Request
import com.aliyun.teaopenapi.models.Config
import com.alibaba.fastjson.JSON

object QuickStart {
    @JvmStatic
    fun main(args: Array<String>) {
        // 1. Create a client.
        val client = createClient()

        // 2. Build a push request.
        val payload = """
            {
              "AppKey": 233586006,
              "PushTask": {
                "Target": {
                  "Type": "DEVICE",
                  "Value": "your-device-id",
                  "Platform": "IOS"
                },
                "Message": {
                  "Title": "Test Message",
                  "Body": "This is a pass-through message"
                }
              }
            }
        """.trimIndent()

        val parameters = JSON.parseObject(payload) as Map<String, Any>
        val request = PushV2Request.build(parameters)

        // 3. Send the push.
        val response = client.pushV2(request)
        println("Push successful! MessageId: ${response.body.messageId}")
    }

    private fun createClient(): Client {
        val config = Config().apply {
            accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
            accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
            endpoint = "cloudpush.aliyuncs.com"
            regionId = "cn-hangzhou"
        }
        return Client(config)
    }
}

Build a push request

Request structure preview

The PushV2 API uses a structured request body that categorizes and organizes its parameters. This structure lets you pass parameters flexibly as needed. The following list describes the request structure. For more information about the parameters, see the PushTask document:

image

Method 1: Build a request quickly using JSON

You can quickly define the push request content using a JSON string. This method is suitable for simple scenarios with clear structures. The following code provides an example:

val payload = """
    {
      "AppKey": 233586006,
      "PushTask": {
        "Target": {
          "Type": "DEVICE",
          "Value": "your-device-id",
          "Platform": "IOS"
        },
        "Message": {
          "Title": "Test Message",
          "Body": "This is a pass-through message"
        }
      }
    }
""".trimIndent()

val parameters = JSON.parseObject(payload) as Map<String, Any>
val request = PushV2Request.build(parameters)
Note

The sample code uses the fastjson library. You must add the dependency for this library. You can also use any other JSON library.

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>${VERSION}</version>
</dependency>

Method 2: Build a request using a struct

You can build a push request clearly and securely using the structs that the SDK provides. You can use chaining or layer-by-layer assignment. This method provides good readability and type safety, and is easy to maintain and extend in complex business logic. The following code provides an example:

val request = PushV2Request().apply {
    this.appKey = 233586006
    this.pushTask = PushTask().apply {
        this.target = PushTask.PushTaskTarget().apply {
            this.type = "DEVICE"
            this.value = "device-id"
            this.platform = "IOS"
        }
        this.message = PushTask.PushTaskMessage().apply {
            this.title = "Message Title"
            this.body = "Message Body"
        }
    }
}

Common push scenarios

Scenario 1: Send a pass-through message

Pass-through messages are sent directly to the application to be handled by the application logic. They do not trigger system notifications.

{
  "AppKey": 233586006,
  "PushTask": {
    "Target": {
      "Type": "DEVICE",
      "Value": "device-id",
      "Platform": "IOS"
    },
    "Message": {
      "Title": "Data Synchronization",
      "Body": "{\"type\": \"sync\", \"data\": \"...\"}"
    }
  }
}

Scenarios:

  • Receiving real-time data when the application is online

  • Data synchronization

  • In-app messages

Notes:

  • Messages are lost if the device is offline unless you set a time-to-live (TTL) using PushTask.Options.ExpireTime.

  • The request body must be in JSON format.

  • The total length cannot exceed 4000 bytes.

Scenario 2: Send a notification message

Notification messages are displayed in the device's notification bar. Users can tap them to view the details.

  • iOS notification example:

{
  "AppKey": 233586006,
  "PushTask": {
    "Target": {
      "Type": "DEVICE",
      "Value": "device-id",
      "Platform": "IOS"
    },
    "Notification": {
      "Title": "Order Reminder",
      "Body": "You have a new order",
      "Ios": {
        "ApnsEnv": "DEV",
        "Badge": 1,
        "Music": "default",
        "ExtParameters": "{\"orderId\": \"123456\"}"
      }
    }
  }
}
  • Android notification example:

{
  "AppKey": 233586006,
  "PushTask": {
    "Target": {
      "Type": "DEVICE",
      "Value": "device-id",
      "Platform": "ANDROID"
    },
    "Notification": {
      "Title": "Order Reminder",
      "Body": "You have a new order",
      "Android": {
        "BadgeSetNum": 1,
        "VendorChannelActivity": "com.example.MainActivity",
        "ChannelId": "8.0up",
        "ExtParameters": "{\"orderId\": \"123456\"}",
        "TestMessage": true
      }
    }
  }
}
  • HarmonyOS notification example:

{
  "AppKey": 233586006,
  "PushTask": {
    "Target": {
      "Type": "DEVICE",
      "Value": "device-id",
      "Platform": "HMOS"
    },
    "Notification": {
      "Title": "Order Reminder",
      "Body": "You have a new order",
      "Hmos": {
        "BadgeSetNum": 1,
        "ExtParameters": "{\"orderId\": \"123456\"}"
      }
    }
  }
}

Scenario 3: Convert offline messages to notifications

You can set both `Message` and `Notification`. If you do, a pass-through message is sent when the device is online, and a notification message is sent when the device is offline.

{
  "AppKey": 233586006,
  "PushTask": {
    "Target": {
      "Type": "DEVICE",
      "Value": "device-id",
      "Platform": "IOS"
    },
    "Message": {
      "Title": "New Message",
      "Body": "{\"type\": \"chat\", \"content\": \"Hello\"}"
    },
    "Notification": {
      "Title": "New Message",
      "Body": "You have a new message",
      "Ios": {
        "ApnsEnv": "DEV",
        "Badge": 1,
        "ExtParameters": "{\"orderId\": \"123456\"}"
      }
    }
  }
}

Scenarios:

  • Delivering important business messages that must be received

  • Supports both online application processing and offline notifications

Scenario 4: Scheduled push

You can push messages and notifications at a specified time.

{
  "AppKey": 233586006,
  "PushTask": {
    "Action": "SCHEDULED_PUSH",
    "Target": {
      "Type": "DEVICE",
      "Value": "device-id",
      "Platform": "IOS"
    },
    "Notification": {
      "Title": "Event Reminder",
      "Body": "The event you scheduled is about to start",
      "Ios": {
        "ApnsEnv": "PRODUCT"
      }
    },
    "Options": {
      "PushTime": "2025-06-19T12:00:00Z"
    }
  }
}

Scenario 5: Continuous push

You can use the continuous push feature to send the same message to different batches of devices. This prevents you from having to repeatedly rebuild the message.

Create a continuous push task

Key configurations

  • Set `Action` to `CREATE_CONTINUOUS_PUSH`.

  • Set the `Notification` parameter, but do not set the `Target` parameter.

  • Configure the complete message content.

Returned result

  • A `MessageId` is returned. You can use this ID for subsequent pushes.

{
  "AppKey": 233586006,
  "PushTask": {
    "Action": "CREATE_CONTINUOUS_PUSH",
    "Notification": {
      "Title": "Surprise Event",
      "Body": "Place an order now to get a 20% discount",
      "Ios": {
        "ApnsEnv": "PRODUCT"
      }
    }
  }
}

Execute a continuous push

Key configurations

  • Set `Action` to `CONTINUOUS_PUSH`.

  • Set `Target` to specify the push target.

  • Set the `MessageId` in the `Options` parameter.

Target limits

  • Only `DEVICE`, `ACCOUNT`, and `ALIAS` types are supported.

  • You can specify a maximum of 1,000 targets per request.

{
  "AppKey": 233586006,
  "PushTask": {
    "Action": "CONTINUOUS_PUSH",
    "Target": {
      "Type": "DEVICE",
      "Value": "device-id",
      "Platform": "IOS"
    },
    "Options": {
      "MessageId": 11747540331280012
    }
  }
}

FAQ

Q1: The push is successful, but the device does not receive it. Why?

Possible reasons:

  • The `DeviceId` is incorrect or the device is not registered.

  • The iOS environment configuration (`DEV`/`PRODUCT`) is incorrect.

  • The Android `VendorChannelActivity` configuration is incorrect.

  • The message has expired.

Solutions:

  • Verify that the `DeviceId` is correct.

  • Confirm that the iOS `ApnsEnv` configuration matches the certificate environment.

  • Verify the Android `Activity` configuration.

  • Set a reasonable time-to-live (TTL).

  • Use the console to troubleshoot the message delivery.

Q2: How can I improve the delivery rate for Android pushes?

Best practices:

  • Specify the `VendorChannelActivity` and `ChannelId`.

  • Configure vendor-specific parameters.

  • Set a reasonable message category and importance level.

Q3: How can I implement push deduplication?

Solutions:

  • Use `IdempotentToken` to ensure API idempotence.

  • Use `NotifyId` (Android) or `CollapseId` (iOS) to overwrite notifications.

  • Control the push frequency at the business layer.

Q4: How do I choose between pass-through messages and notification messages?

Recommendations:

  • Use a pass-through message if the application needs to process the message while it is online and you do not want to display a notification.

  • Use a notification message to remind the user through the system notification bar.

  • If you require both online processing and an offline reminder, set parameters for both message types.

Parameter quick reference

Time format

All time-related parameters must use the ISO 8601 format in UTC.

  • Format: `yyyy-MM-dd'T'HH:mm:ss'Z'`

  • Example: `2025-10-17T16:00:00Z`

Length limits

Content

Limit

Description

Entire `Message`

4000 bytes

UTF-8 encoding

iOS/HarmonyOS notification title

200 bytes

UTF-8 encoding

Android notification title

50 characters

-

Notification body

200 characters

-

`ExtParameters`

-

Standard JSON format

Target quantity limits

Target type

Maximum quantity per request

Device

1,000

ACCOUNT

1,000

Alias

1,000

Tag

Unlimited (tag expression)

ALL

All

References