Broadcast push

更新时间:
复制 MD 格式

Sends the same template-based message to all devices on the network.

Important

Scheduled and recurring pushes are not supported when the target audience is a mobile analytics group or a custom tag group.

Before you call this API:

  • Create a target template with placeholders in the Message Push console to enable personalized messages per push ID. Create a template.

  • Import SDK dependencies. SDK preparation.

Request parameters

Parameter name

Type

Required

Example

Description

classification

String

No

1

The message type for the vivo push channel.

  • 0: Operational messages

  • 1: System messages

Default: 1.

taskName

String

Yes

Broadcast test task

Push task name.

appId

String

Yes

ONEX570DA89211721

The mPaaS App ID.

workspaceId

String

Yes

test

The mPaaS workspace.

deliveryType

Long

Yes

1

The target ID type. Valid values:

  • 1: Android broadcast

  • 2: iOS broadcast

  • 7: HarmonyOS broadcast

msgkey

String

Yes

1578807462788

User-defined unique business message ID.

expiredSeconds

Long

Yes

300

Message validity period, in seconds.

templateName

String

Yes

Broadcast template

Template name. Create templates in the console.

templateKeyValue

String

No

{"content":"Announcement content"}

Template parameters in map format for the template specified by templateName. Key: placeholder name. Value: replacement value.

pushStatus

Long

No

0

The logon status for broadcast push.

  • 0: Attached users (default)

  • 1: All users (including attached and detached users)

  • 2: Detached users

bindPeriod

Integer

No

Logon duration. Required when pushStatus is 0.

  • Users attached 1 to 7 days ago

  • 2: Users attached within 15 days

  • 3: Users attached within 60 days

  • 4: Permanent

Note

The bindPeriod parameter can only be configured in non-Gold environments.

unBindPeriod

Long

No

Logoff duration. Required when pushStatus is 1 or 2.

  • 1: Users detached within 7 days

  • 2: Users detached within 15 days

  • 3: Users detached within 60 days

  • 4: Permanent

androidChannel

Integer

No

The Android message channel.

  • 1: MPS self-built channel

  • 2: Default channel

strategyType

int

No

1

The push policy type.

  • 0: Immediate

  • 1: Scheduled

  • 2 - loop

Default: 0.

StrategyContent

String

No

{\”fixedTime\”:1630303126000,\”startTime\”:1625673600000,\”endTime\”:1630303126000,\”circleType\”:1,\”circleValue\”:[1, 7],\”time\”:\”13:45:11\”}

Push policy details as a JSON string. Required when strategyType is not 0. See the StrategyContent field description below.

transparentMessagePayload

Map<String, JSONObject>

No

-

The vendor pass-through message body.

  • Key: The vendor channel type.

    • hms for Huawei channel

    • honor for Honor channel

    • fcm for Google Firebase channel

    • harmonyos for HarmonyOS channel

  • Value: Pass-through message body sent to the vendor.

The format of the pass-through message body is as follows:

{
	"data": "{\"name\":\"123hms\"}",
	"android": {
		"category": "VOIP",
		"ttl": "600s",
		"urgency": "HIGH"
	},
	"token": [
		"9912981981wqdq2112291fcm001saa222222222ggwerfw gsas2cc3"
	]
}

transparentMessageUrgency

String

No

-

Vendor pass-through message priority. Valid only when `transparentMessagePayload` is set.

Only Huawei, Honor, and HarmonyOS support this parameter. Valid values: HIGH, NORMAL.

For Huawei and Honor:

  • HIGH: Indicates a high-priority pass-through message.

  • NORMAL or leaving the parameter empty: Indicates a normal-priority pass-through message.

For HarmonyOS:

  • HIGH: The current message is a notification extension message.

  • NORMAL: The current message is a background message.

thirdChannelCategory

Map

No

thirdChannelCategory: {

"hms": "9", //Huawei FINANCE message

"vivo": "1"

//vivo IM message

}

Vendor message categorization. Vendor message categorization.

notifyLevel

Map

No

notifyLevel: {"oppo":"2"//OPPO notification bar + lock screen}

Vendor message notification level. OPPO message levels:

  • 1: Notification bar

  • 2: Notification bar and lock screen

  • 3: Notification bar, lock screen, banner, vibration, and ringtone

miChannelId

String

No

"123321"

Xiaomi push channel ID.

timeMode

Integer

No

0

The time mode.

  • 0: Fixed number of days (default)

  • 1: Time range

bindStartTime

Long

No

1746720000000

The start timestamp for attachment.

bindEndTime

Long

No

1746806219999

The end timestamp for attachment.

unBindStartTime

Long

No

1746720000000

The start timestamp for detachment.

unBindEndTime

Long

No

1746806219999

The end timestamp for detachment.

StrategyContent field description

Pass the value as a JSON string.

Parameter name

Type

Required

Example

Description

fixedTime

long

No

1630303126000

Scheduled push timestamp in milliseconds, accurate to the second. fixedTime is required when strategyType is 1.

startTime

long

No

1640966400000

Start timestamp of the recurring cycle. UNIX timestamp in milliseconds, accurate to the day. startTime is required when strategyType is 2.

endTime

long

No

1672416000000

End timestamp of the recurring cycle in milliseconds, accurate to the day. Cannot exceed 180 days from today. endTime is required when strategyType is 2.

circleType

int

No

3

Loop type:

  • 1: Daily

  • 2: Weekly

  • 3: Monthly

circleType is required when strategyType is 2.

circleValue

int[]

No

[1,3]

The recurrence value.

  • If the recurrence type is daily, this is empty.

  • If the recurrence type is weekly, set the days of the week for recurrence. For example, [1,3] means Monday and Wednesday.

  • If the recurrence type is monthly, set the days of the month for recurrence. For example, [1,3] means the 1st and 3rd of the month.

circleValue is required when strategyType is 2 and circleType is not daily.

time

String

No

09:45:11

Recurring push time in HH:mm:ss format. time is required when strategyType is 2.

Note
  • The maximum number of pending scheduled or recurring push tasks is 100 by default.

  • The recurring epoch starts at 00:00 on the start date and ends at 24:00 on the end date.

  • The start and end times for a recurring task cannot be earlier than 00:00 on the current day. The end time cannot be earlier than the start time.

Response parameters

Parameter name

Type

Example

Description

RequestId

String

B589F4F4-CD68-3CE5-BDA0-6597F33E23916512

The request ID.

ResultCode

String

OK

Request result code.

ResultMessage

String

param is invalid

Request error description.

PushResult

JSON

Request result.

Success

boolean

true

Request status. Success is included in the PushResult JSON string.

ResultMsg

String

param is invalid

Error details. ResultMsg is included in the PushResult JSON string.

Data

String

903bf653c1b5442b9ba07684767bf9c2

Scheduled push task ID. Non-empty when strategyType is not 0.

Code examples

Your AccessKey must have the `AliyunMPAASFullAccess` permission. Application-level access control for RAM accounts.

Java code example

To obtain the AccessKey ID and AccessKey secret used in the example below, see AccessKey management.

import com.alibaba.fastjson.JSON;
import com.aliyun.mpaas20201028.Client;
import com.aliyun.mpaas20201028.models.PushBroadcastRequest;
import com.aliyun.mpaas20201028.models.PushBroadcastResponse;
import com.aliyun.teaopenapi.models.Config;
import java.text.SimpleDateFormat;

public static void main(String[] args) throws Exception {
    // An Alibaba Cloud account AccessKey has full access to all APIs. We recommend that you use a RAM user for API calls and daily O&M.
    // We strongly recommend that you do not hard-code the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and threaten the security of all your resources.
    // This example shows how to store the AccessKey ID and AccessKey secret in environment variables. You can also store them in a configuration file as needed.
    // We recommend that you configure the environment variables first.
    Config config = new Config();
    // Required. Your AccessKey ID.
    config.setAccessKeyId(System.getenv("MPAAS_AK_ENV"));
    // Required. Your AccessKey secret.
    config.setAccessKeySecret(System.getenv("MPAAS_SK_ENV"));
    // The REGION_ID and Endpoint of mPaaS. The Hangzhou non-Gold environment is used as an example.
    config.setRegionId("cn-hangzhou");
    config.setEndpoint("mpaas.cn-hangzhou.aliyuncs.com");
    Client client = new Client(config);

    PushBroadcastRequest request = new PushBroadcastRequest();
    request.setAppId("ONEX570DA89211721");
    request.setWorkspaceId("test");
    request.setTenantId("xxx");
    request.setTemplateName("Test Template");
    request.setExpiredSeconds(180L);
    request.setTaskName("Broadcast Task");
    request.setAndroidChannel(2);
    // 1: Android, 2: iOS, 7: HarmonyOS
    request.setDeliveryType(1L);
    // 0: Fixed number of days, 1: Time range
    // request.setTimeMode(1);
    // 0: Query attached devices, 1: Query attached/detached device information, 2: Query detached device information
    request.setPushStatus(0L);
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    long startTime = dateFormat.parse("2024-05-20 15:59:48").getTime();
    long endTime = dateFormat.parse("2024-05-20 15:59:48").getTime();
    request.setBindStartTime(startTime);
    request.setBindEndTime(endTime);
    request.setMsgkey(String.valueOf(System.currentTimeMillis()));
    System.out.println("request==>"+JSON.toJSONString(request));
    PushBroadcastResponse acsResponse = client.pushBroadcast(request);
    System.out.println("response==>"+JSON.toJSONString(acsResponse));
}

Python code example

# -*- coding: utf8 -*-

from aliyunsdkcore.client import AcsClient
from aliyunsdkmpaas.request.v20190821 import PushBroadcastRequest
import json
import time

// An Alibaba Cloud account AccessKey has full access to all APIs, which poses a high security risk. We strongly recommend that you create and use a RAM user for API calls and daily O&M. Log on to the RAM console to create a RAM user.
// This example shows how to store the AccessKey and AccessKey secret in environment variables. You can also store them in a configuration file as needed.
// We strongly recommend that you do not hard-code the AccessKey and AccessKey secret in your code to avoid key leakage.
// We recommend that you configure the environment variables first.
# Initialize AcsClient instance
String accessKeyId = System.getenv("MPAAS_AK_ENV");
String accessKeySecret = System.getenv("MPAAS_SK_ENV");
client = AcsClient(
accessKeyId,      
accessKeySecret, 
"cn-hangzhou"
);

# Initialize a request and set parameters
request = PushBroadcastRequest.PushBroadcastRequest()
request.set_endpoint("mpaas.cn-hangzhou.aliyuncs.com")
request.set_AppId("ONEX570DA89211720")
request.set_WorkspaceId("test")
request.set_TemplateName("broadcastTemplate")
templatekv = {"content":"This is an announcement"}
request.set_TemplateKeyValue(json.dumps(templatekv))
request.set_DeliveryType(1)
request.set_TaskName("Python test broadcast task")
request.set_ExpiredSeconds(600)
request.set_Msgkey(str(time.time()))

# Print response
response = client.do_action_with_exception(request)
print response

Node.js code example

const sdk = require('@alicloud/mpaas20190821');

const { default: Client, PushBroadcastRequest } = sdk;
// Create a client
// An Alibaba Cloud account AccessKey has full access to all APIs, which poses a high security risk. We strongly recommend that you create and use a RAM user for API calls and daily O&M. Log on to the RAM console to create a RAM user.
// This example shows how to store the AccessKey and AccessKey secret in environment variables. You can also store them in a configuration file as needed.
// We strongly recommend that you do not hard-code the AccessKey and AccessKey secret in your code to avoid key leakage.
// We recommend that you configure the environment variables first.
String accessKeyId = System.getenv("MPAAS_AK_ENV");
String accessKeySecret = System.getenv("MPAAS_SK_ENV");
const client = new Client({
  accessKeyId,      
  accessKeySecret, 
  endpoint: 'mpaas.cn-hangzhou.aliyuncs.com',
  apiVersion: '2019-08-21'
});
// Initialize request

  const request = new PushBroadcastRequest();
  request.appId = "ONEX570DA89211720";
  request.workspaceId = "test";
  request.templateName= "broadcastTemplate";
  const templatekv = {
    content: 'This is an announcement',
  };
  request.templateKeyValue = JSON.stringify(templatekv);
  request.deliveryType = 1;
  request.taskName = "Node.js test task";
  request.expiredSeconds=600;
  const extendedParam = {
    test: 'Custom extended parameter'
  };
  request.extendedParams = JSON.stringify(extendedParam);

  request.msgkey = String(new Date().valueOf())

// Call API
try {
  client.pushBroadcast(request).then(res => {
    console.log('SUCCESS', res);
  }).catch(e => {
    console.log('FAIL', e);
  });
} catch(e) {
  console.log('ERROR', e);
}

PHP code example

<?php

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\MPaaS\MPaaS;
AlibabaCloud::accessKeyClient('accessKeyId', 'accessKeySecret')
    ->regionId('cn-hangzhou')
    ->asDefaultClient();

class Demo {
    public function run() {
        try {
               $this->broadcastPush();
        } catch (\Exception $e) {
        }
    }


   public function broadcastPush(){
        $request = MPaaS::v20190821()->pushBroadcast();
        $result = $request->host("mpaas.cn-hangzhou.aliyuncs.com")
            // Specifies whether to enable the debug mode
            ->debug(true)
            ->withAppId("ONEX570DA89211720")
            ->withWorkspaceId("test")
            ->withTemplateName("broadcastTemplate")
            ->withTemplateKeyValue(
                json_encode(["content" => "This is an announcement"])
            )
            ->withDeliveryType(1)
            ->withTaskName("PHP test broadcast task")
            ->withExpiredSeconds(600)
            ->withMsgkey("". time())
            ->request();
    }
}