All Products
Search
Document Center

Server API

Last Updated: Sep 16, 2021

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:

 
  1. <dependency>
  2. <groupId>com.aliyun</groupId>
  3. <artifactId>aliyun-java-sdk-mpaas</artifactId>
  4. <version>3.0.6</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>com.aliyun</groupId>
  8. <artifactId>aliyun-java-sdk-core</artifactId>
  9. <optional>true</optional>
  10. <version>[4.3.2,5.0.0)</version>
  11. </dependency>

Python

Run the following commands to add relevant dependencies.

 
  1. ## Aliyun SDK
  2. pip install aliyun-python-sdk-core
  3. ## mPaaSs SDK
  4. pip install aliyun-python-sdk-mpaas

Node.js

Run the following commands to add relevant dependencies.

 
  1. npm i @alicloud/mpaas20190821

PHP

Run the following commands to add relevant dependencies.

 
  1. 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 {\”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\"} 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 {\”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\"} 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 {\”fixedTime\”:1630303126000,\”startTime\”:1625673600000,\”endTime\”:1630303126000,\”circleType\”:1,\”circleValue\”:[1, 7],\”time\”:\”13:45:11\”} 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.

 
  1. DefaultProfile.addEndpoint("cn-hongkong", "mpaas", "mpaas.cn-hongkong.aliyuncs.com");
  2. // Create a DefaultAcsClient instance and initialize it
  3. DefaultProfile profile = DefaultProfile.getProfile(
  4. "cn-hangzhou", // Region ID
  5. "******", // The AccessKey ID of the RAM account
  6. "*****"); // The AccessKey secret of the RAM account
  7. IAcsClient client = new DefaultAcsClient(profile);
  8. // Create an API request and set parameters
  9. PushSimpleRequest request = new PushSimpleRequest();
  10. request.setAppId("ONEX570DA89211721");
  11. request.setWorkspaceId("test");
  12. request.setTaskName("Test task");
  13. request.setTitle("Test");
  14. request.setContent("Test");
  15. request.setDeliveryType(3L);
  16. Map<String,String> extendedParam = new HashMap<String, String>();
  17. extendedParam.put("key1","value1");
  18. request.setExtendedParams(JSON.toJSONString(extendedParam));
  19. request.setExpiredSeconds(300L);
  20. request.setPushStyle(2);
  21. 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\"}";
  22. 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\"}";
  23. request.setImageUrls(imageUrls);
  24. request.setIconUrls(iconUrls);
  25. request.setStrategyType(2);
  26. request.setStrategyContent("{\"fixedTime\":1630303126000,\"startTime\":1625673600000,\"endTime\":1630303126000,\"circleType\":1,\"circleValue\":[1, 7],\"time\":\"13:45:11\"}");
  27. Map<String,String> target = new HashMap<String, String>();
  28. String msgKey = String.valueOf(System.currentTimeMillis());
  29. target.put("user1024",msgKey);
  30. request.setTargetMsgkey(JSON.toJSONString(target));
  31. // Initiate the request and handle the response or exceptions
  32. PushSimpleResponse response;
  33. try {
  34. response = client.getAcsResponse(request);
  35. System.out.println(response.getResultCode());
  36. System.out.println(response.getResultMessage());
  37. } catch (ClientException e) {
  38. e.printStackTrace();
  39. }

Python sample code

 
  1. from aliyunsdkcore.client import AcsClient
  2. from aliyunsdkmpaas.request.v20190821 import PushSimpleRequest
  3. import json
  4. # Initialize AcsClient instance
  5. client = AcsClient(
  6. "***",
  7. "***",
  8. "cn-hongkong"
  9. );
  10. # Initialize a request and set parameters
  11. request = PushSimpleRequest.PushSimpleRequest()
  12. request.set_endpoint("mpaas.cn-hongkong.aliyuncs.com")
  13. request.set_AppId("ONEX570DA89211721")
  14. request.set_WorkspaceId("test")
  15. request.set_Title( "Python test")
  16. request.set_Content( "Test 2")
  17. request.set_DeliveryType(3)
  18. request.set_TaskName("The test task of Python template push")
  19. request.set_ExpiredSeconds(600)
  20. target = {"user1024":str(time.time())}
  21. request.set_TargetMsgkey(json.dumps(target))
  22. # Print response
  23. response = client.do_action_with_exception(request)
  24. print response

Node.js sample code

 
  1. const sdk = require('@alicloud/mpaas20190821');
  2. const { default: Client, PushSimpleRequest } = sdk;
  3. // Create a client
  4. const client = new Client({
  5. accessKeyId: '****',
  6. accessKeySecret: '*****',
  7. endpoint: 'mpaas.cn-hongkong.aliyuncs.com',
  8. apiVersion: '2019-08-21'
  9. });
  10. // Initialize the request.
  11. const request = new PushSimpleRequest();
  12. request.appId = "ONEX570DA89211721";
  13. request.workspaceId = "test";
  14. request.title = "Node test";
  15. request.content = "Test";
  16. request.deliveryType = 3;
  17. request.taskName = "Node test task";
  18. request.expiredSeconds=600;
  19. const extendedParam = {
  20. test: 'Custom extension parameter'
  21. };
  22. request.extendedParams = JSON.stringify(extendedParam);
  23. // The value is the ID of the business message. Make sure that the ID is unique.
  24. const target = {
  25. "userid1024": String(new Date().valueOf())
  26. };
  27. request.targetMsgkey = JSON.stringify(target);
  28. // Call the API operation.
  29. try {
  30. client.pushSimple(request).then(res => {
  31. console.log('SUCCESS', res);
  32. }).catch(e => {
  33. console.log('FAIL', e);
  34. });
  35. } catch(e) {
  36. console.log('ERROR', e);
  37. }

PHP sample code

 
  1. <?php
  2. use AlibabaCloud\Client\AlibabaCloud;
  3. use AlibabaCloud\MPaaS\MPaaS;
  4. AlibabaCloud::accessKeyClient('accessKeyId', 'accessKeySecret')
  5. ->regionId('cn-hongkong')
  6. ->asDefaultClient();
  7. class Demo {
  8. public function run() {
  9. try {
  10. $this->simplePush();
  11. } catch (\Exception $e) {
  12. }
  13. }
  14. public function simplePush() {
  15. $request = MPaaS::v20190821()->pushSimple();
  16. $result = $request->withAppId("ONEX570DA89211721")
  17. ->withWorkspaceId("test")
  18. ->withTitle("PHP test")
  19. ->withContent("Test 3")
  20. ->withDeliveryType(3)
  21. ->withTaskName("PHP test task")
  22. ->withExpiredSeconds(600)
  23. ->withTargetMsgkey(
  24. json_encode(["userid1024" => "".time() ]
  25. ))
  26. // endpoint
  27. ->host("mpaas.cn-hongkong.aliyuncs.com")
  28. // Specify whether to enable the debug mode
  29. ->debug(true)
  30. ->request();
  31. }
  32. }

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 {\”fixedTime\”:1630303126000,\”startTime\”:1625673600000,\”endTime\”:1630303126000,\”circleType\”:1,\”circleValue\”:[1, 7],\”time\”:\”13:45:11\”} 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.

 
  1. DefaultProfile.addEndpoint("cn-hongkong", "mpaas", "mpaas.cn-hongkong.aliyuncs.com");
  2. // Create a DefaultAcsClient instance and initialize it.
  3. DefaultProfile profile = DefaultProfile.getProfile(
  4. "cn-hangzhou", // region ID
  5. "******", // The AccessKey ID of the RAM account
  6. "******"); // The AccessKey secret of the RAM account
  7. IAcsClient client = new DefaultAcsClient(profile);
  8. // Create an API request and set parameters
  9. PushTemplateRequest request = new PushTemplateRequest();
  10. request.setAppId("ONEX570DA89211721");
  11. request.setWorkspaceId("test");
  12. request.setTemplateName("testTemplate");
  13. // Hello #name#. Congratulations to you for winning RMB #money#.
  14. Map<String,String> templatekv = new HashMap<String, String>();
  15. templatekv.put("name"," Bob");
  16. templatekv.put("money","200");
  17. request.setTemplateKeyValue(JSON.toJSONString(templatekv));
  18. request.setExpiredSeconds(600L);
  19. request.setTaskName("templateTest");
  20. request.setDeliveryType(3L);
  21. Map<String,String> target = new HashMap<String, String>();
  22. String msgKey = String.valueOf(System.currentTimeMillis());
  23. target.put("userid1024",msgKey);
  24. request.setTargetMsgkey(JSON.toJSONString(target));
  25. request.setStrategyType(2);
  26. request.setStrategyContent("{\"fixedTime\":1630303126000,\"startTime\":1625673600000,\"endTime\":1630303126000,\"circleType\":1,\"circleValue\":[1, 7],\"time\":\"13:45:11\"}");
  27. PushTemplateResponse response;
  28. try {
  29. response = client.getAcsResponse(request);
  30. System.out.println(response.getResultCode());
  31. System.out.println(response.getResultMessage());
  32. } catch (ClientException e) {
  33. e.printStackTrace();
  34. }

Python sample code

 
  1. from aliyunsdkcore.client import AcsClient
  2. from aliyunsdkmpaas.request.v20190821 import PushTemplateRequest
  3. import json
  4. import time
  5. # Initialize AcsClient instance
  6. client = AcsClient(
  7. "AccessKey ID",
  8. "AccessKey Secret",
  9. "cn-hongkong"
  10. );
  11. # Initialize a request and set parameters
  12. request = PushTemplateRequest.PushTemplateRequest()
  13. request.set_endpoint("mpaas.cn-hongkong.aliyuncs.com")
  14. request.set_AppId("ONEX570DA89211721")
  15. request.set_WorkspaceId("test")
  16. request.set_TemplateName("template1024")
  17. templatekv = {"name":"Bob","money":"200"}
  18. request.set_TemplateKeyValue(json.dumps(templatekv))
  19. request.set_DeliveryType(3)
  20. request.set_TaskName("The test task of Python template push")
  21. request.set_ExpiredSeconds(600)
  22. target = {"userid1024":str(time.time())}
  23. request.set_TargetMsgkey(json.dumps(target))
  24. # Print response
  25. response = client.do_action_with_exception(request)
  26. print response

Node.js sample code

 
  1. const sdk = require('@alicloud/mpaas20190821');
  2. const { default: Client, PushTemplateRequest } = sdk;
  3. // Create a client.
  4. const client = new Client({
  5. accessKeyId: 'accessKeyId',
  6. accessKeySecret: 'accessKeySecret',
  7. endpoint: 'mpaas.cn-hongkong.aliyuncs.com',
  8. apiVersion: '2019-08-21'
  9. });
  10. // Initialize the request.
  11. const request = new PushTemplateRequest();
  12. request.appId = "ONEX570DA89211721";
  13. request.workspaceId = "test";
  14. request.templateName= "template1024";
  15. const templatekv = {
  16. name: 'Bob',
  17. money:'300'
  18. };
  19. request.templateKeyValue = JSON.stringify(templatekv);
  20. request.deliveryType = 3;
  21. request.taskName = "Node test task";
  22. request.expiredSeconds=600;
  23. const extendedParam = {
  24. test: 'Custom extension parameter'
  25. };
  26. request.extendedParams = JSON.stringify(extendedParam);
  27. const target = {
  28. "userid1024": String(new Date().valueOf())
  29. };
  30. request.targetMsgkey = JSON.stringify(target);
  31. // Call the API operation.
  32. try {
  33. client.pushTemplate(request).then(res => {
  34. console.log('SUCCESS', res);
  35. }).catch(e => {
  36. console.log('FAIL', e);
  37. });
  38. } catch(e) {
  39. console.log('ERROR', e);
  40. }

PHP sample code

 
  1. <?php
  2. use AlibabaCloud\Client\AlibabaCloud;
  3. use AlibabaCloud\MPaaS\MPaaS;
  4. AlibabaCloud::accessKeyClient('accessKeyId', 'accessKeySecret')
  5. ->regionId('cn-hongkong')
  6. ->asDefaultClient();
  7. class Demo {
  8. public function run() {
  9. try {
  10. $this->templatePush();
  11. } catch (\Exception $e) {
  12. }
  13. }
  14. public function templatePush() {
  15. $request = MPaaS::v20190821()->pushTemplate();
  16. $result = $request->host("mpaas.cn-hongkong.aliyuncs.com")
  17. // Specify whether to enable the debug mode.
  18. ->debug(true)
  19. ->withAppId("ONEX570DA89211721")
  20. ->withWorkspaceId("test")
  21. ->withTemplateName("template1024")
  22. ->withTemplateKeyValue(json_encode(["name" => "Bob", "money" => "200"]))
  23. ->withDeliveryType(3)
  24. ->withTaskName("PHP test task")
  25. ->withExpiredSeconds(600)
  26. ->withTargetMsgkey(
  27. json_encode(["userid1024" => "".time() ])
  28. )
  29. ->request();
  30. }
  31. }

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 {\”fixedTime\”:1630303126000,\”startTime\”:1625673600000,\”endTime\”:1630303126000,\”circleType\”:1,\”circleValue\”:[1, 7],\”time\”:\”13:45:11\”} 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
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.

 
  1. DefaultProfile.addEndpoint("cn-hongkong", "mpaas", "mpaas.cn-hongkong.aliyuncs.com");
  2. // Create a DefaultAcsClient instance and initialize it
  3. DefaultProfile profile = DefaultProfile.getProfile(
  4. "cn-hangzhou", // Region ID
  5. "******", // The AccessKey ID of the RAM account
  6. "******"); // he AccessKey secret of the RAM account
  7. IAcsClient client = new DefaultAcsClient(profile);
  8. // Create an API request and set parameters
  9. PushMultipleRequest request = new PushMultipleRequest();
  10. request.setAppId("ONEX570DA89211721");
  11. request.setWorkspaceId("test");
  12. request.setDeliveryType(3L);
  13. request.setTaskName("multipleTest");
  14. request.setTemplateName("testTemplate");
  15. // Hello #name#. Congratulations to you for winning RMB #money#.
  16. List<PushMultipleRequest.TargetMsg> targetMsgs = new ArrayList<PushMultipleRequest.TargetMsg>();
  17. PushMultipleRequest.TargetMsg targetMsg = new PushMultipleRequest.TargetMsg();
  18. targetMsg.setTarget("userid1024");
  19. targetMsg.setMsgKey(String.valueOf(System.currentTimeMillis()));
  20. Map<String, String> templatekv = new HashMap<String, String>();
  21. templatekv.put("name", "Bob");
  22. templatekv.put("money", "200");
  23. targetMsg.setTemplateKeyValue(JSON.toJSONString(templatekv));
  24. // The number of TargetMsg objects can be up to 400
  25. targetMsgs.add(targetMsg);
  26. request.setTargetMsgs(targetMsgs);
  27. request.setExpiredSeconds(600L);
  28. request.setStrategyType(2);
  29. request.setStrategyContent("{\"fixedTime\":1630303126000,\"startTime\":1625673600000,\"endTime\":1630303126000,\"circleType\":1,\"circleValue\":[1, 7],\"time\":\"13:45:11\"}");
  30. PushMultipleResponse response;
  31. try {
  32. response = client.getAcsResponse(request);
  33. System.out.println(response.getResultCode());
  34. System.out.println(response.getResultMessage());
  35. System.out.println(response.getPushResult().getData()); // Push task ID or scheduled push task ID
  36. } catch (ClientException e) {
  37. e.printStackTrace();
  38. }

Python sample code

 
  1. # -*- coding: utf8 -*-
  2. from aliyunsdkcore.client import AcsClient
  3. from aliyunsdkmpaas.request.v20190821 import PushMultipleRequest
  4. import json
  5. import time
  6. # Initialize AcsClient instance
  7. client = AcsClient(
  8. "AccessKey ID",
  9. "AccessKey Secret",
  10. "cn-hongkong"
  11. );
  12. # Initialize a request and set parameters
  13. request = PushMultipleRequest.PushMultipleRequest()
  14. request.set_endpoint("mpaas.cn-hongkong.aliyuncs.com")
  15. request.set_AppId("ONEX570DA89211721")
  16. request.set_WorkspaceId("test")
  17. request.set_TemplateName("template1024")
  18. request.set_DeliveryType(3)
  19. request.set_TaskName("The test task of Python template push")
  20. request.set_ExpiredSeconds(600)
  21. msgkey = str(time.time())
  22. targets = [
  23. {
  24. "Target": "user1024",
  25. "MsgKey": msgkey,
  26. "TemplateKeyValue": {
  27. "name": "Bob",
  28. "money": "200"
  29. }
  30. }
  31. ]
  32. request.set_TargetMsgs(targets)
  33. # Print response
  34. response = client.do_action_with_exception(request)
  35. print response

Node.js sample code

 
  1. const sdk = require('@alicloud/mpaas20190821');
  2. const { default: Client, PushMultipleRequest,PushMultipleRequestTargetMsg } = sdk;
  3. // Create a client
  4. const client = new Client({
  5. accessKeyId: 'accessKeyId',
  6. accessKeySecret: 'AccessKey Secret',
  7. endpoint: 'mpaas.cn-hongkong.aliyuncs.com',
  8. apiVersion: '2019-08-21'
  9. });
  10. // Initialize request
  11. const request = new PushMultipleRequest();
  12. request.appId = "ONEX570DA89211721";
  13. request.workspaceId = "test";
  14. request.templateName= "template1024";
  15. const templatekv = {
  16. name: 'Bob',
  17. money:'300'
  18. };
  19. //request.templateKeyValue = JSON.stringify(templatekv);
  20. request.deliveryType = 3;
  21. request.taskName = "Node test task";
  22. request.expiredSeconds=600;
  23. const extendedParam = {
  24. test: 'Custom extension parameter'
  25. };
  26. request.extendedParams = JSON.stringify(extendedParam);
  27. const targetMsgkey = new PushMultipleRequestTargetMsg();
  28. targetMsgkey.target = "userid1024";
  29. targetMsgkey.msgKey = String(new Date().valueOf());
  30. targetMsgkey.templateKeyValue = JSON.stringify(templatekv);;
  31. request.targetMsg = [targetMsgkey];
  32. // Call the API operation.
  33. try {
  34. client.pushMultiple(request).then(res => {
  35. console.log('SUCCESS', res);
  36. }).catch(e => {
  37. console.log('FAIL', e);
  38. });
  39. } catch(e) {
  40. console.log('ERROR', e);
  41. }

PHP sample code

 
  1. <?php
  2. use AlibabaCloud\Client\AlibabaCloud;
  3. use AlibabaCloud\MPaaS\MPaaS;
  4. AlibabaCloud::accessKeyClient('accessKeyId', 'accessKeySecret')
  5. ->regionId('cn-hongkong')
  6. ->asDefaultClient();
  7. class Demo {
  8. public function run() {
  9. try {
  10. $this->multiPush();
  11. } catch (\Exception $e) {
  12. }
  13. }
  14. public function multiPush() {
  15. $request = MPaaS::v20190821()->pushMultiple();
  16. $result = $request->host("mpaas.cn-hongkong.aliyuncs.com")
  17. // Specify whether to enable the debug mode
  18. ->debug(true)
  19. ->withAppId("ONEX570DA89211721")
  20. ->withWorkspaceId("test")
  21. ->withTemplateName("template1024")
  22. ->withDeliveryType(3)
  23. ->withTaskName("The test task of PHP multiple push")
  24. ->withExpiredSeconds(600)
  25. ->withTargetMsg(
  26. [
  27. [
  28. "Target" => "userid1024",
  29. "MsgKey" => "" . time(),
  30. "TemplateKeyValue" => json_encode([
  31. "name" => "Bob",
  32. "money" => "200",
  33. ])
  34. ]
  35. ]
  36. )
  37. ->request();
  38. }
  39. }

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 {\”fixedTime\”:1630303126000,\”startTime\”:1625673600000,\”endTime\”:1630303126000,\”circleType\”:1,\”circleValue\”:[1, 7],\”time\”:\”13:45:11\”} 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.

 
  1. DefaultProfile.addEndpoint("cn-hongkong", "mpaas", "mpaas.cn-hongkong.aliyuncs.com");
  2. // Create a DefaultAcsClient instance and initialize it
  3. DefaultProfile profile = DefaultProfile.getProfile(
  4. "cn-hangzhou", // Region ID
  5. "******", // The AccessKey ID of the RAM account
  6. "******"); // The AccessKey Secret of the RAM account
  7. IAcsClient client = new DefaultAcsClient(profile);
  8. PushBroadcastRequest request = new PushBroadcastRequest();
  9. request.setAppId("ONEX570DA89211720");
  10. request.setWorkspaceId("test");
  11. request.setDeliveryType(2L);
  12. request.setMsgkey(String.valueOf(System.currentTimeMillis()));
  13. request.setExpiredSeconds(600L);
  14. request.setTaskName("broadcastTest ");
  15. request.setTemplateName("broadcastTemplate ");
  16. // This is an announcement: #content#.
  17. Map<String, String> templatekv = new HashMap<String, String>();
  18. templatekv.put("content", " The content of the announcement ");
  19. request.setTemplateKeyValue(JSON.toJSONString(templatekv));
  20. request.setStrategyType(2);
  21. request.setStrategyContent("{\"fixedTime\":1630303126000,\"startTime\":1625673600000,\"endTime\":1630303126000,\"circleType\":1,\"circleValue\":[1, 7],\"time\":\"13:45:11\"}");
  22. PushBroadcastResponse response;
  23. try {
  24. response = client.getAcsResponse(request);
  25. System.out.println(response.getResultCode());
  26. System.out.println(response.getResultMessage());
  27. System.out.println(response.getPushResult().getData()); // push task ID or scheduled task ID
  28. } catch (ClientException e) {
  29. e.printStackTrace();
  30. }

Python sample code

 
  1. # -*- coding: utf8 -*-
  2. from aliyunsdkcore.client import AcsClient
  3. from aliyunsdkmpaas.request.v20190821 import PushBroadcastRequest
  4. import json
  5. import time
  6. # Initialize AcsClient instance
  7. client = AcsClient(
  8. "AccessKey ID",
  9. "AccessKey Secret",
  10. "cn-hongkong"
  11. );
  12. # Initialize a request and set parameters
  13. request = PushBroadcastRequest.PushBroadcastRequest()
  14. request.set_endpoint("mpaas.cn-hongkong.aliyuncs.com")
  15. request.set_AppId("ONEX570DA89211720")
  16. request.set_WorkspaceId("test")
  17. request.set_TemplateName("broadcastTemplate")
  18. templatekv = {"content":"This is an announcement"}
  19. request.set_TemplateKeyValue(json.dumps(templatekv))
  20. request.set_DeliveryType(1)
  21. request.set_TaskName("The test task of Python broadcast push")
  22. request.set_ExpiredSeconds(600)
  23. request.set_Msgkey(str(time.time()))
  24. # Print response
  25. response = client.do_action_with_exception(request)
  26. print response

Node.js sample code

 
  1. const sdk = require('@alicloud/mpaas20190821');
  2. const { default: Client, PushBroadcastRequest } = sdk;
  3. // Create a client.
  4. const client = new Client({
  5. accessKeyId: 'accessKeyId',
  6. accessKeySecret: 'AccessKey Secret',
  7. endpoint: 'mpaas.cn-hongkong.aliyuncs.com',
  8. apiVersion: '2019-08-21'
  9. });
  10. // Initialize the request.
  11. const request = new PushBroadcastRequest();
  12. request.appId = "ONEX570DA89211720";
  13. request.workspaceId = "test";
  14. request.templateName= "broadcastTemplate";
  15. const templatekv = {
  16. content: 'This is an announcement',
  17. };
  18. request.templateKeyValue = JSON.stringify(templatekv);
  19. request.deliveryType = 1;
  20. request.taskName = "Node test task";
  21. request.expiredSeconds=600;
  22. const extendedParam = {
  23. test: 'Custom extension parameter'
  24. };
  25. request.extendedParams = JSON.stringify(extendedParam);
  26. request.msgkey = String(new Date().valueOf())
  27. // Call the API operation.
  28. try {
  29. client.pushBroadcast(request).then(res => {
  30. console.log('SUCCESS', res);
  31. }).catch(e => {
  32. console.log('FAIL', e);
  33. });
  34. } catch(e) {
  35. console.log('ERROR', e);
  36. }

PHP sample code

 
  1. <?php
  2. use AlibabaCloud\Client\AlibabaCloud;
  3. use AlibabaCloud\MPaaS\MPaaS;
  4. AlibabaCloud::accessKeyClient('accessKeyId', 'accessKeySecret')
  5. ->regionId('cn-hongkong')
  6. ->asDefaultClient();
  7. class Demo {
  8. public function run() {
  9. try {
  10. $this->broadcastPush();
  11. } catch (\Exception $e) {
  12. }
  13. }
  14. public function broadcastPush(){
  15. $request = MPaaS::v20190821()->pushBroadcast();
  16. $result = $request->host("mpaas.cn-hongkong.aliyuncs.com")
  17. // Specify whether to enable the debug mode.
  18. ->debug(true)
  19. ->withAppId("ONEX570DA89211720")
  20. ->withWorkspaceId("test")
  21. ->withTemplateName("broadcastTemplate")
  22. ->withTemplateKeyValue(
  23. json_encode(["content" => "This is an announcement"])
  24. )
  25. ->withDeliveryType(1)
  26. ->withTaskName("The test task of PHP broadcast push")
  27. ->withExpiredSeconds(600)
  28. ->withMsgkey("". time())
  29. ->request();
  30. }
  31. }

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

 
  1. DefaultProfile.addEndpoint("cn-hongkong", "mpaas", "mpaas.cn-hongkong.aliyuncs.com");
  2. // Create a DefaultAcsClient instance and initialize it
  3. DefaultProfile profile = DefaultProfile.getProfile(
  4. "cn-hangzhou", // Region ID
  5. "******", // The AccessKey ID of the RAM account
  6. "******"); // The AccessKey Secret of the RAM account
  7. IAcsClient client = new DefaultAcsClient(profile);
  8. RevokePushMessageRequest request = new RevokePushMessageRequest();
  9. request.setAppId("ONEX570DA89211720");
  10. request.setWorkspaceId("test");
  11. request.setMessageId("console_1624516744112"); // Message ID in business system
  12. request.setTargetId("mpaas_push_demo"); // Target ID
  13. RevokePushMessageResponse response;
  14. try {
  15. response = client.getAcsResponse(request);
  16. System.out.println(response.getResultCode());
  17. System.out.println(response.getResultMessage());
  18. } catch (ClientException e) {
  19. e.printStackTrace();
  20. }

Revoke by task ID

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

Request parameters

Parameter Data type Required Example Description
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

 
  1. DefaultProfile.addEndpoint("cn-hongkong", "mpaas", "mpaas.cn-hongkong.aliyuncs.com");
  2. // Create a DefaultAcsClient instance and initialize it
  3. DefaultProfile profile = DefaultProfile.getProfile(
  4. "cn-hangzhou", // Region ID
  5. "******", // The AccessKey ID of the RAM account
  6. "******"); // The AccessKey Secret of the RAM account
  7. IAcsClient client = new DefaultAcsClient(profile);
  8. RevokePushTaskRequest request = new RevokePushTaskRequest();
  9. request.setAppId("ONEX570DA89211720");
  10. request.setWorkspaceId("test");
  11. request.setTaskId("20842863"); // Push task ID
  12. RevokePushTaskResponse response;
  13. try {
  14. response = client.getAcsResponse(request);
  15. System.out.println(response.getResultCode());
  16. System.out.println(response.getResultMessage());
  17. } catch (ClientException e) {
  18. e.printStackTrace();
  19. }

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

 
  1. DefaultProfile.addEndpoint("cn-hongkong", "mpaas", "mpaas.cn-hongkong.aliyuncs.com");
  2. // Create a DefaultAcsClient instance and initialize it
  3. DefaultProfile profile = DefaultProfile.getProfile(
  4. "cn-hangzhou", // Region ID
  5. "******", // The AccessKey ID of the RAM account
  6. "******"); // The AccessKey Secret of the RAM account
  7. IAcsClient client = new DefaultAcsClient(profile);
  8. QueryPushAnalysisCoreIndexRequest request = new QueryPushAnalysisCoreIndexRequest();
  9. request.setAppId("ONEX570DA89211720");
  10. request.setWorkspaceId("test");
  11. request.setStartTime(Long.valueOf("1617206400000"));
  12. request.setEndTime(Long.valueOf("1624982400000"));
  13. request.setPlatform("ANDROID");
  14. request.setChannel("ANDROID");
  15. request.setType("SIMPLE");
  16. request.setTaskId("20842863");
  17. QueryPushAnalysisCoreIndexResponse response;
  18. try {
  19. response = client.getAcsResponse(request);
  20. System.out.println(response.getResultCode());
  21. System.out.println(response.getResultMessage());
  22. } catch (ClientException e) {
  23. e.printStackTrace();
  24. }

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

 
  1. DefaultProfile.addEndpoint("cn-hongkong", "mpaas", "mpaas.cn-hongkong.aliyuncs.com");
  2. // Create a DefaultAcsClient instance and initialize it
  3. DefaultProfile profile = DefaultProfile.getProfile(
  4. "cn-hangzhou", // Region ID
  5. "******", // The AccessKey ID of the RAM account
  6. "******"); // The AccessKey Secret of the RAM account
  7. IAcsClient client = new DefaultAcsClient(profile);
  8. QueryPushAnalysisTaskListRequest request = new QueryPushAnalysisTaskListRequest();
  9. request.setAppId("ONEX570DA89211721");
  10. request.setWorkspaceId("default");
  11. request.setStartTime(Long.valueOf("1617206400000"));
  12. request.setTaskId("20845212");
  13. request.setTaskName("Tesk task");
  14. request.setPageNumber(1);
  15. request.setPageSize(10);
  16. QueryPushAnalysisTaskListResponse response;
  17. try {
  18. response = client.getAcsResponse(request);
  19. System.out.println(response.getResultCode());
  20. System.out.println(response.getResultMessage());
  21. } catch (ClientException e) {
  22. e.printStackTrace();
  23. }

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

 
  1. DefaultProfile.addEndpoint("cn-hongkong", "mpaas", "mpaas.cn-hongkong.aliyuncs.com");
  2. // Create a DefaultAcsClient instance and initialize it
  3. DefaultProfile profile = DefaultProfile.getProfile(
  4. "cn-hangzhou", // Region ID
  5. "******", // The AccessKey ID of the RAM account
  6. "******"); // The AccessKey Secret of the RAM account
  7. IAcsClient client = new DefaultAcsClient(profile);
  8. QueryPushAnalysisTaskDetailRequest request = new QueryPushAnalysisTaskDetailRequest();
  9. request.setAppId("ONEXPREF4F5C52081557");
  10. request.setWorkspaceId("default");
  11. request.setTaskId("20845212");
  12. QueryPushAnalysisTaskDetailResponse response;
  13. try {
  14. response = client.getAcsResponse(request);
  15. System.out.println(response.getResultCode());
  16. System.out.println(response.getResultMessage());
  17. } catch (ClientException e) {
  18. e.printStackTrace();
  19. }

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

 
  1. DefaultProfile.addEndpoint("cn-hongkong", "mpaas", "mpaas.cn-hongkong.aliyuncs.com");
  2. // Create a DefaultAcsClient instance and initialize it
  3. DefaultProfile profile = DefaultProfile.getProfile(
  4. "cn-hangzhou", // Region ID
  5. "******", // The AccessKey ID of the RAM account
  6. "******"); // The AccessKey Secret of the RAM account
  7. IAcsClient client = new DefaultAcsClient(profile);
  8. QueryPushSchedulerListRequest request = new QueryPushSchedulerListRequest();
  9. request.setAppId("ONEXPREF4F5C52081557");
  10. request.setWorkspaceId("default");
  11. request.setStartTime(Long.valueOf("1625068800000"));
  12. request.setEndTime(Long.valueOf("1630425600000"));
  13. request.setType(0);
  14. request.setUniqueId("49ec0ed5a2a642bcbe139a2d7a419d6d");
  15. request.setPageNumber(1);
  16. request.setPageSize(10);
  17. QueryPushSchedulerListResponse response;
  18. try {
  19. response = client.getAcsResponse(request);
  20. System.out.println(response.getResultCode());
  21. System.out.println(response.getResultMessage());
  22. } catch (ClientException e) {
  23. e.printStackTrace();
  24. }

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

 
  1. DefaultProfile.addEndpoint("cn-hongkong", "mpaas", "mpaas.cn-hongkong.aliyuncs.com");
  2. // Create a DefaultAcsClient instance and initialize it
  3. DefaultProfile profile = DefaultProfile.getProfile(
  4. "cn-hangzhou", // Region ID
  5. "******", // The AccessKey ID of the RAM account
  6. "******"); // The AccessKey Secret of the RAM account
  7. IAcsClient client = new DefaultAcsClient(profile);
  8. CancelPushSchedulerRequest request = new CancelPushSchedulerRequest();
  9. request.setAppId("ONEXPREF4F5C52081557");
  10. request.setWorkspaceId("default");
  11. request.setUniqueIds("49ec0ed5a2a642bcbe139a2d7a419d6d, 49ec0ed5a2a642bcbe139a2d7a419d6c");
  12. CancelPushSchedulerResponse response;
  13. try {
  14. response = client.getAcsResponse(request);
  15. System.out.println(response.getResultCode());
  16. System.out.println(response.getResultMessage());
  17. } catch (ClientException e) {
  18. e.printStackTrace();
  19. }

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.