Template push

更新时间:
复制 MD 格式

Push a message to a single target ID using a template. Multiple IDs can share the same template.

Before you call this API:

  • Create the target template in the Message Push console. For more information, see Create a template.

  • Import the SDK dependencies. For more information, see Server-side API.

Request parameters

Parameter name

Type

Required

Example

Description

classification

String

No

1

Vivo push channel message type:

  • 0: Operational messages

  • 1: System messages

Default: 1.

taskName

String

Yes

Template test

Push task name.

appId

String

Yes

ONEX570DA89211721

The mPaaS App ID.

workspaceId

String

Yes

test

The mPaaS workspace.

deliveryType

Long

Yes

3

Target ID type:

  • 1: Android device dimension

  • 2: iOS device dimension

  • 3: User dimension

  • 5: Live Activity pushToken

  • 6: Live Activity activityId

  • 7: HarmonyOS device dimension

targetMsgkey

String

Yes

{“user1024”:”1578807462788”}

Push target in map format:

  • key: Target ID. Behavior depends on 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 attach API.

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

  • value: Custom business ID. Must be unique.

Note

Maximum 10 targetMsgkey key-value pairs.

expiredSeconds

Long

Yes

300

Message TTL in seconds.

templateName

String

Yes

Test template

The template name. Create the template in the console.

Note

The template name cannot contain commas.

templateKeyValue

String

No

{"money": "200", "name": "Zhang San"}

Template parameters in map format for the template specified by templateName. Keys are placeholder names enclosed in # signs, and values are replacements. Example: Congratulations #name#, you won #money# USD.

extendedParams

String

No

{“key1”:”value1”}

Extended parameters in map format.

notifyType

String

No

Message channel type:

  • transparent: MPS self-built channel

  • notify: Default channel

strategyType

Integer

No

1

Push strategy type:

  • 0: Immediate

  • 1: Scheduled

  • 2: Loop

Default: 0.

StrategyContent

String

No

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

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 StrategyContent field description below.

transparentMessagePayload

Map<String, JSONObject>

No

-

The vendor pass-through message body.

  • key: The vendor channel type.

    • hms for Huawei channel

    • honor for Honor channel

    • fcm for Google Firebase channel

    • harmonyos for HarmonyOS channel

  • value: Pass-through message body sent to the vendor.

Pass-through message body format:

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

transparentMessageUrgency

String

No

-

Vendor pass-through message priority. Valid only when `transparentMessagePayload` is set.

Supported by Huawei, Honor, and HarmonyOS. Valid values: HIGH, NORMAL.

For Huawei and Honor:

  • HIGH: High-priority pass-through message

  • NORMAL or not set: 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

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}

SMS template variable values in JSON format.

thirdChannelCategory

Map

No

thirdChannelCategory: {

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

"vivo": "1"

// vivo: IM message type

}

Vendor message classification. For more information, see Vendor message classification.

notifyLevel

Map

No

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

Vendor notification level. OPPO levels:

  • 1: Notification bar

  • 2: Notification bar and lock screen

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

miChannelId

String

No

"123321"

Xiaomi push channel ID.

activityEvent

String

No

Live Activity event type:

  • update: Update event

  • end: End event

activityContentState

JSONObject

No

Live Activity content-state. Must match client-defined parameters.

dismissalDate

long

No

Live Activity expiration as a UNIX timestamp in seconds. Default: iOS system expiration of 12 hours.

Note

smsStrategy notes:

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

activityEvent notes:

  • The expiration time set by dismissalDate applies only when the value of activityEvent is `end`.

  • The expiration time set by dismissalDate does not apply when the value of activityEvent is `update`.

  • If end is sent without dismissalDate, iOS ends the Live Activity after 4 hours.

StrategyContent field description

Pass this value as a JSON string.

Parameter name

Type

Required

Example

Description

fixedTime

long

No

1630303126000

Scheduled push timestamp in milliseconds, accurate to the second. fixedTime is required when strategyType is 1.

startTime

long

No

1640966400000

Recurring cycle start timestamp in milliseconds, accurate to the day. startTime is required when strategyType is 2.

endTime

long

No

1672416000000

Recurring cycle end timestamp in milliseconds, accurate to the day. Cannot exceed 180 days from today. endTime is required when strategyType is 2.

circleType

int

No

3

Recurrence type:

  • 1: Daily

  • 2: Weekly

  • 3: Monthly

circleType is required when strategyType is 2.

circleValue

int[]

No

[1,3]

The recurring value:

  • If the recurring type is daily, this is empty.

  • If the recurring type is weekly, set the days of the week for the recurring push. For example, [1,3] means Monday and Wednesday.

  • If the recurring type is monthly, set the days of the month for the recurring push. For example, [1,3] means the 1st and 3rd of each month.

circleValue is required when strategyType is 2 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.

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

  • A recurring cycle runs from 00:00 on the start date to 24:00 on the end date.

  • The start time must be 00:00 of the current day or later. The end time must be the same as or later 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

Error description.

PushResult

JSON

The request result.

Success

boolean

true

Request status. Success is included in the PushResult JSON string.

ResultMsg

String

param is invalid

Error message. ResultMsg is included in the PushResult JSON string.

Data

String

903bf653c1b5442b9ba07684767bf9c2

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

Code examples

Your AccessKey requires the AliyunMPAASFullAccess permission. Control access to applications for RAM accounts.

Java code example

Click here to obtain the AccessKey ID and AccessKey secret.

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

public static void main(String[] args) throws Exception {
    // An Alibaba Cloud account AccessKey has full access to all APIs. We recommend that you use a RAM user for API calls and routine 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 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. The non-financial cloud region in Hangzhou is used as an example.
    config.setRegionId("cn-hangzhou");
    config.setEndpoint("mpaas.cn-hangzhou.aliyuncs.com");
    Client client = new Client(config);

    PushTemplateRequest request = new PushTemplateRequest();
    request.setAppId("ONEX570DA89211721");
    request.setWorkspaceId("test");
    request.setTenantId("xxx");
    request.setTemplateName("Test_Template_With_Placeholders");
    // Hello #name#, congratulations on winning #money# USD
    Map<String,String> templatekv = new HashMap<String, String>();
    templatekv.put("name","John Doe");
    templatekv.put("money","200");
    request.setTemplateKeyValue(JSON.toJSONString(templatekv));
    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));
    PushTemplateResponse pushTemplateResponse = client.pushTemplate(request);
    System.out.println("response==>"+JSON.toJSONString(pushTemplateResponse));
}

Python code example

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

        // An AccessKey of an Alibaba Cloud account has permissions to access all APIs. This poses a high security risk. We strongly recommend that you create and use a RAM user to call APIs or perform daily O&M. Log on to the RAM console to create a RAM user.
        // This example shows how to store your AccessKey and AccessKey secret in environment variables. You can also store them in a configuration file based on your business needs.
        // To prevent security risks, we strongly recommend that you do not hardcode the AccessKey and AccessKey secret in your code.
        // Before you run the sample code, configure the environment variables.
# Initialize AcsClient instance
String accessKeyId = System.getenv("MPAAS_AK_ENV");
String accessKeySecret = System.getenv("MPAAS_SK_ENV");
client = AcsClient(
accessKeyId,      
accessKeySecret, 
"cn-hangzhou"
);

# Initialize a request and set parameters
request = PushTemplateRequest.PushTemplateRequest()
request.set_endpoint("mpaas.cn-hangzhou.aliyuncs.com")
request.set_AppId("ONEX570DA89211721")
request.set_WorkspaceId("test")
request.set_TemplateName("template1024")
templatekv = {"name":"John Doe","money":"200"}
request.set_TemplateKeyValue(json.dumps(templatekv))
request.set_DeliveryType(3)
request.set_TaskName("Python template test task")
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 code example

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

const { default: Client, PushTemplateRequest } = sdk;
// Create a client.
// An AccessKey of an Alibaba Cloud account has permissions for all APIs, which poses a high security risk. We strongly recommend that you create and use a RAM user for API access or daily O&M. To create a RAM user, log on to the RAM console.
// This example shows how to store the AccessKey and AccessKey secret in environment variables. You can also store them in a configuration file based on your business needs.
// We strongly recommend that you do not hard-code the AccessKey and AccessKey secret in your code. This may cause security risks.
// We recommend that you configure the environment variables first.
String accessKeyId = System.getenv("MPAAS_AK_ENV");
String accessKeySecret = System.getenv("MPAAS_SK_ENV");
const client = new Client({
  accessKeyId,      
  accessKeySecret, 
  endpoint: 'mpaas.cn-hangzhou.aliyuncs.com',
  apiVersion: '2019-08-21'
});
// Initialize the request.
  const request = new PushTemplateRequest();
  request.appId = "ONEX570DA89211721";
  request.workspaceId = "test";
  request.templateName= "template1024";
  const templatekv = {
    name: 'Zhang San',
    money:'300'
  };
  request.templateKeyValue = JSON.stringify(templatekv);
  request.deliveryType = 3;
  request.taskName = "Node.js test task";
  request.expiredSeconds=600;
  const extendedParam = {
    test: 'Custom extended parameter'
  };
  request.extendedParams = JSON.stringify(extendedParam);
  const target = {
    "userid1024": String(new Date().valueOf())
  };
  request.targetMsgkey = JSON.stringify(target);

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

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