SmsReport

更新时间:
复制 MD 格式

You can use a message queue to receive SMS delivery status reports (SmsReport), which are delivery receipts for messages sent using the SendSms and SendBatchSms API operations.

Prerequisites

SmsReport message body format

Parameter

Type

Example

Description

send_time

String

2021-09-06 15:49:55

The time when the message was forwarded to the carrier.

report_time

String

2021-09-06 15:49:58

The time when the delivery receipt was received from the carrier.

success

Boolean

true

Indicates whether the message was delivered successfully. Valid values:

  • true: The message was delivered successfully.

  • false: The message failed to be delivered.

err_msg

String

The user received the message.

The description of the status code.

err_code

String

DELIVERED

The status code from the carrier. For successful deliveries, this is often DELIVERED.

phone_number

String

159****6532

The recipient's phone number.

sms_size

String

1

The length of the SMS message. For details on how message length is calculated, see SMS sending rules.

biz_id

String

12345

The delivery receipt ID, also known as the delivery serial number.

This is the BizId returned in the response when you call the SendSms or SendBatchSms API operation. For batch messages, a single BizId is returned for the entire batch. The BizId is unique for each request under the same Alibaba Cloud account.

  • You use this ID to query the delivery status by calling the QuerySendDetails API operation.

  • You can also view the delivery status in the SMS console on the Business Statistics > Delivery Records page.

out_id

String

123456

The custom outId that you specified when calling the SendSms API operation.

Download the demo

See Lightweight Message Queue (formerly MNS) consumer demo to download the demo and SDK for your preferred programming language. This topic uses Java as an example.

Note
  • After you download the demo, the lib directory contains the required JAR packages. Import them by clicking Add as Library.

  • You can find the Maven dependencies in the pom.xml file and install the Alibaba Cloud SDK for Java.

Configure parameters

Before using the sample code, configure the following parameters.

Access key

Note

To prevent your AccessKey from being leaked, obtain it by configuring an environment variable instead of hard-coding it in your code. For more information, see Configure environment variables on Linux, macOS, and Windows systems.

This topic uses ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET as the names of the environment variables. The following code shows how to obtain an access key from environment variables:

String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");

Message type

Replace messageType with the type of message you want to receive, such as SmsReport for delivery receipts. For a list of supported receipt message types, see Configure delivery receipts.

String messageType="<MESSAGE_TYPE>";

Queue name

Replace queueName with the name of your message queue. You can find the queue name in the SMS console by navigating to the General Settings > Receipt Configuration > Status Reports page.

String queueName="<QUEUE_NAME>";

On this page, in the Domestic Messages section, the Queue Name field under the Message Service (MNS) Consumer Mode shows your message queue name. The format is Alicom-Queue-xxx.

Complete example

The dealMessage method processes the status reports you receive. You can add your business logic for handling these reports within this method.

// Parse the message body based on the message format in the documentation.
String arg = (String) contentMap.get("arg");
// Add your business logic here.

The arg parameter represents a field in the receipt message body. Valid values include: send_time, report_time, success, err_msg, err_code, phone_number, sms_size, biz_id, and out_id.

package com.alicom.mns.sample;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.alicom.mns.tools.DefaultAlicomMessagePuller;
import com.alicom.mns.tools.MessageListener;
import com.aliyun.mns.model.Message;
import com.google.gson.Gson;
/**
 * This demo is for receiving messages from Alibaba Cloud Communications services only. It cannot be used for other services.
 */
public class ReceiveDemo {
    private static Log logger=LogFactory.getLog(ReceiveDemo.class);
    static class MyMessageListener implements MessageListener{
        private Gson gson=new Gson();
        @Override
        public boolean dealMessage(Message message) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            // Key values of the message
            System.out.println("message receiver time from mns:" + format.format(new Date()));
            System.out.println("message handle: " + message.getReceiptHandle());
            System.out.println("message body: " + message.getMessageBodyAsString());
            System.out.println("message id: " + message.getMessageId());
            System.out.println("message dequeue count:" + message.getDequeueCount());
            System.out.println("Thread:" + Thread.currentThread().getName());
            try{
                Map<String,Object> contentMap=gson.fromJson(message.getMessageBodyAsString(), HashMap.class);
                // Parse the message body based on the message format in the documentation.
                String arg = (String) contentMap.get("arg");
                // Add your business logic here.
            }catch(com.google.gson.JsonSyntaxException e){
                logger.error("error_json_format:"+message.getMessageBodyAsString(),e);
                // JSON format errors should not occur. If they do, delete the message to prevent it from being redelivered and causing repeated errors.
                return true;
            } catch (Throwable e) {
                // If an exception occurs in your business logic, return false. This prevents the message from being deleted and allows it to be redelivered according to the retry policy.
                return false;
            }
            // If the message is processed successfully, return true. The SDK will then delete the message from the queue.
            return true;
        }
    }
    public static void main(String[] args) throws Exception, ParseException {
        DefaultAlicomMessagePuller puller=new DefaultAlicomMessagePuller();
        // Set the asynchronous thread pool size, task queue size, and idle thread sleep time.
        puller.setConsumeMinThreadSize(6);
        puller.setConsumeMaxThreadSize(16);
        puller.setThreadQueueSize(200);
        puller.setPullMsgThreadSize(1);
        // Enable this for server-side debugging. Keep it disabled during normal operation to improve performance.
        puller.openDebugLog(false);
        // Obtain the AccessKey ID and AccessKey secret from local environment variables.
        String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
        String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
        /*
        *  Replace messageType and queueName with your message type and queue name.
        *  Supported message types for Alibaba Cloud Communications services:
        *  1. SMS delivery receipt: SmsReport,
        *  2. Inbound SMS message: SmsUp,
        *  3. International SMS delivery receipt: GlobeSmsReport
        */
        String messageType="<MESSAGE_TYPE>"; // Replace this with the message type for your product.
        String queueName="<QUEUE_NAME>"; // The queue name is available on the console page after you enable message queuing. The format is similar to Alicom-Queue-******-SmsUp.
        puller.startReceiveMsg(accessKeyId,accessKeySecret,messageType,queueName,new MyMessageListener());
    }
}

The following is sample output from running the demo.

/Library/Java/JavaVirtualMachines/jdk1.8.0_291.jdk/Contents/Home/bin/java ...
Connected to the target VM, address: '127.0.0.1:62393', transport: 'socket'
14:00:07.056 [PullMessageTask-thread-0] DEBUG com.aliyun.mns.client.CloudAccount - initiated CloudAccount, accessId: xxx                    accessKey= xxx
message receiver time from mns: xxx
message handle: xxx
message body: xxx
message id: xxx
message dequeue count:1
Thread:pool-1-thread-1