Batch push

更新时间:
复制 MD 格式

Send distinct messages to each push ID by customizing messages with template placeholders. Unlike template push, each push ID receives unique content.

Important

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

Before you call this API, complete the following:

  • Create a target template in the message push console with placeholders to enable personalized messages. For more information, see Create a Template.

  • Add SDK dependencies. For details, see SDK Preparation.

Request parameters

Parameter name

Type

Required

Example

Description

classification

String

No

1

Message type for the vivo push channel:

  • 0 - Operational message

  • 1 - System message

Default: 1.

taskName

String

Yes

Multiple test

Push task name.

appId

String

Yes

ONEX570DA89211721

mPaaS App ID

workspaceId

String

Yes

test

mPaaS workspace

deliveryType

Long

Yes

3

Target ID type:

  • 1 - Android device dimension

  • 2 - iOS device dimension

  • 3 - User dimension

  • 7 - HarmonyOS device dimension

Note

The maximum number of targets for user dimension and device dimension is 100.

templateName

String

Yes

Test template

Template name, created in the console.

targetMsgs

List

Yes

targetMsgs object list

Target object list. For detailed parameters, see targetMsgs object description.

expiredSeconds

Long

Yes

300

Message validity period, in seconds.

extendedParams

String

No

{“key1”:”value1”}

Unified extended parameters in Map format.

notifyType

String

No

Message channel type:

  • transparent - MPS self-built channel

  • notify - Default channel

strategyType

Integer

No

1

Push strategy 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 strategy details (JSON string). Required when strategyType is not 0. For specific parameters, see StrategyContent field description.

transparentMessagePayload

Map<String, JSONObject>

No

-

Vendor pass-through message body.

  • Key: Vendor channel type

    • Huawei channel is hms

    • Honor channel is honor

    • Google Firebase channel is fcm

    • HarmonyOS channel is harmonyos

  • Value: Pass-through message body. The pass-through message body pushed to the vendor uses this value.

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. Takes effect only when transparentMessagePayload is set.

Currently, only Huawei, Honor, and HarmonyOS support HIGH/NORMAL options.

For Huawei and Honor:

  • HIGH: Indicates high-priority pass-through

  • NORMAL: Or no parameter indicates normal pass-through

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 type message

"vivo": "1"

//vivo IM type message

}

Vendor message classification. For details, see Vendor message classification.

notifyLevel

Map

No

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

Vendor message notification level. OPPO message levels:

  • 1 - Notification bar

  • 2 - Notification bar + lock screen

  • 3 - Notification bar + lock screen + banner + vibration + ringtone

miChannelId

String

No

"123321"

Channel ID for the Xiaomi push channel.

activityEvent

String

No

Real-time activity event. Valid values:

  • update - Update event

  • end - End event

activityContentState

JSONObject

No

Real-time activity message content-state. Must match the parameters defined by the client.

dismissalDate

long

No

Expiration time for the real-time activity message, as a second-level timestamp. Defaults to 12 hours on iOS if not specified.

Note

Regarding the activityEvent parameter:

  • The expiration time set by dismissalDate is effective when activityEvent is an end event.

  • The expiration time set by dismissalDate is not effective when activityEvent is an update event.

  • If an end event is sent without a dismissalDate, the iOS system defaults to ending the real-time activity after 4 hours.

targetMsgs object description

Parameter name

Type

Required

Example

Description

target

String

Yes

userid1024

Target ID. The value depends on the deliveryType.

msgKey

String

Yes

1578807462788

Business message ID for troubleshooting. User-defined and must be unique.

templateKeyValue

String

No

{“money”:”200”,”name”:”Zhang San”}

Template parameters, in Map format, corresponding to the template specified by templateName. The key is the placeholder name, and the value is the value to be replaced. For example, the template content is (the placeholder name is between two #) Congratulations #name# for winning #money# dollars.

extendedParams

String

No

{“key1”:”value1”}

Extended parameters in Map format for per-message customization.

StrategyContent field description

Convert the JSON object to a string before sending.

Parameter name

Type

Required

Example

Description

fixedTime

long

No

1630303126000

Scheduled push timestamp (unit: milliseconds, accurate to seconds). When the push strategy type is scheduled (strategyType value is 1), fixedTime is required.

startTime

long

No

1640966400000

Loop cycle start timestamp (unit: milliseconds, accurate to days). When the push strategy type is loop (strategyType value is 2), startTime is required.

endTime

long

No

1672416000000

Loop cycle end timestamp (unit: milliseconds, accurate to days). The loop end time cannot exceed 180 days after the current day. When the push strategy type is loop (strategyType value is 2), endTime is required.

circleType

int

No

3

Loop type:

  • 1 - Daily

  • 2 - Weekly

  • 3 - Monthly

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

circleValue

int[]

No

[1,3]

Loop value:

  • If the loop type is daily: empty

  • If the loop type is weekly: set the weekly loop time. For example, [1,3] means every Monday and Wednesday.

  • If the loop type is monthly: set the monthly loop push time. For example, [1,3] means the 1st and 3rd of each month.

When the push strategy type is loop (strategyType value is 2) and the loop type (circleType) is not daily, circleValue is required.

time

String

No

09:45:11

Loop push time (hour, minute, second, format is HH:mm:ss). When the push strategy type is loop (strategyType value is 2), time is required.

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

  • The loop cycle runs from 0:00 on the start day to 24:00 on the end day.

  • The loop start and end times cannot be earlier than 0:00 on the current day, and the end time cannot be before the start time.

Response parameters

Parameter name

Type

Example

Description

RequestId

String

B589F4F4-CD68-3CE5-BDA0-6597F33E23916512

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, included in the returned PushResult JSON string.

ResultMsg

String

param is invalid

Error message, included in the returned PushResult JSON string.

Data

String

903bf653c1b5442b9ba07684767bf9c2

Scheduled push task ID. Returned when strategyType is not 0.

Code examples

Your AccessKey must have the AliyunMPAASFullAccess permission. For details, see Resource Access Management Account Application-Level Access Control.

Java code example

For information about how to obtain the AccessKey ID and AccessKey secret used in the following example, see click here.

import com.alibaba.fastjson.JSON;
import com.aliyun.mpaas20201028.Client;
import com.aliyun.mpaas20201028.models.PushMultipleRequest;
import com.aliyun.mpaas20201028.models.PushMultipleRequest.PushMultipleRequestTargetMsg;
import com.aliyun.mpaas20201028.models.PushMultipleResponse;
import com.aliyun.teaopenapi.models.Config;
import java.util.ArrayList;
import java.util.List;

public static void main(String[] args) throws Exception {
    // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. 
    // We recommend that you do not save your AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources within your account is compromised. 
    // In this example, the AccessKey ID and AccessKey secret are saved as environment variables. You can also save the AccessKey pair in the configuration file based on your business requirements. 
    // We recommend that you configure 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, taking Hangzhou Non-Financial area as an example
    config.setRegionId("cn-hangzhou");
    config.setEndpoint("mpaas.cn-hangzhou.aliyuncs.com");
    Client client = new Client(config);

    PushMultipleRequest request = new PushMultipleRequest();
    request.setAppId("ONEX570DA89211721");
    request.setWorkspaceId("test");
    request.setTenantId("xxx");
    request.setTemplateName("Test Template - with Placeholders");
    request.setExpiredSeconds(180L);
    request.setTaskName("Batch Testing");
    request.setDeliveryType(3L);
    //Hello #name#, congratulations on winning #money# dollars
    List<PushMultipleRequestTargetMsg> targetMsgs = new ArrayList<>();
    PushMultipleRequestTargetMsg targetMsg = new PushMultipleRequestTargetMsg();
    targetMsg.setTarget("push_test");
    targetMsg.setMsgKey(String.valueOf(System.currentTimeMillis()));
    Map<String, String> templatekv = new HashMap<String, String>();
    templatekv.put("name", "John");
    templatekv.put("money", "200");
    targetMsg.setTemplateKeyValue(JSON.toJSONString(templatekv));
    //The number of targets should not exceed 100
    targetMsgs.add(targetMsg);
    request.setTargetMsg(targetMsgs);
    System.out.println("request==>"+JSON.toJSONString(request));
    PushMultipleResponse acsResponse = client.pushMultiple(request);
    System.out.println("response==>"+JSON.toJSONString(acsResponse));
}

Python code example

# -*- coding: utf8 -*-

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

// Alibaba Cloud account AccessKey has access to all APIs, which is very risky. It is strongly recommended to create and use a RAM user for API access or daily operations. Please log in to the RAM console to create a RAM user
// Here, the AccessKey and AccessKeySecret are stored in environment variables as an example. You can also save them in the configuration file based on your business needs
// It is strongly recommended not to save the AccessKey and AccessKeySecret in the code, as there is a risk of key leakage
// It is recommended to complete the environment variable configuration 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 = PushMultipleRequest.PushMultipleRequest()
request.set_endpoint("mpaas.cn-hangzhou.aliyuncs.com")
request.set_AppId("ONEX570DA89211721")
request.set_WorkspaceId("test")
request.set_TemplateName("template1024")
request.set_DeliveryType(3)
request.set_TaskName("python test task")
request.set_ExpiredSeconds(600)
msgkey = str(time.time())
targets = [
  {
    "Target": "user1024",
    "MsgKey": msgkey,
    "TemplateKeyValue": {
      "name": "Zhang San",
      "money": "200"
    }
  }
]
request.set_TargetMsgs(targets)
# Print response
response = client.do_action_with_exception(request)
print response

Node.js code example

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

const { default: Client, PushMultipleRequest,PushMultipleRequestTargetMsg } = sdk;
// Create a client
// Alibaba Cloud account AccessKey has access to all APIs, which is very risky. It is strongly recommended to create and use a RAM user for API access or daily operations. Please log in to the RAM console to create a RAM user
// Here, the AccessKey and AccessKeySecret are stored in environment variables as an example. You can also save them in the configuration file based on your business needs
// It is strongly recommended not to save the AccessKey and AccessKeySecret in the code, as there is a risk of key leakage
// It is recommended to complete the environment variable configuration 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 PushMultipleRequest();
  request.appId = "ONEX570DA89211721";
  request.workspaceId = "test";
  request.templateName= "template1024";
  const templatekv = {
    name: 'Zhang San',
    money:'300'
  };
  //request.templateKeyValue = JSON.stringify(templatekv);

  request.deliveryType = 3;
  request.taskName = "Node test task";
  request.expiredSeconds=600;
  const extendedParam = {
    test: 'Custom extended parameter'
  };
  request.extendedParams = JSON.stringify(extendedParam);

  const targetMsgkey = new PushMultipleRequestTargetMsg();
  targetMsgkey.target = "userid1024";
  targetMsgkey.msgKey = String(new Date().valueOf());
  targetMsgkey.templateKeyValue = JSON.stringify(templatekv);;
  request.targetMsg = [targetMsgkey];

// Call API
try {
  client.pushMultiple(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->multiPush();
        } catch (\Exception $e) {
        }
    }


   public function multiPush() {
        $request = MPaaS::v20190821()->pushMultiple();
        $result = $request->host("mpaas.cn-hangzhou.aliyuncs.com")
            // Whether to enable debug mode
            ->debug(true)
            ->withAppId("ONEX570DA89211721")
            ->withWorkspaceId("test")
            ->withTemplateName("template1024")
            ->withDeliveryType(3)
            ->withTaskName("PHP test multiple task")
            ->withExpiredSeconds(600)
            ->withTargetMsg(
                [
                    [
                        "Target" => "userid1024",
                        "MsgKey" => "" . time(),
                        "TemplateKeyValue" => json_encode([
                            "name" => "Zhang San",
                            "money" => "200",
                        ])
                    ]
                ]
            )
            ->request();
    }
}