Simple push

更新时间:
复制 MD 格式

Push a message to one or more target devices or users by push ID.

Import the required dependencies before calling this API. SDK Preparation.

Request parameters

Parameter name

Type

Required

Example

Description

classification

String

No

1

The message type for the vivo push channel.

  • 0: Operational messages

  • 1: System messages

Default: 1.

taskName

String

Yes

simpleTest

Push task name.

title

String

Yes

Test

Message title.

content

String

Yes

Test

Message body.

appId

String

Yes

ONEX570DA89211721

The mPaaS App ID.

workspaceId

String

Yes

test

The mPaaS workspace.

deliveryType

Long

Yes

3

Target ID type. Valid values:

  • 1: Android device

  • 2: iOS device

  • 3: User

  • 5: Live Activity pushToken

  • 6: Live Activity activityId

  • 7: HarmonyOS device

targetMsgkey

String

Yes

{“user1024”:”1578807462788”}

Push target in map format.

  • key: The target. This parameter is used with deliveryType.

    • If deliveryType is 1, the key is the Android device ID.

    • If deliveryType is 2, the key is the iOS device ID.

    • If deliveryType is 3, the key is the user ID. This is the userid value passed when the user calls the binding API.

    • If deliveryType is 7, the key is the HarmonyOS device ID.

  • value: The business ID of the message. This is a custom ID and must be unique.

Note

The targetMsgkey parameter supports a maximum of 10 key-value pairs.

expiredSeconds

Long

Yes

300

Message validity period, in seconds.

pushStyle

Integer

Yes

0

The push style.

  • 0: Default

  • 1: Big text

  • 2: Image and text

extendedParams

String

No

{“key1”:”value1”}

Extended parameters in map format.

pushAction

Long

No

0

Action when a message is clicked.

  • 0: Web URL

  • 1: Intent Activity

Default: Web URL.

uri

String

No

http://www

Redirect URL when the message is clicked.

silent

Long

No

1

Whether to send a silent push.

  • 1: Silent

  • 0: Not silent

notifyType

String

No

The message channel type.

  • transparent: MPS self-built channel

  • notify: Default channel

imageUrls

String

No

{\”defaultUrl\”:\”https://mpaas.oss-cn-hangzhou.aliyuncs.com/tmp/test.png\",\"oppoUrl\":\"https://mpaas.oss-cn-hangzhou.aliyuncs.com/tmp/test.png\",\"miuiUrl\":\"https://mpaas.oss-cn-hangzhou.aliyuncs.com/tmp/test.png\",\"fcmUrl\":\"https://mpaas.oss-cn-hangzhou.aliyuncs.com/tmp/test.png\",\"iosUrl\":\"https://mpaas.oss-cn-hangzhou.aliyuncs.com/tmp/test.png\"}

Large image URL in JSON format. Supported by OPPO, HMS, MIUI, FCM, and iOS channels. Use defaultUrl as the fallback.

iconUrls

String

No

{\”defaultUrl\”:\”https://mpaas.oss-cn-hangzhou.aliyuncs.com/tmp/test.png\",\"hmsUrl\":\"https://mpaas.oss-cn-hangzhou.aliyuncs.com/tmp/test.png\",\"oppoUrl\":\"https://mpaas.oss-cn-hangzhou.aliyuncs.com/tmp/test.png\",\"miuiUrl\":\"https://mpaas.oss-cn-hangzhou.aliyuncs.com/tmp/test.png\"}

Icon URL in JSON format. Supported by OPPO, HMS, MIUI, FCM, and iOS channels. Use defaultUrl as the fallback.

strategyType

Integer

No

1

The push policy type.

  • 0: Immediate

  • 1: Scheduled

  • 2: Recurring

Default: 0.

StrategyContent

String

No

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

The details of the push policy in a JSON string. This parameter is required when strategyType is not 0. For more information about the parameters, see the StrategyContent field description section below.

transparentMessagePayload

Map<String, JSONObject>

No

-

The pass-through message body for the vendor channel.

  • key: The vendor channel type.

    • For the Huawei channel, use hms.

    • For the Honor channel, use honor.

    • For the Google Firebase channel, use fcm.

    • For the HarmonyOS channel, use harmonyos.

  • value: The pass-through message body. This value is used as the pass-through message body sent to the vendor.

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

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

transparentMessageUrgency

String

No

-

The priority of the vendor pass-through message. This parameter is valid only when `transparentMessagePayload` is set.

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

For Huawei and Honor:

  • HIGH: high-priority pass-through message.

  • NORMAL or unspecified: normal-priority pass-through message.

For HarmonyOS:

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

  • NORMAL: The current message is a background message.

smsStrategy

int

No

2

The SMS policy.

  • 0: None (default)

  • 1: Resend

  • 2: Concurrent

smsSignName

String

No

mPaaS Test

The SMS signature.

smsTemplateCode

String

No

SMS_216070269

The SMS template ID.

smsTemplateParam

String

No

{\"code\": 123456}

The actual values for the variables in the SMS template, in JSON format.

thirdChannelCategory

Map

No

thirdChannelCategory: {

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

"vivo": "1"

// vivo: IM message

}

Vendor message category. Vendor message categories.

notifyLevel

Map

No

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

The notification level for vendor messages. For example, the OPPO message levels are as follows:

  • 1: Notification bar

  • 2: Notification bar and lock screen

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

miChannelId

String

No

"123321"

The channelId for the Xiaomi push channel.

activityEvent

String

No

The Live Activity event. Valid values are update or end.

  • update: Update event

  • end: End event

activityContentState

JSONObject

No

The content-state of the Live Activity message. This must be consistent with the parameters defined on the client.

dismissalDate

long

No

The expiration time for the Live Activity message as a UNIX timestamp in seconds. This is an optional field. If not specified, the default iOS system expiration time of 12 hours is used.

Note

Notes on the smsStrategy parameter:

  • If the value of smsStrategy is not 0, the smsSignName, smsTemplateCode, and smsTemplateParam parameters are required.

Notes on the activityEvent parameter:

  • When the activityEvent is an `end` event, the expiration time that is configured in dismissalDate is applied.

  • When the activityEvent is an `update` event, the expiration time that is configured in dismissalDate is ignored.

  • If you send an `end` event but do not specify a value for dismissalDate, the iOS system ends the Live Activity after 4 hours by default.

StrategyContent field description

Convert the JSON value to a string before passing it.

Parameter Name

Type

Required

Example

Description

fixedTime

long

No

1630303126000

The timestamp for the scheduled push in milliseconds, accurate to the second. fixedTime is required when strategyType is 1 (scheduled).

startTime

long

No

1640966400000

Start timestamp of the recurring period in milliseconds (day-level precision). startTime is required when strategyType is 2 (recurring).

endTime

long

No

1672416000000

End timestamp of the recurring period in milliseconds (day-level precision). Must be within 180 days of today. endTime is required when strategyType is 2 (recurring).

circleType

int

No

3

The recurrence type.

  • 1: Daily

  • 2: Weekly

  • 3: Monthly

circleType is required when strategyType is 2 (recurring).

circleValue

int[]

No

[1,3]

The recurrence value.

  • If the recurrence type is daily: empty.

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

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

circleValue is required when strategyType is 2 (recurring) and circleType is not daily.

time

String

No

09:45:11

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

Note
  • Maximum unexecuted scheduled or recurring push tasks: 100.

  • The recurring period spans from 00:00 on the start date to 24:00 on the end date.

  • The start time and end time cannot be earlier than 00:00 on the current day. The end time cannot be earlier than the start time.

Response parameters

Parameter Name

Type

Example

Description

RequestId

String

B589F4F4-CD68-3CE5-BDA0-6597F33E23916512

The request ID.

ResultCode

String

OK

The result code of the request.

ResultMessage

String

param is invalid

The error description of the request.

PushResult

JSON

The result of the request.

Success

boolean

true

The request status. The Success parameter is included in the PushRresult JSON string.

ResultMsg

String

param is invalid

The error details of the request. The ResultMsg parameter is included in the PushRresult JSON string.

Data

String

903bf653c1b5442b9ba07684767bf9c2

The ID of the scheduled push task. This field is not empty when strategyType is not 0.

Code examples

Your AccessKey must have the `AliyunMPAASFullAccess` permission. Control access to applications for RAM accounts.

Java code example

Obtain an AccessKey pair for the code examples below.

import com.alibaba.fastjson.JSON;
import com.aliyun.mpaas20201028.Client;
import com.aliyun.mpaas20201028.models.PushSimpleRequest;
import com.aliyun.mpaas20201028.models.PushSimpleResponse;
import com.aliyun.teaopenapi.models.Config;
import java.util.HashMap;
import java.util.Map;

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

    PushSimpleRequest request = new PushSimpleRequest();
    request.setAppId("ONEX570DA89211721");
    request.setWorkspaceId("test");
    request.setTenantId("xxx");
    request.setTitle("Simple Test Title");
    request.setContent("Simple Test Content");
    request.setExpiredSeconds(180L);
    request.setTaskName("-");
    request.setDeliveryType(3L);
    Map<String,String> targetMsgkey = new HashMap<>();
    String msgKey = String.valueOf(System.currentTimeMillis());
    targetMsgkey.put("push_test",msgKey);
    request.setTargetMsgkey(JSON.toJSONString(targetMsgkey));
    System.out.println("request==>"+JSON.toJSONString(request));
    PushSimpleResponse pushSimpleResponse = client.pushSimple(request);
    System.out.println("response==>"+JSON.toJSONString(pushSimpleResponse));
}

Python code example

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

# WARNING: AccessKey has full access to all APIs. Use RAM users instead. Save credentials in environment variables.
# For more information, see RAM User Security Best Practices in the console.
# Never store AccessKey or AccessKey secret in code to avoid key leaks.
# We recommend that you configure the environment variables first.
accessKeyId = System.getenv("MPAAS_AK_ENV")
accessKeySecret = System.getenv("MPAAS_SK_ENV")
# Initialize AcsClient instance
client = AcsClient(
"cn-hangzhou",
accessKeyId,      
accessKeySecret 
);

# Initialize a request and set parameters
request = PushSimpleRequest.PushSimpleRequest()
request.set_endpoint("mpaas.cn-hangzhou.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("Python Test Task")
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 code example

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

const { default: Client, PushSimpleRequest } = sdk;
// Create a client.
// Your Alibaba Cloud account AccessKey has full access to all APIs, which poses a high security risk. We strongly recommend that you create and use a RAM user for API calls and daily O&M. Log on to the RAM console to create a RAM user.
// This example shows how to save the AccessKey and AccessKey secret in environment variables. You can also save them in a configuration file as needed.
// We strongly recommend that you do not save the AccessKey and AccessKey secret in your code. This can lead to a key leak.
// We recommend that you configure the environment variables first.
const accessKeyId = System.getenv("MPAAS_AK_ENV");
const accessKeySecret = System.getenv("MPAAS_SK_ENV");
const client = new Client({
  accessKeyId,      
  accessKeySecret, 
  endpoint: 'mpaas.cn-hangzhou.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 extended parameter'
  };
  request.extendedParams = JSON.stringify(extendedParam);
// The value is the business message ID. Make sure it is unique.
  const target = {
    "userid1024": String(new Date().valueOf())
  };
  request.targetMsgkey = JSON.stringify(target);

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

PHP code example

<?php

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

class Demo {
    public function run() {
        try {
               $this->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-hangzhou.aliyuncs.com")
            // Specifies whether to enable debug mode.
            ->debug(true)
            ->request();
    }
}