Broadcast push

Updated at:

Sends the same message to all devices by using a template.

Important

When the push target is a Mobile Analysis audience or a custom tag audience, scheduled and recurring pushes are not supported.

Before you call this API, ensure that you have completed the following:

  • Create a target template in the Message Push console and ensure it contains placeholders. Otherwise, you cannot send personalized messages with unique content for each push ID. For details, see Create a template.

  • Add the required SDK dependency. For more information, see SDK preparation.

Request parameters

Parameter

Type

Required

Example

Description

classification

String

No

1

Specifies the message type for the vivo push channel.

  • 0: operational message

  • 1: system message

If this parameter is not specified, the default value is 1.

taskName

String

Yes

Broadcast test task

The name of the push task.

appId

String

Yes

ONEX570DA89211721

The mPaaS App ID.

workspaceId

String

Yes

test

The mPaaS workspace.

deliveryType

Long

Yes

1

The target device type. Valid values:

  • 1: Broadcast to Android

  • 2: Broadcast to iOS

  • 7: Broadcast to HarmonyOS

msgkey

String

Yes

1578807462788

The business message ID. This must be a user-defined, unique value.

expiredSeconds

Long

Yes

300

The message validity period, in seconds.

templateName

String

Yes

Broadcast template

The name of the template created in the console.

templateKeyValue

String

No

{content:Announcement content}

The template parameters, provided as a map. This map corresponds to the template specified by templateName. The key is the placeholder name, and the value is the content that replaces it.

pushStatus

Long

No

0

The binding status of the target users for the broadcast push:

  • 0: bound users (default)

  • 1: All users (including bound and unbound users)

  • 2: unbound users

bindPeriod

Integer

No

-

The binding duration. This parameter is required when pushStatus is set to 0. Valid values:

  • 1: Users bound within 7 days

  • 2: Users bound within 15 days

  • 3: Users bound within 60 days

  • 4: Permanent

Note

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

unBindPeriod

Long

No

-

The unbinding duration. This parameter is required when pushStatus is set to 1 or 2. Valid values:

  • 1: Users unbound within 7 days

  • 2: Users unbound within 15 days

  • 3: Users unbound 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 strategy type:

  • 0: Immediately

  • 1: Scheduled

  • 2: Recurring

If this parameter is not specified, the default value is 0.

StrategyContent

String

No

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

The push strategy details, in JSON format. This parameter is required if strategyType is not 0. For more information, see the StrategyContent field description below.

transparentMessagePayload

Map<String, JSONObject>

No

-

The vendor-specific transparent message payload.

  • Key: The vendor channel type.

    • hms for the Huawei channel.

    • honor for the Honor channel.

    • fcm for the Google FCM channel.

    • harmonyos for the HarmonyOS channel.

  • Value: The transparent message payload that is sent to the vendor.

The format of the transparent message payload is as follows:

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

transparentMessageUrgency

String

No

-

Vendor transparent message priority (effective only when transparentMessagePayload is set).

Currently, this is supported only by Huawei, Honor, and HarmonyOS. Valid values are HIGH and NORMAL.

For Huawei and Honor:

  • HIGH: high-priority transparent message.

  • NORMAL or unspecified: normal-priority transparent message.

For HarmonyOS:

  • HIGH: The message is a notification extension message.

  • NORMAL: The message is a background message.

thirdChannelCategory

Map

No

thirdChannelCategory: {

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

"vivo": "1"

//vivo IM message type

}

Specifies the vendor message category. For details, see Vendor Message Category.

notifyLevel

Map

No

notifyLevel: {"oppo":"2"//OPPO: Notification bar + Lock screen}

The notification level for the vendor message. For example, OPPO supports the following levels:

  • 1: Notification bar

  • 2: Notification bar + Lock screen

  • 3: Notification bar + Lock screen + Banner + Vibration + Ringtone

miChannelId

String

No

"123321"

The channel ID for the Xiaomi vendor push channel.

timeMode

Integer

No

0

The time mode:

  • 0: Fixed days (default)

  • 1: Time range

bindStartTime

Long

No

1746720000000

The binding start timestamp.

bindEndTime

Long

No

1746806219999

The binding end timestamp.

unBindStartTime

Long

No

1746720000000

The unbinding start timestamp.

unBindEndTime

Long

No

1746806219999

The unbinding end timestamp.

vendorTemplate

Json String

No

-

The vendor template information, provided as a JSON string. The key can be miui or oppo. For the structure of the value, see VendorTemplateInfo object. This field must be used with miChannelId. To create a template, see Update notice on new regulations for message template pushes.

VendorTemplateInfo object

Parameter

Type

Required

Description

templateId

String

Yes

Template ID

templateParams

Map<String, Object>

Yes

Template parameters

The following examples show the VendorTemplateInfo parameters for the Xiaomi and OPPO platforms. Configure the fields according to your platform's requirements.

  • Xiaomi

    {
      "templateId": "1001",
      "templateParams": {
        "app_name": "Xiaomi Store",
        "order_no": "XM202601130001"
      }
    }

    The app_name and order_no parameters correspond to the placeholder parameters in the title or content fields of the Xiaomi platform's message template.

  • OPPO

    {
      "templateId": "TPL_001",
      "templateParams": {
        "titleParams": {
          "city": "Beijing"
        },
        "contentParams": {
          "userName": "Zhang San"
        }
      }
    }

    The titleParams and contentParams parameter structures are fixed. Here, city corresponds to the placeholder parameter in the title field of the OPPO platform's message template, and userName corresponds to the placeholder parameter in the content field. These are dynamically replaced when the push is sent.

StrategyContent field

Provide this value as a JSON-formatted string.

Parameter

Type

Required

Example

Description

fixedTime

long

No

1630303126000

The timestamp for a scheduled push, in milliseconds, accurate to the second. The fixedTime parameter is required when the push strategy type is scheduled (the value of strategyType is 1).

startTime

long

No

1640966400000

The start timestamp of the recurring cycle. The unit is milliseconds and the value must be accurate to the day. The startTime parameter is required when the push strategy type is recurring (strategyType is 2).

endTime

long

No

1672416000000

The end timestamp of the recurring cycle must be in milliseconds, accurate to the day, and no more than 180 days after the current day. The endTime parameter is required when the push strategy type is recurring (strategyType is set to 2).

circleType

int

No

3

The recurrence type:

  • 1: Daily

  • 2: Weekly

  • 3: Monthly

When the push strategy type is recurring (strategyType is 2), circleType is required.

circleValue

int[]

No

[1,3]

The recurrence value:

  • If circleType is 1 (Daily), this parameter is not used.

  • If circleType is 2 (Weekly), specify the days of the week for the recurring push. For example, [1,3] means Monday and Wednesday.

  • If circleType is 3 (Monthly), specify the days of the month for the recurring push. For example, [1,3] means the 1st and 3rd of each month.

If the push strategy type is recurring (strategyType is 2) and the recurring type (circleType) is not daily, circleValue is required.

time

String

No

09:45:11

The recurring push time, in HH:mm:ss format. The time parameter is required if the push strategy type is recurring (strategyType is 2).

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

  • The recurring cycle runs from 00:00 on the start date to the end of the day on the end date.

  • The recurrence start time cannot be in the past. The end time must be after the start time.

Response parameters

Parameter

Type

Example

Description

RequestId

String

B589F4F4-CD68-3CE5-BDA0-6597F33E23916512

The request ID.

ResultCode

String

OK

The request result code.

ResultMessage

String

param is invalid

The error description.

PushResult

JSON

The result of the request.

Success

boolean

true

Indicates whether the request was successful. The Success parameter is part of the PushResult JSON string.

ResultMsg

String

param is invalid

The error details. The ResultMsg parameter is part of the PushResult JSON string.

Data

String

903bf653c1b5442b9ba07684767bf9c2

The scheduled push task ID. This field is returned if the push is scheduled or recurring (strategyType is not 0).

Code examples

Ensure that your AccessKey has the AliyunMPAASFullAccess permission. For more information, see Grant app-level access permissions to a RAM user.

Java code example

The following code examples require an AccessKey ID and AccessKey secret. Click here to learn how to obtain them.

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 AccessKey grants full access to all APIs. We recommend using a RAM user for API access and daily operations.
    // Do not hard-code your AccessKey ID and AccessKey secret in your code. Leaking your AccessKeys compromises the security of all resources in your account.
    // This example shows how to store your AccessKey ID and AccessKey secret in environment variables. You can also store them in a configuration file based on your business needs.
    // 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 for mPaaS. This example uses a non-production environment in Hangzhou.
    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 days, 1: Time range
    // request.setTimeMode(1);
    // 0: bound users, 1: All users (including bound and unbound users), 2: unbound users
    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
import os

# An Alibaba Cloud AccessKey grants full access to all APIs, which poses a high security risk. We strongly recommend that you create and use a RAM user for API access and daily operations. To create a RAM user, log on to the RAM console.
# This example shows how to store your AccessKey ID and AccessKey secret in environment variables. You can also store them in a configuration file based on your business needs.
# Do not hard-code your AccessKey ID and AccessKey secret in your project code. This can lead to a secret key leak.
# We recommend that you configure the environment variables first.
# Initialize AcsClient instance
accessKeyId = os.getenv("MPAAS_AK_ENV")
accessKeySecret = os.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 AccessKey grants full access to all APIs, which poses a high security risk. We strongly recommend that you create and use a RAM user for API access and daily operations. To create a RAM user, log on to the RAM console.
// This example shows how to store your AccessKey and AccessKeySecret in environment variables. You can also store them in a configuration file based on your business needs.
// Do not hard-code your AccessKey and AccessKeySecret in your project code. This can lead to a secret key leak.
// We recommend that you configure the environment variables first.
const accessKeyId = process.env.MPAAS_AK_ENV;
const accessKeySecret = process.env.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 the 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")
            // Enable 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();
    }
}