All Products
Search
Document Center

Server APIs

Last Updated: Jan 17, 2022

Message Push Service (MPS) provides the following Open APIs for the server to implement the functions of message push (simple push, template push, multiple push, and broadcast push), message revocation, message statistics and analysis, and scheduled push. As for message push, MPS supports immediate push, timed push, and scheduled push three push strategies to meet the push requirements in different scenarios and reduce repetitive work.

API

Description

Push message - simple push

Push one message to one target ID.

Push message - template push

Push one message to one target ID. The message is created based on a template.

Push message - multiple push

Push different messages to multiple target IDs. Based on the template, configure different template placeholders for the target IDs to Implement personalized message push by use template placeholders based on the template.

Push message - broadcast push

Push the same message to all devices. The message is created based on a template.

Revoke messages

Retract the pushed messages.

Messages pushed through simple push or template push can be withdrawn through message ID; messages pushed through the multiple push or broadcast push can be withdrawn through task ID.

Analyze message push

Query message push statistical data, including pushed messages, successfully pushed messages, message arrivals, opened messages, and ignored messages, and query the multiple/broadcast push tasks created on MPS console or triggered by calling API as well as the task details.

Manage scheduled push tasks

Support querying the scheduled push task list and canceling the scheduled push task. Scheduled push fall into two types: timed push and cyclic push:

  • Timed push: Push messages at a specified time. For example, push messages at 8:00 AM on June 19.

  • Cyclic push: Push messages repeatedly within a specified time period. For example, push messages at 8:00 AM every Friday from June 1 to September 30. A cyclic push task may generate one or more scheduled push tasks.

SDK preparations

MPS supports four programming languages: Java, Python, Node.js, and PHP. Before you call the preceding APIs for message push, you should make different preparations for different programming languages.

The following examples describe the preparations needed before implementing the SDK for different programming languages.

Java

Before you call the preceding four APIs for message push, introduce the Maven configuration. Import the following dependencies to the main pom file:

<dependency>
  <groupId>com.aliyun</groupId>
  <artifactId>aliyun-java-sdk-mpaas</artifactId>
    <version>3.0.6</version>
</dependency>

<dependency>
<groupId>com.aliyun</groupId>
  <artifactId>aliyun-java-sdk-core</artifactId>
  <optional>true</optional>
  <version>[4.3.2,5.0.0)</version>
</dependency>

Python

Run the following commands to add relevant dependencies.

## Aliyun SDK
pip install aliyun-python-sdk-core
## mPaaSs SDK 
pip install aliyun-python-sdk-mpaas

Node.js

Run the following commands to add relevant dependencies.

npm i @alicloud/mpaas20190821

PHP

Run the following commands to add relevant dependencies.

composer require alibabacloud/sdk

Push message - simple push

Push one message to one target ID.Before you call this API, you must introduce the required dependencies. For more information, see SDK preparations.

Request parameters

Parameter

Data type

Required

Example

Description

taskName

String

Yes

simpleTest

The name of push task

title

String

Yes

Test

Message title

content

String

Yes

Test

Message body

appId

String

Yes

ONEX570DA89211721

mPaaS App ID

workspaceId

String

Yes

test

mPaaS workspace

deliveryType

Long

Yes

3

The type of target ID. Valid values:

  • 1 - Android device

  • 2 - iOS device

  • 3 - User

targetMsgkey

String

Yes

{“user1024”:”1578807462788”}

Targets to which the message will be pushed, in the map format:

  • key: The target, which depends on the value of deliveryType.

    If the value of deliveryType is 1, the key is Android device ID.

    If the value of deliveryType is 2, the key is iOS device ID.

    If the value of deliveryType is 3, the key is userid.

  • value: The business ID of the message, which is user-defined and must be unique.

Note that the number of the targets cannot exceed 10.

expiredSeconds

Long

Yes

300

The validity period of message, in seconds.

pushStyle

Integer

Yes

0

Push style:

  • 0 - Default

  • 1 - Big text

  • 2 - Image and text

extendedParams

String

No

{“key1”:”value1”}

The extension parameters, in the map format.

pushAction

Long

No

0

The redirection method upon a tap on the message. Valid values:

  • 0: Web URL

  • 1 - Intent Activity

The default redirection method is Web URL.

uri

String

No

http://www

The URL to be redirected to upon a tap on the message.

silent

Long

No

1

Specify whether the message is silent. Valid values:

  • 1 - Silent

  • 0 - Not silent

notifyType

String

No

Message push channel:

  • transparent - MPS self-built channel

  • notify - Default channel

imageUrls

String

No

Large image link (JSON string), supported in OPPO, MIUI, FCM and iOS push channels. You can use defaultUrl as the default value.

iconUrls

String

No

Icon link (JSON string), supported in OPPO, MIUI, FCM and iOS push channels. You can use defaultUrl as the default value.

strategyType

int

No

1

Push strategy:

  • 0 - Immediately

  • 1 - Timed

  • 2 - Cyclic

It is 0 by default.

strategyDetail

String

No

Push strategy details (JSON string). This parameter is required when the value of strategyType is not 0. See the following strategyDetail field description for details.

strategyDetail fields

JSON value is converted to String and passed in.

Parameter

Data type

Required

Example

Description

fixedTime

long

No

1630303126000

Scheduled push timestamp (in ms, accurate to second).

When the push strategy is Timed (the value of strategyType is 1), fixedTime is required.

startTime

long

No

1640966400000

Cycle period start timestamp (in ms, accurate to day).

When the push strategy is Cyclic (the value of strategyType is 2), startTime is required.

endTime

long

No

1672416000000

Cycle period end timestamp (in ms, accurate to day). The end time cannot exceed 180 days after the current day.

When the push strategy is Cyclic (the value of strategyType is 2), endTime is required.

circleType

int

No

3

Loop type:

  • 1 - Daily

  • 2 - Weekly

  • 3 - Monthly

When the push strategy is Cyclic (the value of strategyType is 2), circleType is required.

circleValue

int[]

No

[1,3]

Cycle value:

  • If the loop type is daily: Empty

  • If the loop type is weekly: Set the cyclic push time every week. For example, [1,3] means pushing the message every Monday and Wednesday.

  • If the loop type is monthly: Set the cyclic push time every month. For example, [1,3] means pushing the message on the 1st and 3rd day every month.

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

time

String

No

09:45:11

Cyclic push time (time format: HH:mm:ss).

When the push strategy is Cyclic (the value of strategyType is 2), time is required.

Note
  • The upper limit of unexecuted timed or cyclic push tasks is 100 by default.

  • The cycle period is from 00:00 at the start date to 24:00 at the end date.

  • Neither the cycle start time nor the end time can be earlier than 00:00 of the day, and the end time cannot be earlier than the start time.

Return parameters

Parameter

Data type

Example

Description

RequestId

String

B589F4F4-CD68-3CE5-BDA0-6597F33E23916512

Request ID

ResultCode

String

OK

Request result code

ResultMessage

String

param is invalid

Error description

PushResult

JSON

Request result

Success

boolean

true

Request status. The value of Success is contained in the PushRresult JSON string.

ResultMsg

String

param is invalid

Error content. The value of ResultMsg is contained in the PushRresult JSON string.

Data

String

903bf653c1b5442b9ba07684767bf9c2

Scheduled push task ID. When strategyType is not 0 , this field is not empty.

Java sample code

Click here for information about how to obtain the AccessKey ID and AccessKey secret in the following sample code.

 DefaultProfile.addEndpoint("cn-hongkong", "mpaas", "mpaas.cn-hongkong.aliyuncs.com");
        // Create a DefaultAcsClient instance and initialize it
        DefaultProfile profile = DefaultProfile.getProfile(
            "cn-hangzhou",          // Region ID
            "******",      // The AccessKey ID of the RAM account
            "*****"); // The AccessKey secret of the RAM account

        IAcsClient client = new DefaultAcsClient(profile);
        // Create an API request and set parameters
        PushSimpleRequest request = new PushSimpleRequest();
        request.setAppId("ONEX570DA89211721");
        request.setWorkspaceId("test");
        request.setTaskName("Test task");
        request.setTitle("Test");
        request.setContent("Test");
        request.setDeliveryType(3L);
        Map<String,String> extendedParam = new HashMap<String, String>();
        extendedParam.put("key1","value1");
        request.setExtendedParams(JSON.toJSONString(extendedParam));
        request.setExpiredSeconds(300L);

        request.setPushStyle(2);
        String imageUrls = "{\"defaultUrl\":\"https://pre-mpaas.oss-cn-hangzhou.aliyuncs.com/tmp/test.png\",\"oppoUrl\":\"https://pre-mpaas.oss-cn-hangzhou.aliyuncs.com/tmp/test.png\",\"miuiUrl\":\"https://pre-mpaas.oss-cn-hangzhou.aliyuncs.com/tmp/test.png\",\"fcmUrl\":\"https://pre-mpaas.oss-cn-hangzhou.aliyuncs.com/tmp/test.png\",\"iosUrl\":\"https://pre-mpaas.oss-cn-hangzhou.aliyuncs.com/tmp/test.png\"}";
        String iconUrls = "{\"defaultUrl\":\"https://pre-mpaas.oss-cn-hangzhou.aliyuncs.com/tmp/test.png\",\"hmsUrl\":\"https://pre-mpaas.oss-cn-hangzhou.aliyuncs.com/tmp/test.png\",\"oppoUrl\":\"https://pre-mpaas.oss-cn-hangzhou.aliyuncs.com/tmp/test.png\",\"miuiUrl\":\"https://pre-mpaas.oss-cn-hangzhou.aliyuncs.com/tmp/test.png\"}";
        request.setImageUrls(imageUrls);
        request.setIconUrls(iconUrls);

        request.setStrategyType(2);
        request.setStrategyContent("{\"fixedTime\":1630303126000,\"startTime\":1625673600000,\"endTime\":1630303126000,\"circleType\":1,\"circleValue\":[1, 7],\"time\":\"13:45:11\"}");

        Map<String,String> target = new HashMap<String, String>();
        String msgKey = String.valueOf(System.currentTimeMillis());
        target.put("user1024",msgKey);
        request.setTargetMsgkey(JSON.toJSONString(target));
        // Initiate the request and handle the response or exceptions
        PushSimpleResponse response;
        try {
            response = client.getAcsResponse(request);
            System.out.println(response.getResultCode());
            System.out.println(response.getResultMessage());
        } catch (ClientException e) {
            e.printStackTrace();
        }

Python sample code

from aliyunsdkcore.client import AcsClient
from aliyunsdkmpaas.request.v20190821 import PushSimpleRequest
import json

# Initialize AcsClient instance
client = AcsClient(
  "***",
  "***",
  "cn-hongkong"
);

# Initialize a request and set parameters
request = PushSimpleRequest.PushSimpleRequest()
request.set_endpoint("mpaas.cn-hongkong.aliyuncs.com")
request.set_AppId("ONEX570DA89211721")
request.set_WorkspaceId("test")
request.set_Title( "Python test")
request.set_Content( "Test 2")
request.set_DeliveryType(3)
request.set_TaskName("The test task of Python template push")
request.set_ExpiredSeconds(600)
target = {"user1024":str(time.time())}
request.set_TargetMsgkey(json.dumps(target))

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

Node.js sample code

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

const { default: Client, PushSimpleRequest } = sdk;
// Create a client
const client = new Client({
  accessKeyId: '****',
  accessKeySecret: '*****',
  endpoint: 'mpaas.cn-hongkong.aliyuncs.com',
  apiVersion: '2019-08-21'
});
// Initialize the request.
  const request = new PushSimpleRequest();
  request.appId = "ONEX570DA89211721";
  request.workspaceId = "test";
  request.title = "Node test";
  request.content = "Test";
  request.deliveryType = 3;
  request.taskName = "Node test task";
  request.expiredSeconds=600;
  const extendedParam = {
    test: 'Custom extension parameter'
  };
  request.extendedParams = JSON.stringify(extendedParam);
// The value is the ID of the business message. Make sure that the ID is unique.
  const target = {
    "userid1024": String(new Date().valueOf())
  };
  request.targetMsgkey = JSON.stringify(target);

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

PHP sample code

<?php

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

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


    public function simplePush() {
        $request = MPaaS::v20190821()->pushSimple();
        $result = $request->withAppId("ONEX570DA89211721")
            ->withWorkspaceId("test")
            ->withTitle("PHP test")
            ->withContent("Test 3")
            ->withDeliveryType(3)
            ->withTaskName("PHP test task")
            ->withExpiredSeconds(600)
            ->withTargetMsgkey(
                json_encode(["userid1024" => "".time() ]
            ))
            // endpoint
            ->host("mpaas.cn-hongkong.aliyuncs.com")
            // Specify whether to enable the debug mode
            ->debug(true)
            ->request();
    }
}

Push message - template push

Template push refers to pushing one message to a single target ID. The message is created based on a template. Multiple IDs can share the same template.

Before you call the interface, ensure that you have completed the following operations:

  • You have created a template in the MPS console. For more information, see Create a template.

  • You have introduced the required dependencies. For more information, see SDK preparations.

Request parameters

Parameter

Data type

Required

Example

Description

taskName

String

Yes

templateTest

The name of push task

appId

String

Yes

ONEX570DA89211721

mPaaS App ID

workspaceId

String

Yes

test

mPaaS workspace

deliveryType

Long

Yes

3

The type of target ID. Valid values:

  • 1 - Android device

  • 2 - iOS device

  • 3 - User

targetMsgkey

String

Yes

{“user1024”:”1578807462788”}

Targets to which the message will be pushed, in the map format:

  • key: The target, which depends on the value of deliveryType.

    If the value of deliveryType is 1, the key is Android device ID.

    If the value of deliveryType is 2, the key is iOS device ID.

    If the value of deliveryType is 3, the key is userid.

  • value: The business ID of the message, which is user-defined and must be unique.

Note that the number of the targets cannot exceed 10.

expiredSeconds

Long

Yes

300

The validity period of message, in seconds.

templateName

String

Yes

testTemplate

The name of template. Create a template in the MPS console.

templateKeyValue

String

No

{“money”:”200”,”name”:”Bob”}

The parameters of template, in the map format. The parameters depend on the template specified by templateName. Key refers to the placeholder while value refers to the specific value that is used to replace the placeholder. For example, the content of a template can be Congratulations to #name# for winning RMB #money#. The string between two number signs “#” is the name of the placeholder.

extendedParams

String

No

{“key1”:”value1”}

The extension parameters, in the map format.

notifyType

String

No

Message push channel:

  • transparent - MPS self-built channel

  • notify - Default channel

strategyType

int

No

1

Push strategy:

  • 0 - Immediately

  • 1 - Timed

  • 2 - Cyclic

It is 0 by default.

strategyDetail

String

No

Push strategy details (JSON string). This parameter is required when the value of strategyType is not 0. See the following strategyDetail field description for details.

strategyDetail fields

JSON value is converted to String and passed in.

Parameter

type

Required

Example

Description

fixedTime

long

No

1630303126000

Scheduled push timestamp (in ms, accurate to second).

When the push strategy is Timed (the value of strategyType is 1), fixedTime is required.

startTime

long

No

1640966400000

Cycle period start timestamp (in ms, accurate to day).

When the push strategy is Cyclic (the value of strategyType is 2), startTime is required.

endTime

long

No

1672416000000

Cycle period end timestamp (in ms, accurate to day). The end time cannot exceed 180 days after the current day.

When the push strategy is Cyclic (the value of strategyType is 2), endTime is required.

circleType

int

No

3

Loop type:

  • 1 - Daily

  • 2 - Weekly

  • 3 - Monthly

When the push strategy is Cyclic (the value of strategyType is 2), circleType is required.

circleValue

int[]

No

[1,3]

Cycle value:

  • If the loop type is daily: Empty

  • If the loop type is weekly: Set the cyclic push time every week. For example, [1,3] means pushing the message every Monday and Wednesday.

  • If the loop type is monthly: Set the cyclic push time every month. For example, [1,3] means pushing the message on the 1st and 3rd day every month.

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

time

String

No

09:45:11

Cyclic push time (time format: HH:mm:ss).

When the push strategy is Cyclic (the value of strategyType is 2), time is required.

Note
  • The upper limit of unexecuted timed or cyclic push tasks is 100 by default.

  • The cycle period is from 00:00 at the start date to 24:00 at the end date.

  • Neither the cycle start time nor the end time can be earlier than 00:00 of the day, and the end time cannot be earlier than the start time.

Return parameters

Parameter

Data type

Example

Description

RequestId

String

B589F4F4-CD68-3CE5-BDA0-6597F33E23916512

Request ID

ResultCode

String

OK

Request result code

ResultMessage

String

param is invalid

Error description

PushResult

JSON

Request result

Success

boolean

true

Request status. The value of Success is contained in the PushRresult JSON string.

ResultMsg

String

param is invalid

Error content. The value of ResultMsg is contained in the PushRresult JSON string.

Data

String

903bf653c1b5442b9ba07684767bf9c2

Scheduled push task ID. When strategyType is not 0 , this field is not empty.

Java sample code

Click here for information about how to obtain the AccessKey ID and AccessKey secret in the following sample code.

 DefaultProfile.addEndpoint("cn-hongkong", "mpaas", "mpaas.cn-hongkong.aliyuncs.com");
        // Create a DefaultAcsClient instance and initialize it.
        DefaultProfile profile = DefaultProfile.getProfile(
            "cn-hangzhou",          // region ID
            "******",      // The AccessKey ID of the RAM account
            "******"); // The AccessKey secret of the RAM account

        IAcsClient client = new DefaultAcsClient(profile);
        // Create an API request and set parameters
        PushTemplateRequest request = new PushTemplateRequest();
        request.setAppId("ONEX570DA89211721");
        request.setWorkspaceId("test");
        request.setTemplateName("testTemplate");
        // Hello #name#. Congratulations to you for winning RMB #money#.
        Map<String,String> templatekv = new HashMap<String, String>();
        templatekv.put("name"," Bob");
        templatekv.put("money","200");
        request.setTemplateKeyValue(JSON.toJSONString(templatekv));
        request.setExpiredSeconds(600L);
        request.setTaskName("templateTest");
        request.setDeliveryType(3L);
        Map<String,String> target = new HashMap<String, String>();
        String msgKey = String.valueOf(System.currentTimeMillis());
        target.put("userid1024",msgKey);
        request.setTargetMsgkey(JSON.toJSONString(target));

        request.setStrategyType(2);
        request.setStrategyContent("{\"fixedTime\":1630303126000,\"startTime\":1625673600000,\"endTime\":1630303126000,\"circleType\":1,\"circleValue\":[1, 7],\"time\":\"13:45:11\"}");

        PushTemplateResponse response;
        try {
            response = client.getAcsResponse(request);

            System.out.println(response.getResultCode());
            System.out.println(response.getResultMessage());
        } catch (ClientException e) {
            e.printStackTrace();
        }

Python sample code

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

# Initialize AcsClient instance
client = AcsClient(
  "AccessKey ID",
  "AccessKey Secret",
  "cn-hongkong"
);

# Initialize a request and set parameters
request = PushTemplateRequest.PushTemplateRequest()
request.set_endpoint("mpaas.cn-hongkong.aliyuncs.com")
request.set_AppId("ONEX570DA89211721")
request.set_WorkspaceId("test")
request.set_TemplateName("template1024")
templatekv = {"name":"Bob","money":"200"}
request.set_TemplateKeyValue(json.dumps(templatekv))
request.set_DeliveryType(3)
request.set_TaskName("The test task of Python template push")
request.set_ExpiredSeconds(600)
target = {"userid1024":str(time.time())}
request.set_TargetMsgkey(json.dumps(target))

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

Node.js sample code

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

const { default: Client, PushTemplateRequest } = sdk;
// Create a client.
const client = new Client({
  accessKeyId: 'accessKeyId',
  accessKeySecret: 'accessKeySecret',
  endpoint: 'mpaas.cn-hongkong.aliyuncs.com',
  apiVersion: '2019-08-21'
});
// Initialize the request.
  const request = new PushTemplateRequest();
  request.appId = "ONEX570DA89211721";
  request.workspaceId = "test";
  request.templateName= "template1024";
  const templatekv = {
    name: 'Bob',
    money:'300'
  };
  request.templateKeyValue = JSON.stringify(templatekv);
  request.deliveryType = 3;
  request.taskName = "Node test task";
  request.expiredSeconds=600;
  const extendedParam = {
    test: 'Custom extension parameter'
  };
  request.extendedParams = JSON.stringify(extendedParam);
  const target = {
    "userid1024": String(new Date().valueOf())
  };
  request.targetMsgkey = JSON.stringify(target);

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

PHP sample code

<?php

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

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

    public function templatePush() {
        $request = MPaaS::v20190821()->pushTemplate();
        $result = $request->host("mpaas.cn-hongkong.aliyuncs.com")
            // Specify whether to enable the debug mode.
            ->debug(true)
            ->withAppId("ONEX570DA89211721")
            ->withWorkspaceId("test")
            ->withTemplateName("template1024")
            ->withTemplateKeyValue(json_encode(["name" => "Bob", "money" => "200"]))
            ->withDeliveryType(3)
            ->withTaskName("PHP test task")
            ->withExpiredSeconds(600)
            ->withTargetMsgkey(
                json_encode(["userid1024" => "".time() ])
            )
            ->request();
    }
}

Push message - multiple push

You can call this API to push different messages to different target IDs. This API allows you to create a personalized message for a target ID by replacing the template placeholders. Different from template push, multiple push allows you to send messages of different content to different target IDs.

Before you call the interface, ensure that you have completed the following operations:

  • You have created a template in the MPS console, and the template contains placeholders. Otherwise, you can’t implement personalized message push, that is, push different messages to different target IDs. For more information, see Create a template.

  • You have introduced the required dependencies. For more information, see SDK preparations.

Request parameters

Parameter

Data type

Required

Example

Description

taskName

String

Yes

multipleTest

The name of push task

appId

String

Yes

ONEX570DA89211721

mPaaS App ID

workspaceId

String

Yes

test

mPaaS workspace

deliveryType

Long

Yes

3

The type of target ID. Valid values:

  • 1 - Android device

  • 2 - iOS device

  • 3: User

templateName

String

Yes

testTemplate

Template name. The template can be created in the MPS console.

targetMsgs

List

Yes

targetMsgs object list

The list of TargetMsg objects. | The list of push targets. For information about the parameters of each object, see targetMsgs objects.

expiredSeconds

Long

Yes

300

The validity period of message, in seconds.

extendedParams

String

No

{“key1”:”value1”}

The extension parameters, in the map format.

notifyType

String

No

Message push channel:

  • transparent - MPS self-built channel

  • notify - Default channel

strategyType

int

No

1

Push strategy:

  • 0 – Immediately

  • 1 - Timed

  • 2 - Cyclic

It is 0 by default.

strategyDetail

String

No

Push strategy details (JSON string). This parameter is required when the value of strategyType is not 0. See the following strategyDetail field description for details.

targetMsgs objects

Parameter

Data type

Required

Example

Description

Parameter

Data type

Required

Example

Description

target

String

Yes

userid1024

The target ID, which depends on the value of the deliveryType parameter.

msgKey

String

Yes

1578807462788

The ID of business message. The ID is used for message troubleshooting. The ID is user defined and must be unique.

templateKeyValue

String

No

{“money”:”200”,”name”:”Bob”}

The parameters of template, in the map format. The parameters depend on the template specified by templateName. Key refers to the placeholder while value refers to the specific value that is used to replace the placeholder. For example, the content of a template can be Congratulations to #name# for winning RMB #money#. The string between two number signs “#” is the name of the placeholder.

extendedParams

String

No

{“key1”:”value1”}

The extension parameters, in the map format. Different messages have different extension parameters.

strategyDetail fields

JSON value is converted to String and passed in.

Parameter

Data type

Required

Example

Description

fixedTime

long

No

1630303126000

Scheduled push timestamp (in ms, accurate to second).

When the push strategy is Timed (the value of strategyType is 1), fixedTime is required.

startTime

long

No

1640966400000

Cycle period start timestamp (in ms, accurate to day).

When the push strategy is Cyclic (the value of strategyType is 2), startTime is required.

endTime

long

No

1672416000000

Cycle period end timestamp (in ms, accurate to day). The end time cannot exceed 180 days after the current day.

When the push strategy is Cyclic (the value of strategyType is 2), endTime is required.

circleType

int

No

3

Loop type:

  • 1 - Daily

  • 2 - Weekly

  • 3 - Monthly

When the push strategy is Cyclic (the value of strategyType is 2), circleType is required.

circleValue

int[]

No

[1,3]

Cycle value:

  • If the loop type is daily: Empty

  • If the loop type is weekly: Set the cyclic push time every week. For example, [1,3] means pushing the message every Monday and Wednesday.

  • If the loop type is monthly: Set the cyclic push time every month. For example, [1,3] means pushing the message on the 1st and 3rd day every month.

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

time

String

No

09:45:11

Cyclic push time (time format: HH:mm:ss).

When the push strategy is Cyclic (the value of strategyType is 2), time is required.

Note
  • The upper limit of unexecuted timed or cyclic push tasks is 100 by default.

  • The cycle period is from 00:00 at the start date to 24:00 at the end date.

  • Neither the cycle start time nor the end time can be earlier than 00:00 of the day, and the end time cannot be earlier than the start time.

Return parameters

Parameter

Data type

Example

Description

RequestId

String

B589F4F4-CD68-3CE5-BDA0-6597F33E23916512

Request ID

ResultCode

String

OK

Request result code

ResultMessage

String

param is invalid

Error description

PushResult

JSON

Request result

Success

boolean

true

Request status. The value of Success is contained in the PushRresult JSON string.

ResultMsg

String

param is invalid

Error content. The value of ResultMsg is contained in the PushRresult JSON string.

Data

String

903bf653c1b5442b9ba07684767bf9c2

Scheduled push task ID. When strategyType is not 0 , this field is not empty.

Java sample code

Click here for information about how to obtain the AccessKey ID and AccessKey secret in the following sample code.

 DefaultProfile.addEndpoint("cn-hongkong", "mpaas", "mpaas.cn-hongkong.aliyuncs.com");
        // Create a DefaultAcsClient instance and initialize it
        DefaultProfile profile = DefaultProfile.getProfile(
            "cn-hangzhou",          // Region ID
            "******",      // The AccessKey ID of the RAM account
            "******"); // he AccessKey secret of the RAM account

        IAcsClient client = new DefaultAcsClient(profile);
        // Create an API request and set parameters
        PushMultipleRequest request = new PushMultipleRequest();
        request.setAppId("ONEX570DA89211721");
        request.setWorkspaceId("test");
        request.setDeliveryType(3L);
        request.setTaskName("multipleTest");
        request.setTemplateName("testTemplate");
        // Hello #name#. Congratulations to you for winning RMB #money#.
        List<PushMultipleRequest.TargetMsg> targetMsgs = new ArrayList<PushMultipleRequest.TargetMsg>();
        PushMultipleRequest.TargetMsg targetMsg = new PushMultipleRequest.TargetMsg();
        targetMsg.setTarget("userid1024");
        targetMsg.setMsgKey(String.valueOf(System.currentTimeMillis()));
        Map<String, String> templatekv = new HashMap<String, String>();
        templatekv.put("name", "Bob");
        templatekv.put("money", "200");
        targetMsg.setTemplateKeyValue(JSON.toJSONString(templatekv));
        // The number of TargetMsg objects can be up to 400
        targetMsgs.add(targetMsg);
        request.setTargetMsgs(targetMsgs);
        request.setExpiredSeconds(600L);

        request.setStrategyType(2);
        request.setStrategyContent("{\"fixedTime\":1630303126000,\"startTime\":1625673600000,\"endTime\":1630303126000,\"circleType\":1,\"circleValue\":[1, 7],\"time\":\"13:45:11\"}");

        PushMultipleResponse response;
        try {
            response = client.getAcsResponse(request);
            System.out.println(response.getResultCode());
            System.out.println(response.getResultMessage());
            System.out.println(response.getPushResult().getData());  // Push task ID or scheduled push task ID
        } catch (ClientException e) {
            e.printStackTrace();
        }

Python sample code

# -*- coding: utf8 -*-
from aliyunsdkcore.client import AcsClient
from aliyunsdkmpaas.request.v20190821 import PushMultipleRequest
import json
import time

# Initialize AcsClient instance
client = AcsClient(
  "AccessKey ID",
  "AccessKey Secret",
  "cn-hongkong"
);

# Initialize a request and set parameters
request = PushMultipleRequest.PushMultipleRequest()
request.set_endpoint("mpaas.cn-hongkong.aliyuncs.com")
request.set_AppId("ONEX570DA89211721")
request.set_WorkspaceId("test")
request.set_TemplateName("template1024")
request.set_DeliveryType(3)
request.set_TaskName("The test task of Python template push")
request.set_ExpiredSeconds(600)
msgkey = str(time.time())
targets = [
  {
    "Target": "user1024",
    "MsgKey": msgkey,
    "TemplateKeyValue": {
      "name": "Bob",
      "money": "200"
    }
  }
]
request.set_TargetMsgs(targets)
# Print response
response = client.do_action_with_exception(request)
print response

Node.js sample code

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

const { default: Client, PushMultipleRequest,PushMultipleRequestTargetMsg } = sdk;
// Create a client
const client = new Client({
  accessKeyId: 'accessKeyId',
  accessKeySecret: 'AccessKey Secret',
  endpoint: 'mpaas.cn-hongkong.aliyuncs.com',
  apiVersion: '2019-08-21'
});
// Initialize request
  const request = new PushMultipleRequest();
  request.appId = "ONEX570DA89211721";
  request.workspaceId = "test";
  request.templateName= "template1024";
  const templatekv = {
    name: 'Bob',
    money:'300'
  };
  //request.templateKeyValue = JSON.stringify(templatekv);

  request.deliveryType = 3;
  request.taskName = "Node test task";
  request.expiredSeconds=600;
  const extendedParam = {
    test: 'Custom extension 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 the API operation.
try {
  client.pushMultiple(request).then(res => {
    console.log('SUCCESS', res);
  }).catch(e => {
    console.log('FAIL', e);
  });
} catch(e) {
  console.log('ERROR', e);
}

PHP sample code

<?php

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

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


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

Push message - broadcast push

You can call this interface to push the same message to all devices. The message is created based on a template.

Before you call the interface, ensure that you have completed the following operations:

  • You have created a template in the MPS console, and the template contains placeholders. Otherwise, you cann’t implement personalized message push, that is, push different messages to different target IDs. For more information, see Create a template.

  • You have introduced the required dependencies. For more information, see SDK preparations.

Request parameters

Parameter

Data type

Required

Example

Description

taskName

String

Yes

broadcastTest

The name of push task

appId

String

Yes

ONEX570DA89211721

mPaaS App ID

workspaceId

String

Yes

test

mPaaS workspace

deliveryType

Long

Yes

1

The type of target ID. Valid values:

  • 1 - Android broadcast

  • 2 - iOS broadcast

msgkey

String

Yes

1578807462788

The ID of business message. The ID is used for message troubleshooting. The ID is user defined and must be unique.

expiredSeconds

Long

Yes

300

The validity period of message, in seconds.

templateName

String

Yes

broadcastTemplate

Template name. The template can be created in the MPS console.

templateKeyValue

String

No

{“content”:”Announcement”}

The parameters of template, in the map format. The parameters depend on the template specified by templateName. Key refers to the placeholder while value refers to the specific value that is used to replace the placeholder.

pushStatus

Long

No

0

Login status:

  • 0 - Login users (default)

  • 1 - All users (including login and logout users)

  • 2 - Logout users

bindPeriod

int

No

Login period, required when the value of pushStatus is 0:

  • 1 - Login users in recent 7 days

  • 2 - Login users in recent 15 days

  • 3 - Login users in recent 60 days

  • 4 - Permanent

Note

The bindPeriod parameter is only configurable in non-financial environment.

unBindPeriod

Long

No

Logout period, required when the value of pushStatus is 1 or 2:

  • 1 - Logout users in recent 7 days

  • 2 - Logout users in recent 15 days

  • 3 - Logout users in recent 60 days

  • 4 - Permanent

androidChannel

Integer

No

Android message channel:

  • transparent - MPS self-built channel

  • notify - Default channel

strategyType

int

No

1

Push strategy:

  • 0 - Immediately

  • 1 - Timed

  • 2 - Cyclic

It is 0 by default.

strategyDetail

String

No

Push strategy details (JSON string). This parameter is required when the value of strategyType is not 0. See the following strategyDetail field description for details.

strategyDetail fields

JSON value is converted to String and passed in.

Parameter

Data type

Required

Example

Description

fixedTime

long

No

1630303126000

Scheduled push timestamp (in ms, accurate to second).

When the push strategy is Timed (the value of strategyType is 1), fixedTime is required.

startTime

long

No

1640966400000

Cycle period start timestamp (in ms, accurate to day).

When the push strategy is Cyclic (the value of strategyType is 2), startTime is required.

endTime

long

No

1672416000000

Cycle period end timestamp (in ms, accurate to day). The end time cannot exceed 180 days after the current day.

When the push strategy is Cyclic (the value of strategyType is 2), endTime is required.

circleType

int

No

3

Loop type:

  • 1 - Daily

  • 2 - Weekly

  • 3 - Monthly

When the push strategy is Cyclic (the value of strategyType is 2), circleType is required.

circleValue

int[]

No

[1,3]

Cycle value:

  • If the loop type is daily: Empty

  • If the loop type is weekly: Set the cyclic push time every week. For example, [1,3] means pushing the message every Monday and Wednesday.

  • If the loop type is monthly: Set the cyclic push time every month. For example, [1,3] means pushing the message on the 1st and 3rd day every month.

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

time

String

No

09:45:11

Cyclic push time (time format: HH:mm:ss).

When the push strategy is Cyclic (the value of strategyType is 2), time is required.

Note
  • The upper limit of unexecuted timed or cyclic push tasks is 100 by default.

  • The cycle period is from 00:00 at the start date to 24:00 at the end date.

  • Neither the cycle start time nor the end time can be earlier than 00:00 of the day, and the end time cannot be earlier than the start time.

Return parameters

Parameter

Data type

Example

Description

RequestId

String

B589F4F4-CD68-3CE5-BDA0-6597F33E23916512

Request ID

ResultCode

String

OK

Request result code

ResultMessage

String

param is invalid

Error description

PushResult

JSON

Request result

Success

boolean

true

Request status. The value of Success is contained in the PushRresult JSON string.

ResultMsg

String

param is invalid

Error content. The value of ResultMsg is contained in the PushRresult JSON string.

Data

String

903bf653c1b5442b9ba07684767bf9c2

Scheduled push task ID. When strategyType is not 0 , this field is not empty.

Java sample code

Click here for information about how to obtain the AccessKey ID and AccessKey secret in the following sample code.

DefaultProfile.addEndpoint("cn-hongkong", "mpaas", "mpaas.cn-hongkong.aliyuncs.com");
        // Create a DefaultAcsClient instance and initialize it
        DefaultProfile profile = DefaultProfile.getProfile(
            "cn-hangzhou",          // Region ID
            "******",      // The AccessKey ID of the RAM account
            "******"); // The AccessKey Secret of the RAM account

        IAcsClient client = new DefaultAcsClient(profile);

        PushBroadcastRequest request = new PushBroadcastRequest();
        request.setAppId("ONEX570DA89211720");
        request.setWorkspaceId("test");
        request.setDeliveryType(2L);
        request.setMsgkey(String.valueOf(System.currentTimeMillis()));
        request.setExpiredSeconds(600L);
        request.setTaskName("broadcastTest ");
        request.setTemplateName("broadcastTemplate ");
        // This is an announcement: #content#.
        Map<String, String> templatekv = new HashMap<String, String>();
        templatekv.put("content", " The content of the announcement ");
        request.setTemplateKeyValue(JSON.toJSONString(templatekv));

        request.setStrategyType(2);
        request.setStrategyContent("{\"fixedTime\":1630303126000,\"startTime\":1625673600000,\"endTime\":1630303126000,\"circleType\":1,\"circleValue\":[1, 7],\"time\":\"13:45:11\"}");    

        PushBroadcastResponse response;
        try {
            response = client.getAcsResponse(request);
            System.out.println(response.getResultCode());
            System.out.println(response.getResultMessage());
            System.out.println(response.getPushResult().getData());  // push task ID or scheduled task ID
        } catch (ClientException e) {
            e.printStackTrace();
        }

Python sample code

# -*- coding: utf8 -*-

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

# Initialize AcsClient instance
client = AcsClient(
  "AccessKey ID",
  "AccessKey Secret",
  "cn-hongkong"
);

# Initialize a request and set parameters
request = PushBroadcastRequest.PushBroadcastRequest()
request.set_endpoint("mpaas.cn-hongkong.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("The test task of Python broadcast push")
request.set_ExpiredSeconds(600)
request.set_Msgkey(str(time.time()))

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

Node.js sample code

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

const { default: Client, PushBroadcastRequest } = sdk;
// Create a client.
const client = new Client({
  accessKeyId: 'accessKeyId',
  accessKeySecret: 'AccessKey Secret',
  endpoint: 'mpaas.cn-hongkong.aliyuncs.com',
  apiVersion: '2019-08-21'
});
// Initialize the 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 test task";
  request.expiredSeconds=600;
  const extendedParam = {
    test: 'Custom extension parameter'
  };
  request.extendedParams = JSON.stringify(extendedParam);

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

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

PHP sample code

<?php

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

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


   public function broadcastPush(){
        $request = MPaaS::v20190821()->pushBroadcast();
        $result = $request->host("mpaas.cn-hongkong.aliyuncs.com")
            // Specify 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("The test task of PHP broadcast push")
            ->withExpiredSeconds(600)
            ->withMsgkey("". time())
            ->request();
    }
}

Revoke messages

Messages pushed through simple push or template push can be withdrawn through message ID; messages pushed through the multiple push or broadcast push can be withdrawn through task ID. Only the messages pushed in recent 7 days can be revoked.

Revoke by message ID

Revoke the messages pushed through simple push mode or template push mode.

Request parameters

Parameter

Data type

Required

Example

Description

messageId

String

Yes

1578807462788

Message ID in business system, which can be customiezed by users and is used to uniquely identify the message in the business system.

targetId

String

Yes

user1024

Target ID. If the message was pushed by device, then the target ID refers to device ID; if the message was pushed by user, then the target ID refers to user ID.

Return parameters

Parameter

Data type

Example

Description

RequestId

String

B589F4F4-CD68-3CE5-BDA0-6597F33E23916512

Request ID

ResultCode

String

OK

Request result code

ResultMessage

String

param is invalid

Error description

PushResult

JSON

Request result

Success

boolean

true

Request status. The value of Success is contained in the PushRresult JSON string.

ResultMsg

String

param is invalid

Error content. The value of ResultMsg is contained in the PushRresult JSON string.

Sample code

DefaultProfile.addEndpoint("cn-hongkong", "mpaas", "mpaas.cn-hongkong.aliyuncs.com");
        // Create a DefaultAcsClient instance and initialize it
        DefaultProfile profile = DefaultProfile.getProfile(
            "cn-hangzhou",          // Region ID
            "******",      // The AccessKey ID of the RAM account
            "******"); // The AccessKey Secret of the RAM account

        IAcsClient client = new DefaultAcsClient(profile);        

        RevokePushMessageRequest request = new RevokePushMessageRequest();
        request.setAppId("ONEX570DA89211720");
        request.setWorkspaceId("test");
        request.setMessageId("console_1624516744112");  // Message ID in business system
        request.setTargetId("mpaas_push_demo");         // Target ID

        RevokePushMessageResponse response;
        try {
            response = client.getAcsResponse(request);
            System.out.println(response.getResultCode());
            System.out.println(response.getResultMessage());
        } catch (ClientException e) {
            e.printStackTrace();
        }

Revoke by task ID

Revoke the messages pushed through multiple push mode or broadcast push mode.

Request parameters

Parameter

Data type

Required

Example

Example

taskId

String

Yes

20842863

Push task ID, which can be used to query push tasks in the MPS console.

Return parameters

Parameter

Data type

Example

Description

RequestId

String

B589F4F4-CD68-3CE5-BDA0-6597F33E23916512

Request ID

ResultCode

String

OK

Request result code

ResultMessage

String

param is invalid

Error description

PushResult

JSON

Request result

Success

boolean

true

Request status. The value of Success is contained in the PushRresult JSON string.

ResultMsg

String

param is invalid

Error content. The value of ResultMsg is contained in the PushRresult JSON string.

Sample code

DefaultProfile.addEndpoint("cn-hongkong", "mpaas", "mpaas.cn-hongkong.aliyuncs.com");
        // Create a DefaultAcsClient instance and initialize it
        DefaultProfile profile = DefaultProfile.getProfile(
            "cn-hangzhou",          // Region ID
            "******",      // The AccessKey ID of the RAM account
            "******"); // The AccessKey Secret of the RAM account

        IAcsClient client = new DefaultAcsClient(profile);

        RevokePushTaskRequest request = new RevokePushTaskRequest();
        request.setAppId("ONEX570DA89211720");
        request.setWorkspaceId("test");
        request.setTaskId("20842863");     // Push task ID

        RevokePushTaskResponse response;
        try {
            response = client.getAcsResponse(request);
            System.out.println(response.getResultCode());
            System.out.println(response.getResultMessage());
        } catch (ClientException e) {
            e.printStackTrace();
        }

Analyze message push

Query statistical data

Query message push statistical data, including pushed messages, successfully pushed messages, message arrivals, opened messages, and ignored messages.

Request parameters

Parameter

Data type

Required

Example

Description

appId

String

Yes

ONEX570DA89211721

mPaaS App ID

workspaceId

String

Yes

test

mPaaS workspace

startTime

long

Yes

1619798400000

The start timestamp of the time period to be queried, in millisenconds and accurate to day.

endTime

long

Yes

1624358433000

The end timestamp of the time period to be queried, in millisenconds and accureate to day. The interval between the start time and end time cannot exceed 90 days.

platform

String

No

ANDROID

Push platform. It defaults to query all platforms if no value is passed in.

Valid values: IOS, ANDROID

channel

String

No

ANDROID

Push channel. It defaults to query all channels if no value is passed in.

Valid values: IOS, FCM, HMS, MIUI, OPPO, VIVO, ANDROID (self-build channel)

type

String

No

SIMPLE

Push mode. It defaults to query all types if no value is passed in.

Valid values: SIMPLE, TEMPLATE, MULTIPLE, BROADCAST

taskId

String

No

20842863

Push task ID

Return parameters

Parameter

Data type

Example

Description

RequestId

String

B589F4F4-CD68-3CE5-BDA0-6597F33E23916512

Request ID

ResultCode

String

OK

Request result code

ResultMessage

String

param is invalid

Error description

ResultContent

JSON

Response content

data

JSON

Response content. The value of data is contained in the ResultContent JSON string.

pushTotalNum

float

100

The number of pushed messages

pushNum

float

100

The number of successfully pushed messages

arrivalNum

float

100

The number of messages that arrive client

openNum

float

100

The number of opened messages

openRate

float

100

Message open rate

ignoreNum

float

100

The number of ignored messages

ignoreRate

float

100

Message ignorance rate

Sample code

DefaultProfile.addEndpoint("cn-hongkong", "mpaas", "mpaas.cn-hongkong.aliyuncs.com");
        // Create a DefaultAcsClient instance and initialize it
        DefaultProfile profile = DefaultProfile.getProfile(
            "cn-hangzhou",          // Region ID
            "******",      // The AccessKey ID of the RAM account
            "******"); // The AccessKey Secret of the RAM account
        IAcsClient client = new DefaultAcsClient(profile);
        QueryPushAnalysisCoreIndexRequest request = new QueryPushAnalysisCoreIndexRequest();
        request.setAppId("ONEX570DA89211720");
        request.setWorkspaceId("test");
        request.setStartTime(Long.valueOf("1617206400000"));
        request.setEndTime(Long.valueOf("1624982400000"));
        request.setPlatform("ANDROID");
        request.setChannel("ANDROID");
        request.setType("SIMPLE");
        request.setTaskId("20842863");

        QueryPushAnalysisCoreIndexResponse response;
        try {
            response = client.getAcsResponse(request);
            System.out.println(response.getResultCode());
            System.out.println(response.getResultMessage());
        } catch (ClientException e) {
            e.printStackTrace();
        }

Query push tasks

Query the multiple/broadcast push tasks created on MPS console or triggered by calling API.

Request parameters

Parameter

Data type

Required

Example

Description

appId

String

Yes

ONEX570DA89211721

mPaaS App ID

workspaceId

String

Yes

test

mPaaS workspace

startTime

long

Yes

1619798400000

The start timestamp of the time period to be queried, in milliseconds and accurate to day.

taskId

String

No

20842863

Push task ID

taskName

String

No

Test task

Task name

pageNumber

int

No

1

Page number, 1 by default.

pageSize

int

No

10

The total number of pages, 500 by default.

Return parameters

Parameter

Data type

Example

Description

RequestId

String

B589F4F4-CD68-3CE5-BDA0-6597F33E23916512

Request ID

ResultCode

String

OK

Request result code

ResultMessage

String

param is invalid

Error description

ResultContent

JSON

Response content

data

JSON

Response content. The value of data is contained in the ResultContent JSON string.

taskId

String

20927873

Task ID

taskName

String

Test task

Task name

templateId

String

9108

Template ID

templateName

String

Test template

Template name

type

long

3

Push mode:

  • 2 – Multiple push

  • 3 – Broadcast push

gmtCreate

long

1630052750000

Creation time

Sample code

DefaultProfile.addEndpoint("cn-hongkong", "mpaas", "mpaas.cn-hongkong.aliyuncs.com");
        // Create a DefaultAcsClient instance and initialize it
        DefaultProfile profile = DefaultProfile.getProfile(
            "cn-hangzhou",          // Region ID
            "******",      // The AccessKey ID of the RAM account
            "******"); // The AccessKey Secret of the RAM account
        IAcsClient client = new DefaultAcsClient(profile);

        QueryPushAnalysisTaskListRequest request = new QueryPushAnalysisTaskListRequest();
        request.setAppId("ONEX570DA89211721");
        request.setWorkspaceId("default");
        request.setStartTime(Long.valueOf("1617206400000"));
        request.setTaskId("20845212");
        request.setTaskName("Tesk task");
        request.setPageNumber(1);
        request.setPageSize(10);

        QueryPushAnalysisTaskListResponse response;
        try {
            response = client.getAcsResponse(request);
            System.out.println(response.getResultCode());
            System.out.println(response.getResultMessage());
        } catch (ClientException e) {
            e.printStackTrace();
        }

Query push task details

Query the details of multiple/broadcast push tasks created on MPS console or triggered by calling API.

Request parameters

Parameter

Data type

Required

Example

Description

appId

String

Yes

ONEX570DA89211721

mPaaS App ID

workspaceId

String

Yes

test

mPaaS workspace

taskId

String

Yes

20842863

Push task ID

Return parameters

Parameter

Data type

Example

Description

RequestId

String

B589F4F4-CD68-3CE5-BDA0-6597F33E23916512

Request ID

ResultCode

String

OK

Request result code

ResultMessage

String

param is invalid

Error description

ResultContent

JSON

Response content

data

JSON

Response content. The value of data is contained in the ResultContent JSON string.

taskId

long

20927872

Task ID

pushNum

float

10

The number of pushed messages

pushSuccessNum

float

10

The number of successfully pushed messages

pushArrivalNum

float

10

The number of messages that arrive client

startTime

long

1630052735000

Start time (ms)

endTime

long

1630052831000

End time (ms)

duration

string

00 hour 01 minute 36 seconds

Push duration

Sample code

DefaultProfile.addEndpoint("cn-hongkong", "mpaas", "mpaas.cn-hongkong.aliyuncs.com");
        // Create a DefaultAcsClient instance and initialize it
        DefaultProfile profile = DefaultProfile.getProfile(
            "cn-hangzhou",          // Region ID
            "******",      // The AccessKey ID of the RAM account
            "******"); // The AccessKey Secret of the RAM account
        IAcsClient client = new DefaultAcsClient(profile);

        QueryPushAnalysisTaskDetailRequest request = new QueryPushAnalysisTaskDetailRequest();
        request.setAppId("ONEXPREF4F5C52081557");
        request.setWorkspaceId("default");
        request.setTaskId("20845212");

        QueryPushAnalysisTaskDetailResponse response;
        try {
            response = client.getAcsResponse(request);
            System.out.println(response.getResultCode());
            System.out.println(response.getResultMessage());
        } catch (ClientException e) {
            e.printStackTrace();
        }

Manage scheduled push tasks

Query scheduled push tasks

Query the created scheduled push tasks, including timed and cyclic push tasks.

Request parameters

Parameter

Data type

Required

Example

Description

appId

String

Yes

ONEX570DA89211721

mPaaS App ID

workspaceId

String

Yes

test

mPaaS workspace

startTime

long

Yes

1619798400000

The start timestamp when the scheduled push is triggered, not the task creation time.

endtTime

long

Yes

1630425600000

The end timestamp when the scheduled push is triggered.

type

int

No

0

Push mode:

  • 0 - Simple push

  • 1 – Template push

  • 2 – Multiple push

  • 3 – Broadcast push

uniqueId

String

No

49ec0ed5a2a642bcbe139a2d7a419d6d

The unique ID of the scheduled push task.

If you pass the master task ID, then the information of all sub tasks will be returned. If you pass the sub task ID, then the corresponding sub task information will be returned.

pageNumber

int

No

1

Page number, 1 by default.

pageSize

int

No

10

The total number of pages, 500 by default.

Return parameters

Parameter

Data type

Example

Description

RequestId

String

B589F4F4-CD68-3CE5-BDA0-6597F33E23916512

Request ID

ResultCode

String

OK

Request result code

ResultMessage

String

param is invalid

Error description

ResultContent

JSON

Response content

data

JSON

Response content. The value of data is contained in the ResultContent JSON string.

totalCount

int

10

Total amount

list

JSONArray

Task array

uniqueId

String

56918166720e46e1bcc40195c9ca71db

Unique ID of the scheduled push task.

  • If the value of strategyType is 1, it refers to the master task ID of timed task.

  • If the value of strategyType is 2, it refers to the child task ID of cyclic task.

parentId

String

56918166720e46e1bcc40195c9ca71db

Master ID of the scheduled push task.

  • If the value of strategyType is 1, it refers to the master task ID of timed task.

  • If the value of strategyType is 2, it refers to the master task ID of cyclic task.

pushTime

Date

1630486972000

Scheduled push time

pushTitle

String

Test

Title of message

pushContent

String

Test text

Body content of message

type

int

0

Push mode:

  • 0 - Simple push

  • 1 – Template push

  • 2 – Multiple push

  • 3 – Broadcast push

deliveryType

int

1

Push type:

  • 1 - Android

  • 2 - iOS

  • 3 - UserId

strategyType

int

1

Push strategy:

  • 1 - Timed

  • 2 - Cyclic

executedStatus

int

0

Whether the task has been executed:

  • 0 - No executed

  • 1 - Executed

createType

int

0

Task creation method:

  • 0 - API

  • 1 - Console

gmtCreate

Date

1629971346000

Creation time

Sample code

DefaultProfile.addEndpoint("cn-hongkong", "mpaas", "mpaas.cn-hongkong.aliyuncs.com");
        // Create a DefaultAcsClient instance and initialize it
        DefaultProfile profile = DefaultProfile.getProfile(
            "cn-hangzhou",          // Region ID
            "******",      // The AccessKey ID of the RAM account
            "******"); // The AccessKey Secret of the RAM account
        IAcsClient client = new DefaultAcsClient(profile);

        QueryPushSchedulerListRequest request = new QueryPushSchedulerListRequest();
        request.setAppId("ONEXPREF4F5C52081557");
        request.setWorkspaceId("default");
        request.setStartTime(Long.valueOf("1625068800000"));
        request.setEndTime(Long.valueOf("1630425600000"));
        request.setType(0);
        request.setUniqueId("49ec0ed5a2a642bcbe139a2d7a419d6d");
        request.setPageNumber(1);
        request.setPageSize(10);

        QueryPushSchedulerListResponse response;
        try {
            response = client.getAcsResponse(request);
            System.out.println(response.getResultCode());
            System.out.println(response.getResultMessage());
        } catch (ClientException e) {
            e.printStackTrace();
        }

Cancel scheduled push tasks

Cancel the scheduled push tasks (including cyclic push tasks) that haven’t been pushed. You can cancel the tasks in batch.

Request parameters

Parameter

Data type

Required

Example

Description

appId

String

Yes

ONEX570DA89211721

mPaaS App ID

workspaceId

String

Yes

test

mPaaS workspace

type

int

No

0

Scheduled push task ID type. It is 0 by default.

0 - Master task ID, corresponding to parentId

1 – Sub task ID, corresponding to uniqueId

uniqueIds

String

Yes

714613eb,714613ec,714613ed

The unique ID of the scheduled push task. Multiple task IDs are separated with commas (,). You can input 30 IDs at most.

Return parameters

Parameter

Data type

Example

Description

RequestId

String

B589F4F4-CD68-3CE5-BDA0-6597F33E23916512

Request ID

ResultCode

String

OK

Request result code

ResultMessage

String

param is invalid

Error description

ResultContent

String

{714613eb=1,714613ed=0}

Cancellation result:

  • 1 - Successful

  • 0 - Failed

Sample code

DefaultProfile.addEndpoint("cn-hongkong", "mpaas", "mpaas.cn-hongkong.aliyuncs.com");
        // Create a DefaultAcsClient instance and initialize it
        DefaultProfile profile = DefaultProfile.getProfile(
            "cn-hangzhou",          // Region ID
            "******",      // The AccessKey ID of the RAM account
            "******"); // The AccessKey Secret of the RAM account
        IAcsClient client = new DefaultAcsClient(profile);

CancelPushSchedulerRequest request = new CancelPushSchedulerRequest();
        request.setAppId("ONEXPREF4F5C52081557");
        request.setWorkspaceId("default");
        request.setUniqueIds("49ec0ed5a2a642bcbe139a2d7a419d6d, 49ec0ed5a2a642bcbe139a2d7a419d6c");

        CancelPushSchedulerResponse response;
        try {
            response = client.getAcsResponse(request);
            System.out.println(response.getResultCode());
            System.out.println(response.getResultMessage());
        } catch (ClientException e) {
            e.printStackTrace();
        }

Extension parameters

Extension parameters are passed to the client with message body. You can define or process these parameters.

Extension parameters include the following three types:

  • System extension parameters

    These extension parameters are occupied by the system. Do not modify the values of these parameters. System extension parameters include notifyType, action, silent, pushType, templateCode, channel, and taskId.

  • System extension parameters with some significance

    Extension parameters of this type are occupied by the system. Each parameter has a specific meaning. You can set the values of these extension parameters. The following table describes the extension parameters with specific meanings:

    Key

    Description

    sound

    The custom ringtone of the message. The value of this parameter is the path of the ringtone. This parameter only applies to Xiaomi phones and iPhones.

    badge

    The badge of the App icon. Its value is a specific number. This extension parameter will be passed to the client together with the message body.

    • For Android devices, you need to implement the badge logic by yourself.

    • For iOS devices, the system automatically implements the badge logic. When a message is pushed to the target mobile phone, the number that you specified in value appears in the badge of the App icon.

    mutable-content

    Custom push ID of Apple Push Notification service (APNs). A push notification carrying this parameter indicates the support of iOS 10 UNNotificationServiceExtension. If the push notification not carrying this parameter indicates a common push. Set the value to 1.

    badge_add_num

    Number of added push badges for Huawei push channel.

    badge_class

    Activity class corresponding to the desktop icon for Huawei push channel

    big_text

    Big text style. This parameter has a fixed value “1”. Any other value is invalid. This parameter is only valid for Xiaomi and Huawei devices.

  • User-defined extension parameters

    All the parameters other than the preceding system extension parameters are user-defined extension parameters. User-defined extension parameters are passed to the client together with a message body. You can define and process these parameters.

Result codes

Result code

Message

Description

100

SUCCESS

Succeeded

-1

SIGNATURE_MISMATCH

Signature mismatched.

3001

NEED_DELIVERYTOKEN

deliveryToken is empty.

3002

NEED_FILE

The file is empty.

3003

NEED_APPID_WORKSPACEID

The App ID or workspace is empty.

3007

APPID_WRONG

Invalid App ID or workspace.

3008

OS_TYPE_NOT_SUPPORTED

Push platform not supported.

3009

DELIVERY_TYPE_NOT_SUPPORTED

deliveryType not supported.

3012

NEED_USERID

UserId is empty.

3019

TASKNAME_NULL

Task name is empty.

3020

EXPIREDSECONDS_WRONG

Illegal message timeout length.

3021

TOKEN_OR_USERID_NULL

Target is empty.

3022

TEMPLATE_NOT_EXIST

Template doesn’t exist.

3023

TEMPLATEKV_NOT_ENOUGH

Template parameter mismatched.

3024

PAYLOAD_NOT_ENOUGH

Title or content is empty.

3025

NEED_TEMPLATE

Template is empty.

3026

EXPIREDTIME_TOO_LONG

The validity period of message is too long.

3028

INVALID_PARAM

Illegal parameter.

3029

SINGLE_PUSH_TARGET_TOO_MUCH

Too many targets.

3030

BROADCAST_ONLY_SUPPORT_BY_DEVICE

Only broadcast push by device is supported.

3031

REQUEST_SHOULD_BE_UTF8

The request body must be UTF-8 encoded.

3032

REST_API_SWITCH_NOT_OPEN

The push API has been closed.

3033

UNKNOWN_REST_SIGN_TYPE

Signature type not supported.

3035

EXTEND_PARAM_TO_MUCH

Too many extension parameters. A maximum of 20 extension parameters are allowed.

3036

TEMPLATE_ALREADY_EXIST

The template already exists.

3037

TEMPLATE_NAME_NULL

Template name is empty.

3038

TEMPLATE_NAME_INVALID

Illegal template name.

3039

TEMPLATE_CONTENT_INVALID

Illegal template content.

3040

TEMPLATE_TITLE_INVALID

Illegal template title.

3041

TEMPLATE_DESC_INFO_INVALID

Illegal template description.

3042

TEMPLATE_URI_INVALID

Illegal template URI.

3043

SINGLE_PUSH_CONTENT_TOO_LONG

Message body is too long.

3044

INVALID_EXTEND_PARAM

Illegal extension parameter.

3049

MULTIPLE_INNER_EXTEND_PARAM_TO_MUCH

The number of internal extension parameters for multiple push cannot exceed 10.

3050

MSG_PAYLOAD_TOO_LONG

Message body is too long.

3051

BROADCAST_ALL_USER_NEED_UNBIND_PERIOD

Unbinding parameters are required for the broadcast push targeting at all users (including both login and logout users).

3052

BROADCAST_ALL_USER_UNBIND_PERIOD_INVALID

Illegal unbinding parameters for broadcast push.

3053

BROADCAST_ALL_USER_NOT_SUPPORT_SELFCHANNEL_ANDROID

MPS self-built push channel doesn’t supports the broadcast push targeting at all users (including both login and logout users).

3054

DELIVERYTOKEN_INVALID

Illegal MPS self-built channel token.

3055

MULTIPLE_TARGET_NUMBER_TOO_MUCH

The number of push targets exceeds the threshold.

3056

TEMPLATE_NUM_TOO_MUCH

The number of message templates exceeds the threshold.

3057

ANDROID_CHANNEL_PARAM_INVALID

Invalid androidChannel.

3058

BADGE_ADD_NUM_INVALID

Invalid badge_add_num.

3059

BADGE_ADD_NUM_NEED_BADGE_CLASS

The parameter badge_class is required for badge_add_num.

9000

SYSTEM_ERROR

System error.